babylon.max.js 3.6 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176
  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 = ""; }
  5317. var destination = creationFunction();
  5318. // Tags
  5319. if (BABYLON.Tags) {
  5320. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5321. }
  5322. var classStore = getMergedStore(destination);
  5323. // Properties
  5324. for (var property in classStore) {
  5325. var propertyDescriptor = classStore[property];
  5326. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5327. var propertyType = propertyDescriptor.type;
  5328. if (sourceProperty !== undefined && sourceProperty !== null) {
  5329. var dest = destination;
  5330. switch (propertyType) {
  5331. case 0:// Value
  5332. dest[property] = sourceProperty;
  5333. break;
  5334. case 1:// Texture
  5335. if (scene) {
  5336. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5337. }
  5338. break;
  5339. case 2:// Color3
  5340. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  5341. break;
  5342. case 3:// FresnelParameters
  5343. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5344. break;
  5345. case 4:// Vector2
  5346. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5347. break;
  5348. case 5:// Vector3
  5349. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5350. break;
  5351. case 6:// Mesh reference
  5352. if (scene) {
  5353. dest[property] = scene.getLastMeshByID(sourceProperty);
  5354. }
  5355. break;
  5356. case 7:// Color Curves
  5357. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5358. break;
  5359. case 8:// Color 4
  5360. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  5361. break;
  5362. case 9:// Image Processing
  5363. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5364. break;
  5365. }
  5366. }
  5367. }
  5368. return destination;
  5369. };
  5370. SerializationHelper.Clone = function (creationFunction, source) {
  5371. return _copySource(creationFunction, source, false);
  5372. };
  5373. SerializationHelper.Instanciate = function (creationFunction, source) {
  5374. return _copySource(creationFunction, source, true);
  5375. };
  5376. return SerializationHelper;
  5377. }());
  5378. BABYLON.SerializationHelper = SerializationHelper;
  5379. })(BABYLON || (BABYLON = {}));
  5380. //# sourceMappingURL=babylon.decorators.js.map
  5381. var BABYLON;
  5382. (function (BABYLON) {
  5383. /**
  5384. * A class serves as a medium between the observable and its observers
  5385. */
  5386. var EventState = /** @class */ (function () {
  5387. /**
  5388. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5389. */
  5390. function EventState(mask, skipNextObservers, target, currentTarget) {
  5391. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5392. this.initalize(mask, skipNextObservers, target, currentTarget);
  5393. }
  5394. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  5395. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5396. this.mask = mask;
  5397. this.skipNextObservers = skipNextObservers;
  5398. this.target = target;
  5399. this.currentTarget = currentTarget;
  5400. return this;
  5401. };
  5402. return EventState;
  5403. }());
  5404. BABYLON.EventState = EventState;
  5405. /**
  5406. * Represent an Observer registered to a given Observable object.
  5407. */
  5408. var Observer = /** @class */ (function () {
  5409. function Observer(callback, mask, scope) {
  5410. if (scope === void 0) { scope = null; }
  5411. this.callback = callback;
  5412. this.mask = mask;
  5413. this.scope = scope;
  5414. }
  5415. return Observer;
  5416. }());
  5417. BABYLON.Observer = Observer;
  5418. /**
  5419. * Represent a list of observers registered to multiple Observables object.
  5420. */
  5421. var MultiObserver = /** @class */ (function () {
  5422. function MultiObserver() {
  5423. }
  5424. MultiObserver.prototype.dispose = function () {
  5425. if (this._observers && this._observables) {
  5426. for (var index = 0; index < this._observers.length; index++) {
  5427. this._observables[index].remove(this._observers[index]);
  5428. }
  5429. }
  5430. this._observers = null;
  5431. this._observables = null;
  5432. };
  5433. MultiObserver.Watch = function (observables, callback, mask, scope) {
  5434. if (mask === void 0) { mask = -1; }
  5435. if (scope === void 0) { scope = null; }
  5436. var result = new MultiObserver();
  5437. result._observers = new Array();
  5438. result._observables = observables;
  5439. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  5440. var observable = observables_1[_i];
  5441. var observer = observable.add(callback, mask, false, scope);
  5442. if (observer) {
  5443. result._observers.push(observer);
  5444. }
  5445. }
  5446. return result;
  5447. };
  5448. return MultiObserver;
  5449. }());
  5450. BABYLON.MultiObserver = MultiObserver;
  5451. /**
  5452. * The Observable class is a simple implementation of the Observable pattern.
  5453. * 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.
  5454. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5455. * 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).
  5456. * 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.
  5457. */
  5458. var Observable = /** @class */ (function () {
  5459. function Observable(onObserverAdded) {
  5460. this._observers = new Array();
  5461. this._eventState = new EventState(0);
  5462. if (onObserverAdded) {
  5463. this._onObserverAdded = onObserverAdded;
  5464. }
  5465. }
  5466. /**
  5467. * Create a new Observer with the specified callback
  5468. * @param callback the callback that will be executed for that Observer
  5469. * @param mask the mask used to filter observers
  5470. * @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.
  5471. * @param scope optional scope for the callback to be called from
  5472. */
  5473. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  5474. if (mask === void 0) { mask = -1; }
  5475. if (insertFirst === void 0) { insertFirst = false; }
  5476. if (scope === void 0) { scope = null; }
  5477. if (!callback) {
  5478. return null;
  5479. }
  5480. var observer = new Observer(callback, mask, scope);
  5481. if (insertFirst) {
  5482. this._observers.unshift(observer);
  5483. }
  5484. else {
  5485. this._observers.push(observer);
  5486. }
  5487. if (this._onObserverAdded) {
  5488. this._onObserverAdded(observer);
  5489. }
  5490. return observer;
  5491. };
  5492. /**
  5493. * Remove an Observer from the Observable object
  5494. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5495. */
  5496. Observable.prototype.remove = function (observer) {
  5497. if (!observer) {
  5498. return false;
  5499. }
  5500. var index = this._observers.indexOf(observer);
  5501. if (index !== -1) {
  5502. this._observers.splice(index, 1);
  5503. return true;
  5504. }
  5505. return false;
  5506. };
  5507. /**
  5508. * Remove a callback from the Observable object
  5509. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5510. */
  5511. Observable.prototype.removeCallback = function (callback) {
  5512. for (var index = 0; index < this._observers.length; index++) {
  5513. if (this._observers[index].callback === callback) {
  5514. this._observers.splice(index, 1);
  5515. return true;
  5516. }
  5517. }
  5518. return false;
  5519. };
  5520. /**
  5521. * Notify all Observers by calling their respective callback with the given data
  5522. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5523. * @param eventData
  5524. * @param mask
  5525. */
  5526. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  5527. if (mask === void 0) { mask = -1; }
  5528. var state = this._eventState;
  5529. state.mask = mask;
  5530. state.target = target;
  5531. state.currentTarget = currentTarget;
  5532. state.skipNextObservers = false;
  5533. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5534. var obs = _a[_i];
  5535. if (obs.mask & mask) {
  5536. if (obs.scope) {
  5537. obs.callback.apply(obs.scope, [eventData, state]);
  5538. }
  5539. else {
  5540. obs.callback(eventData, state);
  5541. }
  5542. }
  5543. if (state.skipNextObservers) {
  5544. return false;
  5545. }
  5546. }
  5547. return true;
  5548. };
  5549. /**
  5550. * Notify a specific observer
  5551. * @param eventData
  5552. * @param mask
  5553. */
  5554. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  5555. if (mask === void 0) { mask = -1; }
  5556. var state = this._eventState;
  5557. state.mask = mask;
  5558. state.skipNextObservers = false;
  5559. observer.callback(eventData, state);
  5560. };
  5561. /**
  5562. * return true is the Observable has at least one Observer registered
  5563. */
  5564. Observable.prototype.hasObservers = function () {
  5565. return this._observers.length > 0;
  5566. };
  5567. /**
  5568. * Clear the list of observers
  5569. */
  5570. Observable.prototype.clear = function () {
  5571. this._observers = new Array();
  5572. this._onObserverAdded = null;
  5573. };
  5574. /**
  5575. * Clone the current observable
  5576. */
  5577. Observable.prototype.clone = function () {
  5578. var result = new Observable();
  5579. result._observers = this._observers.slice(0);
  5580. return result;
  5581. };
  5582. /**
  5583. * Does this observable handles observer registered with a given mask
  5584. * @param {number} trigger - the mask to be tested
  5585. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5586. **/
  5587. Observable.prototype.hasSpecificMask = function (mask) {
  5588. if (mask === void 0) { mask = -1; }
  5589. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5590. var obs = _a[_i];
  5591. if (obs.mask & mask || obs.mask === mask) {
  5592. return true;
  5593. }
  5594. }
  5595. return false;
  5596. };
  5597. return Observable;
  5598. }());
  5599. BABYLON.Observable = Observable;
  5600. })(BABYLON || (BABYLON = {}));
  5601. //# sourceMappingURL=babylon.observable.js.map
  5602. var BABYLON;
  5603. (function (BABYLON) {
  5604. var SmartArray = /** @class */ (function () {
  5605. function SmartArray(capacity) {
  5606. this.length = 0;
  5607. this._duplicateId = 0;
  5608. this.data = new Array(capacity);
  5609. this._id = SmartArray._GlobalId++;
  5610. }
  5611. SmartArray.prototype.push = function (value) {
  5612. this.data[this.length++] = value;
  5613. if (this.length > this.data.length) {
  5614. this.data.length *= 2;
  5615. }
  5616. if (!value.__smartArrayFlags) {
  5617. value.__smartArrayFlags = {};
  5618. }
  5619. value.__smartArrayFlags[this._id] = this._duplicateId;
  5620. };
  5621. SmartArray.prototype.forEach = function (func) {
  5622. for (var index = 0; index < this.length; index++) {
  5623. func(this.data[index]);
  5624. }
  5625. };
  5626. SmartArray.prototype.pushNoDuplicate = function (value) {
  5627. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5628. return false;
  5629. }
  5630. this.push(value);
  5631. return true;
  5632. };
  5633. SmartArray.prototype.sort = function (compareFn) {
  5634. this.data.sort(compareFn);
  5635. };
  5636. SmartArray.prototype.reset = function () {
  5637. this.length = 0;
  5638. this._duplicateId++;
  5639. };
  5640. SmartArray.prototype.dispose = function () {
  5641. this.reset();
  5642. if (this.data) {
  5643. this.data.length = 0;
  5644. this.data = [];
  5645. }
  5646. };
  5647. SmartArray.prototype.concat = function (array) {
  5648. if (array.length === 0) {
  5649. return;
  5650. }
  5651. if (this.length + array.length > this.data.length) {
  5652. this.data.length = (this.length + array.length) * 2;
  5653. }
  5654. for (var index = 0; index < array.length; index++) {
  5655. this.data[this.length++] = (array.data || array)[index];
  5656. }
  5657. };
  5658. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5659. if (array.length === 0) {
  5660. return;
  5661. }
  5662. if (this.length + array.length > this.data.length) {
  5663. this.data.length = (this.length + array.length) * 2;
  5664. }
  5665. for (var index = 0; index < array.length; index++) {
  5666. var item = (array.data || array)[index];
  5667. this.pushNoDuplicate(item);
  5668. }
  5669. };
  5670. SmartArray.prototype.indexOf = function (value) {
  5671. var position = this.data.indexOf(value);
  5672. if (position >= this.length) {
  5673. return -1;
  5674. }
  5675. return position;
  5676. };
  5677. SmartArray.prototype.contains = function (value) {
  5678. return this.data.indexOf(value) !== -1;
  5679. };
  5680. // Statics
  5681. SmartArray._GlobalId = 0;
  5682. return SmartArray;
  5683. }());
  5684. BABYLON.SmartArray = SmartArray;
  5685. })(BABYLON || (BABYLON = {}));
  5686. //# sourceMappingURL=babylon.smartArray.js.map
  5687. var BABYLON;
  5688. (function (BABYLON) {
  5689. // Screenshots
  5690. var screenshotCanvas;
  5691. var cloneValue = function (source, destinationObject) {
  5692. if (!source)
  5693. return null;
  5694. if (source instanceof BABYLON.Mesh) {
  5695. return null;
  5696. }
  5697. if (source instanceof BABYLON.SubMesh) {
  5698. return source.clone(destinationObject);
  5699. }
  5700. else if (source.clone) {
  5701. return source.clone();
  5702. }
  5703. return null;
  5704. };
  5705. var Tools = /** @class */ (function () {
  5706. function Tools() {
  5707. }
  5708. ;
  5709. /**
  5710. * Interpolates between a and b via alpha
  5711. * @param a The lower value (returned when alpha = 0)
  5712. * @param b The upper value (returned when alpha = 1)
  5713. * @param alpha The interpolation-factor
  5714. * @return The mixed value
  5715. */
  5716. Tools.Mix = function (a, b, alpha) {
  5717. return a * (1 - alpha) + b * alpha;
  5718. };
  5719. Tools.Instantiate = function (className) {
  5720. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  5721. return Tools.RegisteredExternalClasses[className];
  5722. }
  5723. var arr = className.split(".");
  5724. var fn = (window || this);
  5725. for (var i = 0, len = arr.length; i < len; i++) {
  5726. fn = fn[arr[i]];
  5727. }
  5728. if (typeof fn !== "function") {
  5729. return null;
  5730. }
  5731. return fn;
  5732. };
  5733. Tools.SetImmediate = function (action) {
  5734. if (window.setImmediate) {
  5735. window.setImmediate(action);
  5736. }
  5737. else {
  5738. setTimeout(action, 1);
  5739. }
  5740. };
  5741. Tools.IsExponentOfTwo = function (value) {
  5742. var count = 1;
  5743. do {
  5744. count *= 2;
  5745. } while (count < value);
  5746. return count === value;
  5747. };
  5748. /**
  5749. * Find the next highest power of two.
  5750. * @param x Number to start search from.
  5751. * @return Next highest power of two.
  5752. */
  5753. Tools.CeilingPOT = function (x) {
  5754. x--;
  5755. x |= x >> 1;
  5756. x |= x >> 2;
  5757. x |= x >> 4;
  5758. x |= x >> 8;
  5759. x |= x >> 16;
  5760. x++;
  5761. return x;
  5762. };
  5763. /**
  5764. * Find the next lowest power of two.
  5765. * @param x Number to start search from.
  5766. * @return Next lowest power of two.
  5767. */
  5768. Tools.FloorPOT = function (x) {
  5769. x = x | (x >> 1);
  5770. x = x | (x >> 2);
  5771. x = x | (x >> 4);
  5772. x = x | (x >> 8);
  5773. x = x | (x >> 16);
  5774. return x - (x >> 1);
  5775. };
  5776. /**
  5777. * Find the nearest power of two.
  5778. * @param x Number to start search from.
  5779. * @return Next nearest power of two.
  5780. */
  5781. Tools.NearestPOT = function (x) {
  5782. var c = Tools.CeilingPOT(x);
  5783. var f = Tools.FloorPOT(x);
  5784. return (c - x) > (x - f) ? f : c;
  5785. };
  5786. Tools.GetExponentOfTwo = function (value, max, mode) {
  5787. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5788. var pot;
  5789. switch (mode) {
  5790. case BABYLON.Engine.SCALEMODE_FLOOR:
  5791. pot = Tools.FloorPOT(value);
  5792. break;
  5793. case BABYLON.Engine.SCALEMODE_NEAREST:
  5794. pot = Tools.NearestPOT(value);
  5795. break;
  5796. case BABYLON.Engine.SCALEMODE_CEILING:
  5797. default:
  5798. pot = Tools.CeilingPOT(value);
  5799. break;
  5800. }
  5801. return Math.min(pot, max);
  5802. };
  5803. Tools.GetFilename = function (path) {
  5804. var index = path.lastIndexOf("/");
  5805. if (index < 0)
  5806. return path;
  5807. return path.substring(index + 1);
  5808. };
  5809. Tools.GetDOMTextContent = function (element) {
  5810. var result = "";
  5811. var child = element.firstChild;
  5812. while (child) {
  5813. if (child.nodeType === 3) {
  5814. result += child.textContent;
  5815. }
  5816. child = child.nextSibling;
  5817. }
  5818. return result;
  5819. };
  5820. Tools.ToDegrees = function (angle) {
  5821. return angle * 180 / Math.PI;
  5822. };
  5823. Tools.ToRadians = function (angle) {
  5824. return angle * Math.PI / 180;
  5825. };
  5826. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5827. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5828. var output = "";
  5829. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5830. var i = 0;
  5831. var bytes = new Uint8Array(buffer);
  5832. while (i < bytes.length) {
  5833. chr1 = bytes[i++];
  5834. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5835. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5836. enc1 = chr1 >> 2;
  5837. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5838. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5839. enc4 = chr3 & 63;
  5840. if (isNaN(chr2)) {
  5841. enc3 = enc4 = 64;
  5842. }
  5843. else if (isNaN(chr3)) {
  5844. enc4 = 64;
  5845. }
  5846. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5847. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5848. }
  5849. return "data:image/png;base64," + output;
  5850. };
  5851. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5852. if (bias === void 0) { bias = null; }
  5853. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5854. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5855. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5856. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5857. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5858. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5859. }
  5860. if (bias) {
  5861. minimum.x -= minimum.x * bias.x + bias.y;
  5862. minimum.y -= minimum.y * bias.x + bias.y;
  5863. minimum.z -= minimum.z * bias.x + bias.y;
  5864. maximum.x += maximum.x * bias.x + bias.y;
  5865. maximum.y += maximum.y * bias.x + bias.y;
  5866. maximum.z += maximum.z * bias.x + bias.y;
  5867. }
  5868. return {
  5869. minimum: minimum,
  5870. maximum: maximum
  5871. };
  5872. };
  5873. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5874. if (bias === void 0) { bias = null; }
  5875. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5876. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5877. if (!stride) {
  5878. stride = 3;
  5879. }
  5880. for (var index = start; index < start + count; index++) {
  5881. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5882. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5883. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5884. }
  5885. if (bias) {
  5886. minimum.x -= minimum.x * bias.x + bias.y;
  5887. minimum.y -= minimum.y * bias.x + bias.y;
  5888. minimum.z -= minimum.z * bias.x + bias.y;
  5889. maximum.x += maximum.x * bias.x + bias.y;
  5890. maximum.y += maximum.y * bias.x + bias.y;
  5891. maximum.z += maximum.z * bias.x + bias.y;
  5892. }
  5893. return {
  5894. minimum: minimum,
  5895. maximum: maximum
  5896. };
  5897. };
  5898. Tools.Vector2ArrayFeeder = function (array) {
  5899. return function (index) {
  5900. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5901. var length = isFloatArray ? array.length / 2 : array.length;
  5902. if (index >= length) {
  5903. return null;
  5904. }
  5905. if (isFloatArray) {
  5906. var fa = array;
  5907. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5908. }
  5909. var a = array;
  5910. return a[index];
  5911. };
  5912. };
  5913. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5914. if (bias === void 0) { bias = null; }
  5915. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5916. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5917. var i = 0;
  5918. var cur = feeder(i++);
  5919. while (cur) {
  5920. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5921. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5922. cur = feeder(i++);
  5923. }
  5924. if (bias) {
  5925. minimum.x -= minimum.x * bias.x + bias.y;
  5926. minimum.y -= minimum.y * bias.x + bias.y;
  5927. maximum.x += maximum.x * bias.x + bias.y;
  5928. maximum.y += maximum.y * bias.x + bias.y;
  5929. }
  5930. return {
  5931. minimum: minimum,
  5932. maximum: maximum
  5933. };
  5934. };
  5935. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5936. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5937. return null;
  5938. return Array.isArray(obj) ? obj : [obj];
  5939. };
  5940. // Misc.
  5941. Tools.GetPointerPrefix = function () {
  5942. var eventPrefix = "pointer";
  5943. // Check if pointer events are supported
  5944. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  5945. eventPrefix = "mouse";
  5946. }
  5947. return eventPrefix;
  5948. };
  5949. /**
  5950. * @param func - the function to be called
  5951. * @param requester - the object that will request the next frame. Falls back to window.
  5952. */
  5953. Tools.QueueNewFrame = function (func, requester) {
  5954. if (!Tools.IsWindowObjectExist()) {
  5955. return setTimeout(func, 16);
  5956. }
  5957. if (!requester) {
  5958. requester = window;
  5959. }
  5960. if (requester.requestAnimationFrame) {
  5961. return requester.requestAnimationFrame(func);
  5962. }
  5963. else if (requester.msRequestAnimationFrame) {
  5964. return requester.msRequestAnimationFrame(func);
  5965. }
  5966. else if (requester.webkitRequestAnimationFrame) {
  5967. return requester.webkitRequestAnimationFrame(func);
  5968. }
  5969. else if (requester.mozRequestAnimationFrame) {
  5970. return requester.mozRequestAnimationFrame(func);
  5971. }
  5972. else if (requester.oRequestAnimationFrame) {
  5973. return requester.oRequestAnimationFrame(func);
  5974. }
  5975. else {
  5976. return window.setTimeout(func, 16);
  5977. }
  5978. };
  5979. Tools.RequestFullscreen = function (element) {
  5980. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5981. if (!requestFunction)
  5982. return;
  5983. requestFunction.call(element);
  5984. };
  5985. Tools.ExitFullscreen = function () {
  5986. if (document.exitFullscreen) {
  5987. document.exitFullscreen();
  5988. }
  5989. else if (document.mozCancelFullScreen) {
  5990. document.mozCancelFullScreen();
  5991. }
  5992. else if (document.webkitCancelFullScreen) {
  5993. document.webkitCancelFullScreen();
  5994. }
  5995. else if (document.msCancelFullScreen) {
  5996. document.msCancelFullScreen();
  5997. }
  5998. };
  5999. Tools.SetCorsBehavior = function (url, img) {
  6000. if (Tools.CorsBehavior) {
  6001. switch (typeof (Tools.CorsBehavior)) {
  6002. case "function":
  6003. var result = Tools.CorsBehavior(url);
  6004. if (result) {
  6005. img.crossOrigin = result;
  6006. }
  6007. break;
  6008. case "string":
  6009. default:
  6010. img.crossOrigin = Tools.CorsBehavior;
  6011. break;
  6012. }
  6013. }
  6014. };
  6015. // External files
  6016. Tools.CleanUrl = function (url) {
  6017. url = url.replace(/#/mg, "%23");
  6018. return url;
  6019. };
  6020. Tools.LoadImage = function (url, onLoad, onError, database) {
  6021. if (url instanceof ArrayBuffer) {
  6022. url = Tools.EncodeArrayBufferTobase64(url);
  6023. }
  6024. url = Tools.CleanUrl(url);
  6025. url = Tools.PreprocessUrl(url);
  6026. var img = new Image();
  6027. if (url.substr(0, 5) !== "data:") {
  6028. Tools.SetCorsBehavior(url, img);
  6029. }
  6030. img.onload = function () {
  6031. onLoad(img);
  6032. };
  6033. img.onerror = function (err) {
  6034. Tools.Error("Error while trying to load image: " + url);
  6035. if (Tools.UseFallbackTexture) {
  6036. img.src = Tools.fallbackTexture;
  6037. onLoad(img);
  6038. }
  6039. else {
  6040. onError("Error while trying to load image: " + url, err);
  6041. }
  6042. };
  6043. var noIndexedDB = function () {
  6044. img.src = url;
  6045. };
  6046. var loadFromIndexedDB = function () {
  6047. if (database) {
  6048. database.loadImageFromDB(url, img);
  6049. }
  6050. };
  6051. //ANY database to do!
  6052. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6053. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6054. }
  6055. else {
  6056. if (url.indexOf("file:") !== 0) {
  6057. noIndexedDB();
  6058. }
  6059. else {
  6060. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  6061. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  6062. try {
  6063. var blobURL;
  6064. try {
  6065. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  6066. }
  6067. catch (ex) {
  6068. // Chrome doesn't support oneTimeOnly parameter
  6069. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  6070. }
  6071. img.src = blobURL;
  6072. }
  6073. catch (e) {
  6074. img.src = "";
  6075. }
  6076. }
  6077. else {
  6078. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  6079. img.src = Tools.fallbackTexture;
  6080. }
  6081. }
  6082. }
  6083. return img;
  6084. };
  6085. //ANY
  6086. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  6087. url = Tools.CleanUrl(url);
  6088. url = Tools.PreprocessUrl(url);
  6089. var request;
  6090. var noIndexedDB = function () {
  6091. request = new XMLHttpRequest();
  6092. var loadUrl = Tools.BaseUrl + url;
  6093. request.open('GET', loadUrl, true);
  6094. if (useArrayBuffer) {
  6095. request.responseType = "arraybuffer";
  6096. }
  6097. if (progressCallBack) {
  6098. request.onprogress = progressCallBack;
  6099. }
  6100. request.onreadystatechange = function () {
  6101. // In case of undefined state in some browsers.
  6102. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  6103. request.onreadystatechange = function () { }; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  6104. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  6105. callback(!useArrayBuffer ? request.responseText : request.response);
  6106. }
  6107. else {
  6108. var e = new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  6109. if (onError) {
  6110. onError(request, e);
  6111. }
  6112. else {
  6113. throw e;
  6114. }
  6115. }
  6116. }
  6117. };
  6118. request.send(null);
  6119. };
  6120. var loadFromIndexedDB = function () {
  6121. if (database) {
  6122. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6123. }
  6124. };
  6125. if (url.indexOf("file:") !== -1) {
  6126. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  6127. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6128. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6129. }
  6130. else {
  6131. var errorMessage = "File: " + fileName + " not found. Did you forget to provide it?";
  6132. if (onError) {
  6133. var e = new Error(errorMessage);
  6134. onError(undefined, e);
  6135. }
  6136. else {
  6137. Tools.Error(errorMessage);
  6138. }
  6139. }
  6140. }
  6141. else {
  6142. // Caching all files
  6143. if (database && database.enableSceneOffline) {
  6144. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6145. }
  6146. else {
  6147. noIndexedDB();
  6148. }
  6149. }
  6150. return request;
  6151. };
  6152. /**
  6153. * Load a script (identified by an url). When the url returns, the
  6154. * content of this file is added into a new script element, attached to the DOM (body element)
  6155. */
  6156. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6157. var head = document.getElementsByTagName('head')[0];
  6158. var script = document.createElement('script');
  6159. script.type = 'text/javascript';
  6160. script.src = scriptUrl;
  6161. script.onload = function () {
  6162. if (onSuccess) {
  6163. onSuccess();
  6164. }
  6165. };
  6166. script.onerror = function (e) {
  6167. if (onError) {
  6168. onError("Unable to load script", e);
  6169. }
  6170. };
  6171. head.appendChild(script);
  6172. };
  6173. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6174. var reader = new FileReader();
  6175. reader.onload = function (e) {
  6176. //target doesn't have result from ts 1.3
  6177. callback(e.target['result']);
  6178. };
  6179. reader.onprogress = progressCallback;
  6180. reader.readAsDataURL(fileToLoad);
  6181. };
  6182. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6183. var reader = new FileReader();
  6184. reader.onerror = function (e) {
  6185. Tools.Log("Error while reading file: " + fileToLoad.name);
  6186. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6187. };
  6188. reader.onload = function (e) {
  6189. //target doesn't have result from ts 1.3
  6190. callback(e.target['result']);
  6191. };
  6192. if (progressCallBack) {
  6193. reader.onprogress = progressCallBack;
  6194. }
  6195. if (!useArrayBuffer) {
  6196. // Asynchronous read
  6197. reader.readAsText(fileToLoad);
  6198. }
  6199. else {
  6200. reader.readAsArrayBuffer(fileToLoad);
  6201. }
  6202. };
  6203. //returns a downloadable url to a file content.
  6204. Tools.FileAsURL = function (content) {
  6205. var fileBlob = new Blob([content]);
  6206. var url = window.URL || window.webkitURL;
  6207. var link = url.createObjectURL(fileBlob);
  6208. return link;
  6209. };
  6210. // Misc.
  6211. Tools.Format = function (value, decimals) {
  6212. if (decimals === void 0) { decimals = 2; }
  6213. return value.toFixed(decimals);
  6214. };
  6215. Tools.CheckExtends = function (v, min, max) {
  6216. if (v.x < min.x)
  6217. min.x = v.x;
  6218. if (v.y < min.y)
  6219. min.y = v.y;
  6220. if (v.z < min.z)
  6221. min.z = v.z;
  6222. if (v.x > max.x)
  6223. max.x = v.x;
  6224. if (v.y > max.y)
  6225. max.y = v.y;
  6226. if (v.z > max.z)
  6227. max.z = v.z;
  6228. };
  6229. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6230. for (var prop in source) {
  6231. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6232. continue;
  6233. }
  6234. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6235. continue;
  6236. }
  6237. var sourceValue = source[prop];
  6238. var typeOfSourceValue = typeof sourceValue;
  6239. if (typeOfSourceValue === "function") {
  6240. continue;
  6241. }
  6242. if (typeOfSourceValue === "object") {
  6243. if (sourceValue instanceof Array) {
  6244. destination[prop] = [];
  6245. if (sourceValue.length > 0) {
  6246. if (typeof sourceValue[0] == "object") {
  6247. for (var index = 0; index < sourceValue.length; index++) {
  6248. var clonedValue = cloneValue(sourceValue[index], destination);
  6249. if (destination[prop].indexOf(clonedValue) === -1) {
  6250. destination[prop].push(clonedValue);
  6251. }
  6252. }
  6253. }
  6254. else {
  6255. destination[prop] = sourceValue.slice(0);
  6256. }
  6257. }
  6258. }
  6259. else {
  6260. destination[prop] = cloneValue(sourceValue, destination);
  6261. }
  6262. }
  6263. else {
  6264. destination[prop] = sourceValue;
  6265. }
  6266. }
  6267. };
  6268. Tools.IsEmpty = function (obj) {
  6269. for (var i in obj) {
  6270. if (obj.hasOwnProperty(i)) {
  6271. return false;
  6272. }
  6273. }
  6274. return true;
  6275. };
  6276. Tools.RegisterTopRootEvents = function (events) {
  6277. for (var index = 0; index < events.length; index++) {
  6278. var event = events[index];
  6279. window.addEventListener(event.name, event.handler, false);
  6280. try {
  6281. if (window.parent) {
  6282. window.parent.addEventListener(event.name, event.handler, false);
  6283. }
  6284. }
  6285. catch (e) {
  6286. // Silently fails...
  6287. }
  6288. }
  6289. };
  6290. Tools.UnregisterTopRootEvents = function (events) {
  6291. for (var index = 0; index < events.length; index++) {
  6292. var event = events[index];
  6293. window.removeEventListener(event.name, event.handler);
  6294. try {
  6295. if (window.parent) {
  6296. window.parent.removeEventListener(event.name, event.handler);
  6297. }
  6298. }
  6299. catch (e) {
  6300. // Silently fails...
  6301. }
  6302. }
  6303. };
  6304. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6305. if (mimeType === void 0) { mimeType = "image/png"; }
  6306. // Read the contents of the framebuffer
  6307. var numberOfChannelsByLine = width * 4;
  6308. var halfHeight = height / 2;
  6309. //Reading datas from WebGL
  6310. var data = engine.readPixels(0, 0, width, height);
  6311. //To flip image on Y axis.
  6312. for (var i = 0; i < halfHeight; i++) {
  6313. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6314. var currentCell = j + i * numberOfChannelsByLine;
  6315. var targetLine = height - i - 1;
  6316. var targetCell = j + targetLine * numberOfChannelsByLine;
  6317. var temp = data[currentCell];
  6318. data[currentCell] = data[targetCell];
  6319. data[targetCell] = temp;
  6320. }
  6321. }
  6322. // Create a 2D canvas to store the result
  6323. if (!screenshotCanvas) {
  6324. screenshotCanvas = document.createElement('canvas');
  6325. }
  6326. screenshotCanvas.width = width;
  6327. screenshotCanvas.height = height;
  6328. var context = screenshotCanvas.getContext('2d');
  6329. if (context) {
  6330. // Copy the pixels to a 2D canvas
  6331. var imageData = context.createImageData(width, height);
  6332. var castData = (imageData.data);
  6333. castData.set(data);
  6334. context.putImageData(imageData, 0, 0);
  6335. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6336. }
  6337. };
  6338. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6339. if (mimeType === void 0) { mimeType = "image/png"; }
  6340. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6341. if (successCallback) {
  6342. successCallback(base64Image);
  6343. }
  6344. else {
  6345. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6346. if (("download" in document.createElement("a"))) {
  6347. var a = window.document.createElement("a");
  6348. a.href = base64Image;
  6349. var date = new Date();
  6350. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6351. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6352. window.document.body.appendChild(a);
  6353. a.addEventListener("click", function () {
  6354. if (a.parentElement) {
  6355. a.parentElement.removeChild(a);
  6356. }
  6357. });
  6358. a.click();
  6359. //Or opening a new tab with the image if it is not possible to automatically start download.
  6360. }
  6361. else {
  6362. var newWindow = window.open("");
  6363. var img = newWindow.document.createElement("img");
  6364. img.src = base64Image;
  6365. newWindow.document.body.appendChild(img);
  6366. }
  6367. }
  6368. };
  6369. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6370. if (mimeType === void 0) { mimeType = "image/png"; }
  6371. var width;
  6372. var height;
  6373. // If a precision value is specified
  6374. if (size.precision) {
  6375. width = Math.round(engine.getRenderWidth() * size.precision);
  6376. height = Math.round(width / engine.getAspectRatio(camera));
  6377. }
  6378. else if (size.width && size.height) {
  6379. width = size.width;
  6380. height = size.height;
  6381. }
  6382. else if (size.width && !size.height) {
  6383. width = size.width;
  6384. height = Math.round(width / engine.getAspectRatio(camera));
  6385. }
  6386. else if (size.height && !size.width) {
  6387. height = size.height;
  6388. width = Math.round(height * engine.getAspectRatio(camera));
  6389. }
  6390. else if (!isNaN(size)) {
  6391. height = size;
  6392. width = size;
  6393. }
  6394. else {
  6395. Tools.Error("Invalid 'size' parameter !");
  6396. return;
  6397. }
  6398. if (!screenshotCanvas) {
  6399. screenshotCanvas = document.createElement('canvas');
  6400. }
  6401. screenshotCanvas.width = width;
  6402. screenshotCanvas.height = height;
  6403. var renderContext = screenshotCanvas.getContext("2d");
  6404. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6405. var newWidth = width;
  6406. var newHeight = newWidth / ratio;
  6407. if (newHeight > height) {
  6408. newHeight = height;
  6409. newWidth = newHeight * ratio;
  6410. }
  6411. var offsetX = Math.max(0, width - newWidth) / 2;
  6412. var offsetY = Math.max(0, height - newHeight) / 2;
  6413. var renderingCanvas = engine.getRenderingCanvas();
  6414. if (renderContext && renderingCanvas) {
  6415. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  6416. }
  6417. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6418. };
  6419. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6420. if (mimeType === void 0) { mimeType = "image/png"; }
  6421. if (samples === void 0) { samples = 1; }
  6422. var width;
  6423. var height;
  6424. //If a precision value is specified
  6425. if (size.precision) {
  6426. width = Math.round(engine.getRenderWidth() * size.precision);
  6427. height = Math.round(width / engine.getAspectRatio(camera));
  6428. size = { width: width, height: height };
  6429. }
  6430. else if (size.width && size.height) {
  6431. width = size.width;
  6432. height = size.height;
  6433. }
  6434. else if (size.width && !size.height) {
  6435. width = size.width;
  6436. height = Math.round(width / engine.getAspectRatio(camera));
  6437. size = { width: width, height: height };
  6438. }
  6439. else if (size.height && !size.width) {
  6440. height = size.height;
  6441. width = Math.round(height * engine.getAspectRatio(camera));
  6442. size = { width: width, height: height };
  6443. }
  6444. else if (!isNaN(size)) {
  6445. height = size;
  6446. width = size;
  6447. }
  6448. else {
  6449. Tools.Error("Invalid 'size' parameter !");
  6450. return;
  6451. }
  6452. var scene = camera.getScene();
  6453. var previousCamera = null;
  6454. if (scene.activeCamera !== camera) {
  6455. previousCamera = scene.activeCamera;
  6456. scene.activeCamera = camera;
  6457. }
  6458. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6459. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6460. texture.renderList = null;
  6461. texture.samples = samples;
  6462. texture.onAfterRenderObservable.add(function () {
  6463. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6464. });
  6465. scene.incrementRenderId();
  6466. scene.resetCachedMaterial();
  6467. texture.render(true);
  6468. texture.dispose();
  6469. if (previousCamera) {
  6470. scene.activeCamera = previousCamera;
  6471. }
  6472. camera.getProjectionMatrix(true); // Force cache refresh;
  6473. };
  6474. // XHR response validator for local file scenario
  6475. Tools.ValidateXHRData = function (xhr, dataType) {
  6476. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6477. if (dataType === void 0) { dataType = 7; }
  6478. try {
  6479. if (dataType & 1) {
  6480. if (xhr.responseText && xhr.responseText.length > 0) {
  6481. return true;
  6482. }
  6483. else if (dataType === 1) {
  6484. return false;
  6485. }
  6486. }
  6487. if (dataType & 2) {
  6488. // Check header width and height since there is no "TGA" magic number
  6489. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6490. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6491. return true;
  6492. }
  6493. else if (dataType === 2) {
  6494. return false;
  6495. }
  6496. }
  6497. if (dataType & 4) {
  6498. // Check for the "DDS" magic number
  6499. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6500. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6501. return true;
  6502. }
  6503. else {
  6504. return false;
  6505. }
  6506. }
  6507. }
  6508. catch (e) {
  6509. // Global protection
  6510. }
  6511. return false;
  6512. };
  6513. /**
  6514. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6515. * Be aware Math.random() could cause collisions, but:
  6516. * "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"
  6517. */
  6518. Tools.RandomId = function () {
  6519. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6520. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6521. return v.toString(16);
  6522. });
  6523. };
  6524. Object.defineProperty(Tools, "NoneLogLevel", {
  6525. get: function () {
  6526. return Tools._NoneLogLevel;
  6527. },
  6528. enumerable: true,
  6529. configurable: true
  6530. });
  6531. Object.defineProperty(Tools, "MessageLogLevel", {
  6532. get: function () {
  6533. return Tools._MessageLogLevel;
  6534. },
  6535. enumerable: true,
  6536. configurable: true
  6537. });
  6538. Object.defineProperty(Tools, "WarningLogLevel", {
  6539. get: function () {
  6540. return Tools._WarningLogLevel;
  6541. },
  6542. enumerable: true,
  6543. configurable: true
  6544. });
  6545. Object.defineProperty(Tools, "ErrorLogLevel", {
  6546. get: function () {
  6547. return Tools._ErrorLogLevel;
  6548. },
  6549. enumerable: true,
  6550. configurable: true
  6551. });
  6552. Object.defineProperty(Tools, "AllLogLevel", {
  6553. get: function () {
  6554. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6555. },
  6556. enumerable: true,
  6557. configurable: true
  6558. });
  6559. Tools._AddLogEntry = function (entry) {
  6560. Tools._LogCache = entry + Tools._LogCache;
  6561. if (Tools.OnNewCacheEntry) {
  6562. Tools.OnNewCacheEntry(entry);
  6563. }
  6564. };
  6565. Tools._FormatMessage = function (message) {
  6566. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6567. var date = new Date();
  6568. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6569. };
  6570. Tools._LogDisabled = function (message) {
  6571. // nothing to do
  6572. };
  6573. Tools._LogEnabled = function (message) {
  6574. var formattedMessage = Tools._FormatMessage(message);
  6575. console.log("BJS - " + formattedMessage);
  6576. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6577. Tools._AddLogEntry(entry);
  6578. };
  6579. Tools._WarnDisabled = function (message) {
  6580. // nothing to do
  6581. };
  6582. Tools._WarnEnabled = function (message) {
  6583. var formattedMessage = Tools._FormatMessage(message);
  6584. console.warn("BJS - " + formattedMessage);
  6585. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6586. Tools._AddLogEntry(entry);
  6587. };
  6588. Tools._ErrorDisabled = function (message) {
  6589. // nothing to do
  6590. };
  6591. Tools._ErrorEnabled = function (message) {
  6592. Tools.errorsCount++;
  6593. var formattedMessage = Tools._FormatMessage(message);
  6594. console.error("BJS - " + formattedMessage);
  6595. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6596. Tools._AddLogEntry(entry);
  6597. };
  6598. Object.defineProperty(Tools, "LogCache", {
  6599. get: function () {
  6600. return Tools._LogCache;
  6601. },
  6602. enumerable: true,
  6603. configurable: true
  6604. });
  6605. Tools.ClearLogCache = function () {
  6606. Tools._LogCache = "";
  6607. Tools.errorsCount = 0;
  6608. };
  6609. Object.defineProperty(Tools, "LogLevels", {
  6610. set: function (level) {
  6611. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6612. Tools.Log = Tools._LogEnabled;
  6613. }
  6614. else {
  6615. Tools.Log = Tools._LogDisabled;
  6616. }
  6617. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6618. Tools.Warn = Tools._WarnEnabled;
  6619. }
  6620. else {
  6621. Tools.Warn = Tools._WarnDisabled;
  6622. }
  6623. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6624. Tools.Error = Tools._ErrorEnabled;
  6625. }
  6626. else {
  6627. Tools.Error = Tools._ErrorDisabled;
  6628. }
  6629. },
  6630. enumerable: true,
  6631. configurable: true
  6632. });
  6633. Tools.IsWindowObjectExist = function () {
  6634. return (typeof window) !== "undefined";
  6635. };
  6636. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6637. get: function () {
  6638. return Tools._PerformanceNoneLogLevel;
  6639. },
  6640. enumerable: true,
  6641. configurable: true
  6642. });
  6643. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6644. get: function () {
  6645. return Tools._PerformanceUserMarkLogLevel;
  6646. },
  6647. enumerable: true,
  6648. configurable: true
  6649. });
  6650. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6651. get: function () {
  6652. return Tools._PerformanceConsoleLogLevel;
  6653. },
  6654. enumerable: true,
  6655. configurable: true
  6656. });
  6657. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6658. set: function (level) {
  6659. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6660. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6661. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6662. return;
  6663. }
  6664. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6665. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6666. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6667. return;
  6668. }
  6669. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6670. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6671. },
  6672. enumerable: true,
  6673. configurable: true
  6674. });
  6675. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6676. };
  6677. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6678. };
  6679. Tools._StartUserMark = function (counterName, condition) {
  6680. if (condition === void 0) { condition = true; }
  6681. if (!Tools._performance) {
  6682. if (!Tools.IsWindowObjectExist()) {
  6683. return;
  6684. }
  6685. Tools._performance = window.performance;
  6686. }
  6687. if (!condition || !Tools._performance.mark) {
  6688. return;
  6689. }
  6690. Tools._performance.mark(counterName + "-Begin");
  6691. };
  6692. Tools._EndUserMark = function (counterName, condition) {
  6693. if (condition === void 0) { condition = true; }
  6694. if (!condition || !Tools._performance.mark) {
  6695. return;
  6696. }
  6697. Tools._performance.mark(counterName + "-End");
  6698. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6699. };
  6700. Tools._StartPerformanceConsole = function (counterName, condition) {
  6701. if (condition === void 0) { condition = true; }
  6702. if (!condition) {
  6703. return;
  6704. }
  6705. Tools._StartUserMark(counterName, condition);
  6706. if (console.time) {
  6707. console.time(counterName);
  6708. }
  6709. };
  6710. Tools._EndPerformanceConsole = function (counterName, condition) {
  6711. if (condition === void 0) { condition = true; }
  6712. if (!condition) {
  6713. return;
  6714. }
  6715. Tools._EndUserMark(counterName, condition);
  6716. if (console.time) {
  6717. console.timeEnd(counterName);
  6718. }
  6719. };
  6720. Object.defineProperty(Tools, "Now", {
  6721. get: function () {
  6722. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  6723. return window.performance.now();
  6724. }
  6725. return new Date().getTime();
  6726. },
  6727. enumerable: true,
  6728. configurable: true
  6729. });
  6730. /**
  6731. * This method will return the name of the class used to create the instance of the given object.
  6732. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6733. * @param object the object to get the class name from
  6734. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6735. */
  6736. Tools.GetClassName = function (object, isType) {
  6737. if (isType === void 0) { isType = false; }
  6738. var name = null;
  6739. if (!isType && object.getClassName) {
  6740. name = object.getClassName();
  6741. }
  6742. else {
  6743. if (object instanceof Object) {
  6744. var classObj = isType ? object : Object.getPrototypeOf(object);
  6745. name = classObj.constructor["__bjsclassName__"];
  6746. }
  6747. if (!name) {
  6748. name = typeof object;
  6749. }
  6750. }
  6751. return name;
  6752. };
  6753. Tools.First = function (array, predicate) {
  6754. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6755. var el = array_1[_i];
  6756. if (predicate(el)) {
  6757. return el;
  6758. }
  6759. }
  6760. return null;
  6761. };
  6762. /**
  6763. * This method will return the name of the full name of the class, including its owning module (if any).
  6764. * 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).
  6765. * @param object the object to get the class name from
  6766. * @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.
  6767. */
  6768. Tools.getFullClassName = function (object, isType) {
  6769. if (isType === void 0) { isType = false; }
  6770. var className = null;
  6771. var moduleName = null;
  6772. if (!isType && object.getClassName) {
  6773. className = object.getClassName();
  6774. }
  6775. else {
  6776. if (object instanceof Object) {
  6777. var classObj = isType ? object : Object.getPrototypeOf(object);
  6778. className = classObj.constructor["__bjsclassName__"];
  6779. moduleName = classObj.constructor["__bjsmoduleName__"];
  6780. }
  6781. if (!className) {
  6782. className = typeof object;
  6783. }
  6784. }
  6785. if (!className) {
  6786. return null;
  6787. }
  6788. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6789. };
  6790. /**
  6791. * 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.
  6792. * @param array
  6793. */
  6794. Tools.arrayOrStringFeeder = function (array) {
  6795. return function (index) {
  6796. if (index >= array.length) {
  6797. return null;
  6798. }
  6799. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6800. if (val && val.getHashCode) {
  6801. val = val.getHashCode();
  6802. }
  6803. if (typeof val === "string") {
  6804. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6805. }
  6806. return val;
  6807. };
  6808. };
  6809. /**
  6810. * Compute the hashCode of a stream of number
  6811. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6812. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6813. * @return the hash code computed
  6814. */
  6815. Tools.hashCodeFromStream = function (feeder) {
  6816. // Based from here: http://stackoverflow.com/a/7616484/802124
  6817. var hash = 0;
  6818. var index = 0;
  6819. var chr = feeder(index++);
  6820. while (chr != null) {
  6821. hash = ((hash << 5) - hash) + chr;
  6822. hash |= 0; // Convert to 32bit integer
  6823. chr = feeder(index++);
  6824. }
  6825. return hash;
  6826. };
  6827. Tools.BaseUrl = "";
  6828. Tools.CorsBehavior = "anonymous";
  6829. Tools.UseFallbackTexture = true;
  6830. /**
  6831. * Use this object to register external classes like custom textures or material
  6832. * to allow the laoders to instantiate them
  6833. */
  6834. Tools.RegisteredExternalClasses = {};
  6835. // Used in case of a texture loading problem
  6836. 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";
  6837. Tools.PreprocessUrl = function (url) {
  6838. return url;
  6839. };
  6840. // Logs
  6841. Tools._NoneLogLevel = 0;
  6842. Tools._MessageLogLevel = 1;
  6843. Tools._WarningLogLevel = 2;
  6844. Tools._ErrorLogLevel = 4;
  6845. Tools._LogCache = "";
  6846. Tools.errorsCount = 0;
  6847. Tools.Log = Tools._LogEnabled;
  6848. Tools.Warn = Tools._WarnEnabled;
  6849. Tools.Error = Tools._ErrorEnabled;
  6850. // Performances
  6851. Tools._PerformanceNoneLogLevel = 0;
  6852. Tools._PerformanceUserMarkLogLevel = 1;
  6853. Tools._PerformanceConsoleLogLevel = 2;
  6854. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6855. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6856. return Tools;
  6857. }());
  6858. BABYLON.Tools = Tools;
  6859. /**
  6860. * This class is used to track a performance counter which is number based.
  6861. * The user has access to many properties which give statistics of different nature
  6862. *
  6863. * The implementer can track two kinds of Performance Counter: time and count
  6864. * 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.
  6865. * 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.
  6866. */
  6867. var PerfCounter = /** @class */ (function () {
  6868. function PerfCounter() {
  6869. this._startMonitoringTime = 0;
  6870. this._min = 0;
  6871. this._max = 0;
  6872. this._average = 0;
  6873. this._lastSecAverage = 0;
  6874. this._current = 0;
  6875. this._totalValueCount = 0;
  6876. this._totalAccumulated = 0;
  6877. this._lastSecAccumulated = 0;
  6878. this._lastSecTime = 0;
  6879. this._lastSecValueCount = 0;
  6880. }
  6881. Object.defineProperty(PerfCounter.prototype, "min", {
  6882. /**
  6883. * Returns the smallest value ever
  6884. */
  6885. get: function () {
  6886. return this._min;
  6887. },
  6888. enumerable: true,
  6889. configurable: true
  6890. });
  6891. Object.defineProperty(PerfCounter.prototype, "max", {
  6892. /**
  6893. * Returns the biggest value ever
  6894. */
  6895. get: function () {
  6896. return this._max;
  6897. },
  6898. enumerable: true,
  6899. configurable: true
  6900. });
  6901. Object.defineProperty(PerfCounter.prototype, "average", {
  6902. /**
  6903. * Returns the average value since the performance counter is running
  6904. */
  6905. get: function () {
  6906. return this._average;
  6907. },
  6908. enumerable: true,
  6909. configurable: true
  6910. });
  6911. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6912. /**
  6913. * Returns the average value of the last second the counter was monitored
  6914. */
  6915. get: function () {
  6916. return this._lastSecAverage;
  6917. },
  6918. enumerable: true,
  6919. configurable: true
  6920. });
  6921. Object.defineProperty(PerfCounter.prototype, "current", {
  6922. /**
  6923. * Returns the current value
  6924. */
  6925. get: function () {
  6926. return this._current;
  6927. },
  6928. enumerable: true,
  6929. configurable: true
  6930. });
  6931. Object.defineProperty(PerfCounter.prototype, "total", {
  6932. get: function () {
  6933. return this._totalAccumulated;
  6934. },
  6935. enumerable: true,
  6936. configurable: true
  6937. });
  6938. /**
  6939. * Call this method to start monitoring a new frame.
  6940. * 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.
  6941. */
  6942. PerfCounter.prototype.fetchNewFrame = function () {
  6943. this._totalValueCount++;
  6944. this._current = 0;
  6945. this._lastSecValueCount++;
  6946. };
  6947. /**
  6948. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6949. * @param newCount the count value to add to the monitored count
  6950. * @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.
  6951. */
  6952. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6953. if (!PerfCounter.Enabled) {
  6954. return;
  6955. }
  6956. this._current += newCount;
  6957. if (fetchResult) {
  6958. this._fetchResult();
  6959. }
  6960. };
  6961. /**
  6962. * Start monitoring this performance counter
  6963. */
  6964. PerfCounter.prototype.beginMonitoring = function () {
  6965. if (!PerfCounter.Enabled) {
  6966. return;
  6967. }
  6968. this._startMonitoringTime = Tools.Now;
  6969. };
  6970. /**
  6971. * Compute the time lapsed since the previous beginMonitoring() call.
  6972. * @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
  6973. */
  6974. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6975. if (newFrame === void 0) { newFrame = true; }
  6976. if (!PerfCounter.Enabled) {
  6977. return;
  6978. }
  6979. if (newFrame) {
  6980. this.fetchNewFrame();
  6981. }
  6982. var currentTime = Tools.Now;
  6983. this._current = currentTime - this._startMonitoringTime;
  6984. if (newFrame) {
  6985. this._fetchResult();
  6986. }
  6987. };
  6988. PerfCounter.prototype._fetchResult = function () {
  6989. this._totalAccumulated += this._current;
  6990. this._lastSecAccumulated += this._current;
  6991. // Min/Max update
  6992. this._min = Math.min(this._min, this._current);
  6993. this._max = Math.max(this._max, this._current);
  6994. this._average = this._totalAccumulated / this._totalValueCount;
  6995. // Reset last sec?
  6996. var now = Tools.Now;
  6997. if ((now - this._lastSecTime) > 1000) {
  6998. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6999. this._lastSecTime = now;
  7000. this._lastSecAccumulated = 0;
  7001. this._lastSecValueCount = 0;
  7002. }
  7003. };
  7004. PerfCounter.Enabled = true;
  7005. return PerfCounter;
  7006. }());
  7007. BABYLON.PerfCounter = PerfCounter;
  7008. /**
  7009. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  7010. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  7011. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  7012. * @param name The name of the class, case should be preserved
  7013. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  7014. */
  7015. function className(name, module) {
  7016. return function (target) {
  7017. target["__bjsclassName__"] = name;
  7018. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7019. };
  7020. }
  7021. BABYLON.className = className;
  7022. /**
  7023. * An implementation of a loop for asynchronous functions.
  7024. */
  7025. var AsyncLoop = /** @class */ (function () {
  7026. /**
  7027. * Constroctor.
  7028. * @param iterations the number of iterations.
  7029. * @param _fn the function to run each iteration
  7030. * @param _successCallback the callback that will be called upon succesful execution
  7031. * @param offset starting offset.
  7032. */
  7033. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7034. if (offset === void 0) { offset = 0; }
  7035. this.iterations = iterations;
  7036. this._fn = _fn;
  7037. this._successCallback = _successCallback;
  7038. this.index = offset - 1;
  7039. this._done = false;
  7040. }
  7041. /**
  7042. * Execute the next iteration. Must be called after the last iteration was finished.
  7043. */
  7044. AsyncLoop.prototype.executeNext = function () {
  7045. if (!this._done) {
  7046. if (this.index + 1 < this.iterations) {
  7047. ++this.index;
  7048. this._fn(this);
  7049. }
  7050. else {
  7051. this.breakLoop();
  7052. }
  7053. }
  7054. };
  7055. /**
  7056. * Break the loop and run the success callback.
  7057. */
  7058. AsyncLoop.prototype.breakLoop = function () {
  7059. this._done = true;
  7060. this._successCallback();
  7061. };
  7062. /**
  7063. * Helper function
  7064. */
  7065. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7066. if (offset === void 0) { offset = 0; }
  7067. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7068. loop.executeNext();
  7069. return loop;
  7070. };
  7071. /**
  7072. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7073. * @param iterations total number of iterations
  7074. * @param syncedIterations number of synchronous iterations in each async iteration.
  7075. * @param fn the function to call each iteration.
  7076. * @param callback a success call back that will be called when iterating stops.
  7077. * @param breakFunction a break condition (optional)
  7078. * @param timeout timeout settings for the setTimeout function. default - 0.
  7079. * @constructor
  7080. */
  7081. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7082. if (timeout === void 0) { timeout = 0; }
  7083. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7084. if (breakFunction && breakFunction())
  7085. loop.breakLoop();
  7086. else {
  7087. setTimeout(function () {
  7088. for (var i = 0; i < syncedIterations; ++i) {
  7089. var iteration = (loop.index * syncedIterations) + i;
  7090. if (iteration >= iterations)
  7091. break;
  7092. fn(iteration);
  7093. if (breakFunction && breakFunction()) {
  7094. loop.breakLoop();
  7095. break;
  7096. }
  7097. }
  7098. loop.executeNext();
  7099. }, timeout);
  7100. }
  7101. }, callback);
  7102. };
  7103. return AsyncLoop;
  7104. }());
  7105. BABYLON.AsyncLoop = AsyncLoop;
  7106. })(BABYLON || (BABYLON = {}));
  7107. //# sourceMappingURL=babylon.tools.js.map
  7108. var BABYLON;
  7109. (function (BABYLON) {
  7110. var Internals;
  7111. (function (Internals) {
  7112. var _AlphaState = /** @class */ (function () {
  7113. /**
  7114. * Initializes the state.
  7115. */
  7116. function _AlphaState() {
  7117. this._isAlphaBlendDirty = false;
  7118. this._isBlendFunctionParametersDirty = false;
  7119. this._isBlendEquationParametersDirty = false;
  7120. this._isBlendConstantsDirty = false;
  7121. this._alphaBlend = false;
  7122. this._blendFunctionParameters = new Array(4);
  7123. this._blendEquationParameters = new Array(2);
  7124. this._blendConstants = new Array(4);
  7125. this.reset();
  7126. }
  7127. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7128. get: function () {
  7129. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7130. },
  7131. enumerable: true,
  7132. configurable: true
  7133. });
  7134. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7135. get: function () {
  7136. return this._alphaBlend;
  7137. },
  7138. set: function (value) {
  7139. if (this._alphaBlend === value) {
  7140. return;
  7141. }
  7142. this._alphaBlend = value;
  7143. this._isAlphaBlendDirty = true;
  7144. },
  7145. enumerable: true,
  7146. configurable: true
  7147. });
  7148. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  7149. if (this._blendConstants[0] === r &&
  7150. this._blendConstants[1] === g &&
  7151. this._blendConstants[2] === b &&
  7152. this._blendConstants[3] === a) {
  7153. return;
  7154. }
  7155. this._blendConstants[0] = r;
  7156. this._blendConstants[1] = g;
  7157. this._blendConstants[2] = b;
  7158. this._blendConstants[3] = a;
  7159. this._isBlendConstantsDirty = true;
  7160. };
  7161. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7162. if (this._blendFunctionParameters[0] === value0 &&
  7163. this._blendFunctionParameters[1] === value1 &&
  7164. this._blendFunctionParameters[2] === value2 &&
  7165. this._blendFunctionParameters[3] === value3) {
  7166. return;
  7167. }
  7168. this._blendFunctionParameters[0] = value0;
  7169. this._blendFunctionParameters[1] = value1;
  7170. this._blendFunctionParameters[2] = value2;
  7171. this._blendFunctionParameters[3] = value3;
  7172. this._isBlendFunctionParametersDirty = true;
  7173. };
  7174. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  7175. if (this._blendEquationParameters[0] === rgb &&
  7176. this._blendEquationParameters[1] === alpha) {
  7177. return;
  7178. }
  7179. this._blendEquationParameters[0] = rgb;
  7180. this._blendEquationParameters[1] = alpha;
  7181. this._isBlendEquationParametersDirty = true;
  7182. };
  7183. _AlphaState.prototype.reset = function () {
  7184. this._alphaBlend = false;
  7185. this._blendFunctionParameters[0] = null;
  7186. this._blendFunctionParameters[1] = null;
  7187. this._blendFunctionParameters[2] = null;
  7188. this._blendFunctionParameters[3] = null;
  7189. this._blendEquationParameters[0] = null;
  7190. this._blendEquationParameters[1] = null;
  7191. this._blendConstants[0] = null;
  7192. this._blendConstants[1] = null;
  7193. this._blendConstants[2] = null;
  7194. this._blendConstants[3] = null;
  7195. this._isAlphaBlendDirty = true;
  7196. this._isBlendFunctionParametersDirty = false;
  7197. this._isBlendEquationParametersDirty = false;
  7198. this._isBlendConstantsDirty = false;
  7199. };
  7200. _AlphaState.prototype.apply = function (gl) {
  7201. if (!this.isDirty) {
  7202. return;
  7203. }
  7204. // Alpha blend
  7205. if (this._isAlphaBlendDirty) {
  7206. if (this._alphaBlend) {
  7207. gl.enable(gl.BLEND);
  7208. }
  7209. else {
  7210. gl.disable(gl.BLEND);
  7211. }
  7212. this._isAlphaBlendDirty = false;
  7213. }
  7214. // Alpha function
  7215. if (this._isBlendFunctionParametersDirty) {
  7216. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7217. this._isBlendFunctionParametersDirty = false;
  7218. }
  7219. // Alpha equation
  7220. if (this._isBlendEquationParametersDirty) {
  7221. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  7222. this._isBlendEquationParametersDirty = false;
  7223. }
  7224. // Constants
  7225. if (this._isBlendConstantsDirty) {
  7226. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  7227. this._isBlendConstantsDirty = false;
  7228. }
  7229. };
  7230. return _AlphaState;
  7231. }());
  7232. Internals._AlphaState = _AlphaState;
  7233. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7234. })(BABYLON || (BABYLON = {}));
  7235. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7236. var BABYLON;
  7237. (function (BABYLON) {
  7238. var Internals;
  7239. (function (Internals) {
  7240. var _DepthCullingState = /** @class */ (function () {
  7241. /**
  7242. * Initializes the state.
  7243. */
  7244. function _DepthCullingState() {
  7245. this._isDepthTestDirty = false;
  7246. this._isDepthMaskDirty = false;
  7247. this._isDepthFuncDirty = false;
  7248. this._isCullFaceDirty = false;
  7249. this._isCullDirty = false;
  7250. this._isZOffsetDirty = false;
  7251. this.reset();
  7252. }
  7253. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7254. get: function () {
  7255. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7256. },
  7257. enumerable: true,
  7258. configurable: true
  7259. });
  7260. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7261. get: function () {
  7262. return this._zOffset;
  7263. },
  7264. set: function (value) {
  7265. if (this._zOffset === value) {
  7266. return;
  7267. }
  7268. this._zOffset = value;
  7269. this._isZOffsetDirty = true;
  7270. },
  7271. enumerable: true,
  7272. configurable: true
  7273. });
  7274. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7275. get: function () {
  7276. return this._cullFace;
  7277. },
  7278. set: function (value) {
  7279. if (this._cullFace === value) {
  7280. return;
  7281. }
  7282. this._cullFace = value;
  7283. this._isCullFaceDirty = true;
  7284. },
  7285. enumerable: true,
  7286. configurable: true
  7287. });
  7288. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7289. get: function () {
  7290. return this._cull;
  7291. },
  7292. set: function (value) {
  7293. if (this._cull === value) {
  7294. return;
  7295. }
  7296. this._cull = value;
  7297. this._isCullDirty = true;
  7298. },
  7299. enumerable: true,
  7300. configurable: true
  7301. });
  7302. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7303. get: function () {
  7304. return this._depthFunc;
  7305. },
  7306. set: function (value) {
  7307. if (this._depthFunc === value) {
  7308. return;
  7309. }
  7310. this._depthFunc = value;
  7311. this._isDepthFuncDirty = true;
  7312. },
  7313. enumerable: true,
  7314. configurable: true
  7315. });
  7316. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7317. get: function () {
  7318. return this._depthMask;
  7319. },
  7320. set: function (value) {
  7321. if (this._depthMask === value) {
  7322. return;
  7323. }
  7324. this._depthMask = value;
  7325. this._isDepthMaskDirty = true;
  7326. },
  7327. enumerable: true,
  7328. configurable: true
  7329. });
  7330. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7331. get: function () {
  7332. return this._depthTest;
  7333. },
  7334. set: function (value) {
  7335. if (this._depthTest === value) {
  7336. return;
  7337. }
  7338. this._depthTest = value;
  7339. this._isDepthTestDirty = true;
  7340. },
  7341. enumerable: true,
  7342. configurable: true
  7343. });
  7344. _DepthCullingState.prototype.reset = function () {
  7345. this._depthMask = true;
  7346. this._depthTest = true;
  7347. this._depthFunc = null;
  7348. this._cullFace = null;
  7349. this._cull = null;
  7350. this._zOffset = 0;
  7351. this._isDepthTestDirty = true;
  7352. this._isDepthMaskDirty = true;
  7353. this._isDepthFuncDirty = false;
  7354. this._isCullFaceDirty = false;
  7355. this._isCullDirty = false;
  7356. this._isZOffsetDirty = false;
  7357. };
  7358. _DepthCullingState.prototype.apply = function (gl) {
  7359. if (!this.isDirty) {
  7360. return;
  7361. }
  7362. // Cull
  7363. if (this._isCullDirty) {
  7364. if (this.cull) {
  7365. gl.enable(gl.CULL_FACE);
  7366. }
  7367. else {
  7368. gl.disable(gl.CULL_FACE);
  7369. }
  7370. this._isCullDirty = false;
  7371. }
  7372. // Cull face
  7373. if (this._isCullFaceDirty) {
  7374. gl.cullFace(this.cullFace);
  7375. this._isCullFaceDirty = false;
  7376. }
  7377. // Depth mask
  7378. if (this._isDepthMaskDirty) {
  7379. gl.depthMask(this.depthMask);
  7380. this._isDepthMaskDirty = false;
  7381. }
  7382. // Depth test
  7383. if (this._isDepthTestDirty) {
  7384. if (this.depthTest) {
  7385. gl.enable(gl.DEPTH_TEST);
  7386. }
  7387. else {
  7388. gl.disable(gl.DEPTH_TEST);
  7389. }
  7390. this._isDepthTestDirty = false;
  7391. }
  7392. // Depth func
  7393. if (this._isDepthFuncDirty) {
  7394. gl.depthFunc(this.depthFunc);
  7395. this._isDepthFuncDirty = false;
  7396. }
  7397. // zOffset
  7398. if (this._isZOffsetDirty) {
  7399. if (this.zOffset) {
  7400. gl.enable(gl.POLYGON_OFFSET_FILL);
  7401. gl.polygonOffset(this.zOffset, 0);
  7402. }
  7403. else {
  7404. gl.disable(gl.POLYGON_OFFSET_FILL);
  7405. }
  7406. this._isZOffsetDirty = false;
  7407. }
  7408. };
  7409. return _DepthCullingState;
  7410. }());
  7411. Internals._DepthCullingState = _DepthCullingState;
  7412. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7413. })(BABYLON || (BABYLON = {}));
  7414. //# sourceMappingURL=babylon.depthCullingState.js.map
  7415. var BABYLON;
  7416. (function (BABYLON) {
  7417. var Internals;
  7418. (function (Internals) {
  7419. var _StencilState = /** @class */ (function () {
  7420. function _StencilState() {
  7421. this._isStencilTestDirty = false;
  7422. this._isStencilMaskDirty = false;
  7423. this._isStencilFuncDirty = false;
  7424. this._isStencilOpDirty = false;
  7425. this.reset();
  7426. }
  7427. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7428. get: function () {
  7429. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7430. },
  7431. enumerable: true,
  7432. configurable: true
  7433. });
  7434. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7435. get: function () {
  7436. return this._stencilFunc;
  7437. },
  7438. set: function (value) {
  7439. if (this._stencilFunc === value) {
  7440. return;
  7441. }
  7442. this._stencilFunc = value;
  7443. this._isStencilFuncDirty = true;
  7444. },
  7445. enumerable: true,
  7446. configurable: true
  7447. });
  7448. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7449. get: function () {
  7450. return this._stencilFuncRef;
  7451. },
  7452. set: function (value) {
  7453. if (this._stencilFuncRef === value) {
  7454. return;
  7455. }
  7456. this._stencilFuncRef = value;
  7457. this._isStencilFuncDirty = true;
  7458. },
  7459. enumerable: true,
  7460. configurable: true
  7461. });
  7462. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7463. get: function () {
  7464. return this._stencilFuncMask;
  7465. },
  7466. set: function (value) {
  7467. if (this._stencilFuncMask === value) {
  7468. return;
  7469. }
  7470. this._stencilFuncMask = value;
  7471. this._isStencilFuncDirty = true;
  7472. },
  7473. enumerable: true,
  7474. configurable: true
  7475. });
  7476. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7477. get: function () {
  7478. return this._stencilOpStencilFail;
  7479. },
  7480. set: function (value) {
  7481. if (this._stencilOpStencilFail === value) {
  7482. return;
  7483. }
  7484. this._stencilOpStencilFail = value;
  7485. this._isStencilOpDirty = true;
  7486. },
  7487. enumerable: true,
  7488. configurable: true
  7489. });
  7490. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7491. get: function () {
  7492. return this._stencilOpDepthFail;
  7493. },
  7494. set: function (value) {
  7495. if (this._stencilOpDepthFail === value) {
  7496. return;
  7497. }
  7498. this._stencilOpDepthFail = value;
  7499. this._isStencilOpDirty = true;
  7500. },
  7501. enumerable: true,
  7502. configurable: true
  7503. });
  7504. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7505. get: function () {
  7506. return this._stencilOpStencilDepthPass;
  7507. },
  7508. set: function (value) {
  7509. if (this._stencilOpStencilDepthPass === value) {
  7510. return;
  7511. }
  7512. this._stencilOpStencilDepthPass = value;
  7513. this._isStencilOpDirty = true;
  7514. },
  7515. enumerable: true,
  7516. configurable: true
  7517. });
  7518. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7519. get: function () {
  7520. return this._stencilMask;
  7521. },
  7522. set: function (value) {
  7523. if (this._stencilMask === value) {
  7524. return;
  7525. }
  7526. this._stencilMask = value;
  7527. this._isStencilMaskDirty = true;
  7528. },
  7529. enumerable: true,
  7530. configurable: true
  7531. });
  7532. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7533. get: function () {
  7534. return this._stencilTest;
  7535. },
  7536. set: function (value) {
  7537. if (this._stencilTest === value) {
  7538. return;
  7539. }
  7540. this._stencilTest = value;
  7541. this._isStencilTestDirty = true;
  7542. },
  7543. enumerable: true,
  7544. configurable: true
  7545. });
  7546. _StencilState.prototype.reset = function () {
  7547. this._stencilTest = false;
  7548. this._stencilMask = 0xFF;
  7549. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7550. this._stencilFuncRef = 1;
  7551. this._stencilFuncMask = 0xFF;
  7552. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7553. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7554. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7555. this._isStencilTestDirty = true;
  7556. this._isStencilMaskDirty = true;
  7557. this._isStencilFuncDirty = true;
  7558. this._isStencilOpDirty = true;
  7559. };
  7560. _StencilState.prototype.apply = function (gl) {
  7561. if (!this.isDirty) {
  7562. return;
  7563. }
  7564. // Stencil test
  7565. if (this._isStencilTestDirty) {
  7566. if (this.stencilTest) {
  7567. gl.enable(gl.STENCIL_TEST);
  7568. }
  7569. else {
  7570. gl.disable(gl.STENCIL_TEST);
  7571. }
  7572. this._isStencilTestDirty = false;
  7573. }
  7574. // Stencil mask
  7575. if (this._isStencilMaskDirty) {
  7576. gl.stencilMask(this.stencilMask);
  7577. this._isStencilMaskDirty = false;
  7578. }
  7579. // Stencil func
  7580. if (this._isStencilFuncDirty) {
  7581. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7582. this._isStencilFuncDirty = false;
  7583. }
  7584. // Stencil op
  7585. if (this._isStencilOpDirty) {
  7586. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7587. this._isStencilOpDirty = false;
  7588. }
  7589. };
  7590. return _StencilState;
  7591. }());
  7592. Internals._StencilState = _StencilState;
  7593. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7594. })(BABYLON || (BABYLON = {}));
  7595. //# sourceMappingURL=babylon.stencilState.js.map
  7596. var BABYLON;
  7597. (function (BABYLON) {
  7598. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7599. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  7600. };
  7601. var compileRawShader = function (gl, source, type) {
  7602. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7603. gl.shaderSource(shader, source);
  7604. gl.compileShader(shader);
  7605. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7606. var log = gl.getShaderInfoLog(shader);
  7607. if (log) {
  7608. throw new Error(log);
  7609. }
  7610. }
  7611. if (!shader) {
  7612. throw new Error("Something went wrong while compile the shader.");
  7613. }
  7614. return shader;
  7615. };
  7616. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7617. var magFilter = gl.NEAREST;
  7618. var minFilter = gl.NEAREST;
  7619. switch (samplingMode) {
  7620. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7621. magFilter = gl.LINEAR;
  7622. if (generateMipMaps) {
  7623. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7624. }
  7625. else {
  7626. minFilter = gl.LINEAR;
  7627. }
  7628. break;
  7629. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7630. magFilter = gl.LINEAR;
  7631. if (generateMipMaps) {
  7632. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7633. }
  7634. else {
  7635. minFilter = gl.LINEAR;
  7636. }
  7637. break;
  7638. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7639. magFilter = gl.NEAREST;
  7640. if (generateMipMaps) {
  7641. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7642. }
  7643. else {
  7644. minFilter = gl.NEAREST;
  7645. }
  7646. break;
  7647. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7648. magFilter = gl.NEAREST;
  7649. if (generateMipMaps) {
  7650. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7651. }
  7652. else {
  7653. minFilter = gl.NEAREST;
  7654. }
  7655. break;
  7656. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7657. magFilter = gl.NEAREST;
  7658. if (generateMipMaps) {
  7659. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7660. }
  7661. else {
  7662. minFilter = gl.LINEAR;
  7663. }
  7664. break;
  7665. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7666. magFilter = gl.NEAREST;
  7667. if (generateMipMaps) {
  7668. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7669. }
  7670. else {
  7671. minFilter = gl.LINEAR;
  7672. }
  7673. break;
  7674. case BABYLON.Texture.NEAREST_LINEAR:
  7675. magFilter = gl.NEAREST;
  7676. minFilter = gl.LINEAR;
  7677. break;
  7678. case BABYLON.Texture.NEAREST_NEAREST:
  7679. magFilter = gl.NEAREST;
  7680. minFilter = gl.NEAREST;
  7681. break;
  7682. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7683. magFilter = gl.LINEAR;
  7684. if (generateMipMaps) {
  7685. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7686. }
  7687. else {
  7688. minFilter = gl.NEAREST;
  7689. }
  7690. break;
  7691. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7692. magFilter = gl.LINEAR;
  7693. if (generateMipMaps) {
  7694. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7695. }
  7696. else {
  7697. minFilter = gl.NEAREST;
  7698. }
  7699. break;
  7700. case BABYLON.Texture.LINEAR_LINEAR:
  7701. magFilter = gl.LINEAR;
  7702. minFilter = gl.LINEAR;
  7703. break;
  7704. case BABYLON.Texture.LINEAR_NEAREST:
  7705. magFilter = gl.LINEAR;
  7706. minFilter = gl.NEAREST;
  7707. break;
  7708. }
  7709. return {
  7710. min: minFilter,
  7711. mag: magFilter
  7712. };
  7713. };
  7714. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7715. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7716. var img;
  7717. var onload = function () {
  7718. loadedImages[index] = img;
  7719. loadedImages._internalCount++;
  7720. if (scene) {
  7721. scene._removePendingData(img);
  7722. }
  7723. if (loadedImages._internalCount === 6) {
  7724. onfinish(loadedImages);
  7725. }
  7726. };
  7727. var onerror = function (message, exception) {
  7728. if (scene) {
  7729. scene._removePendingData(img);
  7730. }
  7731. if (onErrorCallBack) {
  7732. onErrorCallBack(message, exception);
  7733. }
  7734. };
  7735. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7736. if (scene) {
  7737. scene._addPendingData(img);
  7738. }
  7739. };
  7740. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7741. if (onError === void 0) { onError = null; }
  7742. var loadedImages = [];
  7743. loadedImages._internalCount = 0;
  7744. for (var index = 0; index < 6; index++) {
  7745. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7746. }
  7747. };
  7748. var BufferPointer = /** @class */ (function () {
  7749. function BufferPointer() {
  7750. }
  7751. return BufferPointer;
  7752. }());
  7753. var InstancingAttributeInfo = /** @class */ (function () {
  7754. function InstancingAttributeInfo() {
  7755. }
  7756. return InstancingAttributeInfo;
  7757. }());
  7758. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7759. /**
  7760. * Define options used to create a render target texture
  7761. */
  7762. var RenderTargetCreationOptions = /** @class */ (function () {
  7763. function RenderTargetCreationOptions() {
  7764. }
  7765. return RenderTargetCreationOptions;
  7766. }());
  7767. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7768. /**
  7769. * Regroup several parameters relative to the browser in use
  7770. */
  7771. var EngineCapabilities = /** @class */ (function () {
  7772. function EngineCapabilities() {
  7773. }
  7774. return EngineCapabilities;
  7775. }());
  7776. BABYLON.EngineCapabilities = EngineCapabilities;
  7777. /**
  7778. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7779. */
  7780. var Engine = /** @class */ (function () {
  7781. /**
  7782. * @constructor
  7783. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7784. * @param {boolean} [antialias] - enable antialias
  7785. * @param options - further options to be sent to the getContext function
  7786. */
  7787. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7788. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7789. var _this = this;
  7790. // Public members
  7791. this.forcePOTTextures = false;
  7792. this.isFullscreen = false;
  7793. this.isPointerLock = false;
  7794. this.cullBackFaces = true;
  7795. this.renderEvenInBackground = true;
  7796. this.preventCacheWipeBetweenFrames = false;
  7797. // To enable/disable IDB support and avoid XHR on .manifest
  7798. this.enableOfflineSupport = false;
  7799. this.scenes = new Array();
  7800. this.postProcesses = new Array();
  7801. // Observables
  7802. /**
  7803. * Observable event triggered each time the rendering canvas is resized
  7804. */
  7805. this.onResizeObservable = new BABYLON.Observable();
  7806. /**
  7807. * Observable event triggered each time the canvas loses focus
  7808. */
  7809. this.onCanvasBlurObservable = new BABYLON.Observable();
  7810. /**
  7811. * Observable event triggered each time the canvas gains focus
  7812. */
  7813. this.onCanvasFocusObservable = new BABYLON.Observable();
  7814. /**
  7815. * Observable event triggered each time the canvas receives pointerout event
  7816. */
  7817. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  7818. /**
  7819. * Observable event triggered before each texture is initialized
  7820. */
  7821. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  7822. //WebVR
  7823. this._vrDisplay = undefined;
  7824. this._vrSupported = false;
  7825. this._vrExclusivePointerMode = false;
  7826. // Uniform buffers list
  7827. this.disableUniformBuffers = false;
  7828. this._uniformBuffers = new Array();
  7829. this._windowIsBackground = false;
  7830. this._webGLVersion = 1.0;
  7831. this._badOS = false;
  7832. this._badDesktopOS = false;
  7833. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  7834. this.onVRRequestPresentComplete = new BABYLON.Observable();
  7835. this.onVRRequestPresentStart = new BABYLON.Observable();
  7836. this._colorWrite = true;
  7837. this._drawCalls = new BABYLON.PerfCounter();
  7838. this._renderingQueueLaunched = false;
  7839. this._activeRenderLoops = new Array();
  7840. // Deterministic lockstepMaxSteps
  7841. this._deterministicLockstep = false;
  7842. this._lockstepMaxSteps = 4;
  7843. // Lost context
  7844. this.onContextLostObservable = new BABYLON.Observable();
  7845. this.onContextRestoredObservable = new BABYLON.Observable();
  7846. this._contextWasLost = false;
  7847. this._doNotHandleContextLost = false;
  7848. // FPS
  7849. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7850. this._fps = 60;
  7851. this._deltaTime = 0;
  7852. /**
  7853. * Turn this value on if you want to pause FPS computation when in background
  7854. */
  7855. this.disablePerformanceMonitorInBackground = false;
  7856. // States
  7857. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7858. this._stencilState = new BABYLON.Internals._StencilState();
  7859. this._alphaState = new BABYLON.Internals._AlphaState();
  7860. this._alphaMode = Engine.ALPHA_DISABLE;
  7861. // Cache
  7862. this._internalTexturesCache = new Array();
  7863. this._activeTexturesCache = {};
  7864. this._compiledEffects = {};
  7865. this._vertexAttribArraysEnabled = [];
  7866. this._uintIndicesCurrentlySet = false;
  7867. this._currentBoundBuffer = new Array();
  7868. this._currentBufferPointers = new Array();
  7869. this._currentInstanceLocations = new Array();
  7870. this._currentInstanceBuffers = new Array();
  7871. this._vaoRecordInProgress = false;
  7872. this._mustWipeVertexAttributes = false;
  7873. // Hardware supported Compressed Textures
  7874. this._texturesSupported = new Array();
  7875. this._onVRFullScreenTriggered = function () {
  7876. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  7877. //get the old size before we change
  7878. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7879. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7880. //get the width and height, change the render size
  7881. var leftEye = _this._vrDisplay.getEyeParameters('left');
  7882. _this.setHardwareScalingLevel(1);
  7883. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7884. }
  7885. else {
  7886. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7887. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7888. }
  7889. };
  7890. var canvas = null;
  7891. Engine.Instances.push(this);
  7892. if (!canvasOrContext) {
  7893. return;
  7894. }
  7895. options = options || {};
  7896. if (canvasOrContext.getContext) {
  7897. canvas = canvasOrContext;
  7898. this._renderingCanvas = canvas;
  7899. if (antialias != null) {
  7900. options.antialias = antialias;
  7901. }
  7902. if (options.deterministicLockstep === undefined) {
  7903. options.deterministicLockstep = false;
  7904. }
  7905. if (options.lockstepMaxSteps === undefined) {
  7906. options.lockstepMaxSteps = 4;
  7907. }
  7908. if (options.preserveDrawingBuffer === undefined) {
  7909. options.preserveDrawingBuffer = false;
  7910. }
  7911. if (options.audioEngine === undefined) {
  7912. options.audioEngine = true;
  7913. }
  7914. if (options.stencil === undefined) {
  7915. options.stencil = true;
  7916. }
  7917. this._deterministicLockstep = options.deterministicLockstep;
  7918. this._lockstepMaxSteps = options.lockstepMaxSteps;
  7919. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  7920. // GL
  7921. if (!options.disableWebGL2Support) {
  7922. try {
  7923. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7924. if (this._gl) {
  7925. this._webGLVersion = 2.0;
  7926. }
  7927. }
  7928. catch (e) {
  7929. // Do nothing
  7930. }
  7931. }
  7932. if (!this._gl) {
  7933. if (!canvas) {
  7934. throw new Error("The provided canvas is null or undefined.");
  7935. }
  7936. try {
  7937. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7938. }
  7939. catch (e) {
  7940. throw new Error("WebGL not supported");
  7941. }
  7942. }
  7943. if (!this._gl) {
  7944. throw new Error("WebGL not supported");
  7945. }
  7946. this._onCanvasFocus = function () {
  7947. _this.onCanvasFocusObservable.notifyObservers(_this);
  7948. };
  7949. this._onCanvasBlur = function () {
  7950. _this.onCanvasBlurObservable.notifyObservers(_this);
  7951. };
  7952. canvas.addEventListener("focus", this._onCanvasFocus);
  7953. canvas.addEventListener("blur", this._onCanvasBlur);
  7954. this._onBlur = function () {
  7955. if (_this.disablePerformanceMonitorInBackground) {
  7956. _this._performanceMonitor.disable();
  7957. }
  7958. _this._windowIsBackground = true;
  7959. };
  7960. this._onFocus = function () {
  7961. if (_this.disablePerformanceMonitorInBackground) {
  7962. _this._performanceMonitor.enable();
  7963. }
  7964. _this._windowIsBackground = false;
  7965. };
  7966. this._onCanvasPointerOut = function () {
  7967. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  7968. };
  7969. window.addEventListener("blur", this._onBlur);
  7970. window.addEventListener("focus", this._onFocus);
  7971. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  7972. // Context lost
  7973. if (!this._doNotHandleContextLost) {
  7974. this._onContextLost = function (evt) {
  7975. evt.preventDefault();
  7976. _this._contextWasLost = true;
  7977. BABYLON.Tools.Warn("WebGL context lost.");
  7978. _this.onContextLostObservable.notifyObservers(_this);
  7979. };
  7980. this._onContextRestored = function (evt) {
  7981. // Adding a timeout to avoid race condition at browser level
  7982. setTimeout(function () {
  7983. // Rebuild gl context
  7984. _this._initGLContext();
  7985. // Rebuild effects
  7986. _this._rebuildEffects();
  7987. // Rebuild textures
  7988. _this._rebuildInternalTextures();
  7989. // Rebuild buffers
  7990. _this._rebuildBuffers();
  7991. // Cache
  7992. _this.wipeCaches(true);
  7993. BABYLON.Tools.Warn("WebGL context successfully restored.");
  7994. _this.onContextRestoredObservable.notifyObservers(_this);
  7995. _this._contextWasLost = false;
  7996. }, 0);
  7997. };
  7998. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  7999. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  8000. }
  8001. }
  8002. else {
  8003. this._gl = canvasOrContext;
  8004. this._renderingCanvas = this._gl.canvas;
  8005. if (this._gl.renderbufferStorageMultisample) {
  8006. this._webGLVersion = 2.0;
  8007. }
  8008. options.stencil = this._gl.getContextAttributes().stencil;
  8009. }
  8010. // Viewport
  8011. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  8012. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  8013. this.resize();
  8014. this._isStencilEnable = options.stencil ? true : false;
  8015. this._initGLContext();
  8016. if (canvas) {
  8017. // Fullscreen
  8018. this._onFullscreenChange = function () {
  8019. if (document.fullscreen !== undefined) {
  8020. _this.isFullscreen = document.fullscreen;
  8021. }
  8022. else if (document.mozFullScreen !== undefined) {
  8023. _this.isFullscreen = document.mozFullScreen;
  8024. }
  8025. else if (document.webkitIsFullScreen !== undefined) {
  8026. _this.isFullscreen = document.webkitIsFullScreen;
  8027. }
  8028. else if (document.msIsFullScreen !== undefined) {
  8029. _this.isFullscreen = document.msIsFullScreen;
  8030. }
  8031. // Pointer lock
  8032. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  8033. canvas.requestPointerLock = canvas.requestPointerLock ||
  8034. canvas.msRequestPointerLock ||
  8035. canvas.mozRequestPointerLock ||
  8036. canvas.webkitRequestPointerLock;
  8037. if (canvas.requestPointerLock) {
  8038. canvas.requestPointerLock();
  8039. }
  8040. }
  8041. };
  8042. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  8043. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  8044. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  8045. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  8046. // Pointer lock
  8047. this._onPointerLockChange = function () {
  8048. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  8049. document.webkitPointerLockElement === canvas ||
  8050. document.msPointerLockElement === canvas ||
  8051. document.pointerLockElement === canvas);
  8052. };
  8053. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  8054. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  8055. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  8056. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  8057. this._onVRDisplayPointerRestricted = function () {
  8058. if (canvas) {
  8059. canvas.requestPointerLock();
  8060. }
  8061. };
  8062. this._onVRDisplayPointerUnrestricted = function () {
  8063. document.exitPointerLock();
  8064. };
  8065. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  8066. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  8067. }
  8068. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  8069. Engine.audioEngine = new BABYLON.AudioEngine();
  8070. }
  8071. // Prepare buffer pointers
  8072. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  8073. this._currentBufferPointers[i] = new BufferPointer();
  8074. }
  8075. // Load WebVR Devices
  8076. if (options.autoEnableWebVR) {
  8077. this.initWebVR();
  8078. }
  8079. // Detect if we are running on a faulty buggy OS.
  8080. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  8081. // Detect if we are running on a faulty buggy desktop OS.
  8082. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  8083. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  8084. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  8085. }
  8086. Object.defineProperty(Engine, "LastCreatedEngine", {
  8087. get: function () {
  8088. if (Engine.Instances.length === 0) {
  8089. return null;
  8090. }
  8091. return Engine.Instances[Engine.Instances.length - 1];
  8092. },
  8093. enumerable: true,
  8094. configurable: true
  8095. });
  8096. Object.defineProperty(Engine, "LastCreatedScene", {
  8097. get: function () {
  8098. var lastCreatedEngine = Engine.LastCreatedEngine;
  8099. if (!lastCreatedEngine) {
  8100. return null;
  8101. }
  8102. if (lastCreatedEngine.scenes.length === 0) {
  8103. return null;
  8104. }
  8105. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  8106. },
  8107. enumerable: true,
  8108. configurable: true
  8109. });
  8110. /**
  8111. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  8112. */
  8113. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  8114. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  8115. var engine = Engine.Instances[engineIndex];
  8116. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  8117. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  8118. }
  8119. }
  8120. };
  8121. Object.defineProperty(Engine, "NEVER", {
  8122. get: function () {
  8123. return Engine._NEVER;
  8124. },
  8125. enumerable: true,
  8126. configurable: true
  8127. });
  8128. Object.defineProperty(Engine, "ALWAYS", {
  8129. get: function () {
  8130. return Engine._ALWAYS;
  8131. },
  8132. enumerable: true,
  8133. configurable: true
  8134. });
  8135. Object.defineProperty(Engine, "LESS", {
  8136. get: function () {
  8137. return Engine._LESS;
  8138. },
  8139. enumerable: true,
  8140. configurable: true
  8141. });
  8142. Object.defineProperty(Engine, "EQUAL", {
  8143. get: function () {
  8144. return Engine._EQUAL;
  8145. },
  8146. enumerable: true,
  8147. configurable: true
  8148. });
  8149. Object.defineProperty(Engine, "LEQUAL", {
  8150. get: function () {
  8151. return Engine._LEQUAL;
  8152. },
  8153. enumerable: true,
  8154. configurable: true
  8155. });
  8156. Object.defineProperty(Engine, "GREATER", {
  8157. get: function () {
  8158. return Engine._GREATER;
  8159. },
  8160. enumerable: true,
  8161. configurable: true
  8162. });
  8163. Object.defineProperty(Engine, "GEQUAL", {
  8164. get: function () {
  8165. return Engine._GEQUAL;
  8166. },
  8167. enumerable: true,
  8168. configurable: true
  8169. });
  8170. Object.defineProperty(Engine, "NOTEQUAL", {
  8171. get: function () {
  8172. return Engine._NOTEQUAL;
  8173. },
  8174. enumerable: true,
  8175. configurable: true
  8176. });
  8177. Object.defineProperty(Engine, "KEEP", {
  8178. get: function () {
  8179. return Engine._KEEP;
  8180. },
  8181. enumerable: true,
  8182. configurable: true
  8183. });
  8184. Object.defineProperty(Engine, "REPLACE", {
  8185. get: function () {
  8186. return Engine._REPLACE;
  8187. },
  8188. enumerable: true,
  8189. configurable: true
  8190. });
  8191. Object.defineProperty(Engine, "INCR", {
  8192. get: function () {
  8193. return Engine._INCR;
  8194. },
  8195. enumerable: true,
  8196. configurable: true
  8197. });
  8198. Object.defineProperty(Engine, "DECR", {
  8199. get: function () {
  8200. return Engine._DECR;
  8201. },
  8202. enumerable: true,
  8203. configurable: true
  8204. });
  8205. Object.defineProperty(Engine, "INVERT", {
  8206. get: function () {
  8207. return Engine._INVERT;
  8208. },
  8209. enumerable: true,
  8210. configurable: true
  8211. });
  8212. Object.defineProperty(Engine, "INCR_WRAP", {
  8213. get: function () {
  8214. return Engine._INCR_WRAP;
  8215. },
  8216. enumerable: true,
  8217. configurable: true
  8218. });
  8219. Object.defineProperty(Engine, "DECR_WRAP", {
  8220. get: function () {
  8221. return Engine._DECR_WRAP;
  8222. },
  8223. enumerable: true,
  8224. configurable: true
  8225. });
  8226. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8227. get: function () {
  8228. return Engine._ALPHA_DISABLE;
  8229. },
  8230. enumerable: true,
  8231. configurable: true
  8232. });
  8233. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8234. get: function () {
  8235. return Engine._ALPHA_ONEONE;
  8236. },
  8237. enumerable: true,
  8238. configurable: true
  8239. });
  8240. Object.defineProperty(Engine, "ALPHA_ADD", {
  8241. get: function () {
  8242. return Engine._ALPHA_ADD;
  8243. },
  8244. enumerable: true,
  8245. configurable: true
  8246. });
  8247. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8248. get: function () {
  8249. return Engine._ALPHA_COMBINE;
  8250. },
  8251. enumerable: true,
  8252. configurable: true
  8253. });
  8254. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8255. get: function () {
  8256. return Engine._ALPHA_SUBTRACT;
  8257. },
  8258. enumerable: true,
  8259. configurable: true
  8260. });
  8261. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8262. get: function () {
  8263. return Engine._ALPHA_MULTIPLY;
  8264. },
  8265. enumerable: true,
  8266. configurable: true
  8267. });
  8268. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8269. get: function () {
  8270. return Engine._ALPHA_MAXIMIZED;
  8271. },
  8272. enumerable: true,
  8273. configurable: true
  8274. });
  8275. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8276. get: function () {
  8277. return Engine._ALPHA_PREMULTIPLIED;
  8278. },
  8279. enumerable: true,
  8280. configurable: true
  8281. });
  8282. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8283. get: function () {
  8284. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8285. },
  8286. enumerable: true,
  8287. configurable: true
  8288. });
  8289. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8290. get: function () {
  8291. return Engine._ALPHA_INTERPOLATE;
  8292. },
  8293. enumerable: true,
  8294. configurable: true
  8295. });
  8296. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8297. get: function () {
  8298. return Engine._ALPHA_SCREENMODE;
  8299. },
  8300. enumerable: true,
  8301. configurable: true
  8302. });
  8303. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8304. get: function () {
  8305. return Engine._DELAYLOADSTATE_NONE;
  8306. },
  8307. enumerable: true,
  8308. configurable: true
  8309. });
  8310. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8311. get: function () {
  8312. return Engine._DELAYLOADSTATE_LOADED;
  8313. },
  8314. enumerable: true,
  8315. configurable: true
  8316. });
  8317. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8318. get: function () {
  8319. return Engine._DELAYLOADSTATE_LOADING;
  8320. },
  8321. enumerable: true,
  8322. configurable: true
  8323. });
  8324. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8325. get: function () {
  8326. return Engine._DELAYLOADSTATE_NOTLOADED;
  8327. },
  8328. enumerable: true,
  8329. configurable: true
  8330. });
  8331. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8332. get: function () {
  8333. return Engine._TEXTUREFORMAT_ALPHA;
  8334. },
  8335. enumerable: true,
  8336. configurable: true
  8337. });
  8338. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8339. get: function () {
  8340. return Engine._TEXTUREFORMAT_LUMINANCE;
  8341. },
  8342. enumerable: true,
  8343. configurable: true
  8344. });
  8345. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8346. get: function () {
  8347. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8348. },
  8349. enumerable: true,
  8350. configurable: true
  8351. });
  8352. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8353. get: function () {
  8354. return Engine._TEXTUREFORMAT_RGB;
  8355. },
  8356. enumerable: true,
  8357. configurable: true
  8358. });
  8359. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8360. get: function () {
  8361. return Engine._TEXTUREFORMAT_RGBA;
  8362. },
  8363. enumerable: true,
  8364. configurable: true
  8365. });
  8366. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8367. get: function () {
  8368. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8369. },
  8370. enumerable: true,
  8371. configurable: true
  8372. });
  8373. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8374. get: function () {
  8375. return Engine._TEXTURETYPE_FLOAT;
  8376. },
  8377. enumerable: true,
  8378. configurable: true
  8379. });
  8380. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8381. get: function () {
  8382. return Engine._TEXTURETYPE_HALF_FLOAT;
  8383. },
  8384. enumerable: true,
  8385. configurable: true
  8386. });
  8387. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8388. get: function () {
  8389. return Engine._SCALEMODE_FLOOR;
  8390. },
  8391. enumerable: true,
  8392. configurable: true
  8393. });
  8394. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8395. get: function () {
  8396. return Engine._SCALEMODE_NEAREST;
  8397. },
  8398. enumerable: true,
  8399. configurable: true
  8400. });
  8401. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8402. get: function () {
  8403. return Engine._SCALEMODE_CEILING;
  8404. },
  8405. enumerable: true,
  8406. configurable: true
  8407. });
  8408. Object.defineProperty(Engine, "Version", {
  8409. get: function () {
  8410. return "3.1-alpha";
  8411. },
  8412. enumerable: true,
  8413. configurable: true
  8414. });
  8415. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  8416. get: function () {
  8417. return this._vrExclusivePointerMode;
  8418. },
  8419. enumerable: true,
  8420. configurable: true
  8421. });
  8422. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8423. get: function () {
  8424. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8425. },
  8426. enumerable: true,
  8427. configurable: true
  8428. });
  8429. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8430. get: function () {
  8431. return this._webGLVersion < 2 || this.forcePOTTextures;
  8432. },
  8433. enumerable: true,
  8434. configurable: true
  8435. });
  8436. Object.defineProperty(Engine.prototype, "badOS", {
  8437. get: function () {
  8438. return this._badOS;
  8439. },
  8440. enumerable: true,
  8441. configurable: true
  8442. });
  8443. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8444. get: function () {
  8445. return this._badDesktopOS;
  8446. },
  8447. enumerable: true,
  8448. configurable: true
  8449. });
  8450. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8451. get: function () {
  8452. return this._performanceMonitor;
  8453. },
  8454. enumerable: true,
  8455. configurable: true
  8456. });
  8457. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8458. get: function () {
  8459. return this._texturesSupported;
  8460. },
  8461. enumerable: true,
  8462. configurable: true
  8463. });
  8464. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8465. get: function () {
  8466. return this._textureFormatInUse;
  8467. },
  8468. enumerable: true,
  8469. configurable: true
  8470. });
  8471. Object.defineProperty(Engine.prototype, "currentViewport", {
  8472. get: function () {
  8473. return this._cachedViewport;
  8474. },
  8475. enumerable: true,
  8476. configurable: true
  8477. });
  8478. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8479. // Empty texture
  8480. get: function () {
  8481. if (!this._emptyTexture) {
  8482. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8483. }
  8484. return this._emptyTexture;
  8485. },
  8486. enumerable: true,
  8487. configurable: true
  8488. });
  8489. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8490. get: function () {
  8491. if (!this._emptyCubeTexture) {
  8492. var faceData = new Uint8Array(4);
  8493. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8494. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8495. }
  8496. return this._emptyCubeTexture;
  8497. },
  8498. enumerable: true,
  8499. configurable: true
  8500. });
  8501. Engine.prototype._rebuildInternalTextures = function () {
  8502. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8503. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8504. var internalTexture = currentState_1[_i];
  8505. internalTexture._rebuild();
  8506. }
  8507. };
  8508. Engine.prototype._rebuildEffects = function () {
  8509. for (var key in this._compiledEffects) {
  8510. var effect = this._compiledEffects[key];
  8511. effect._prepareEffect();
  8512. }
  8513. BABYLON.Effect.ResetCache();
  8514. };
  8515. Engine.prototype._rebuildBuffers = function () {
  8516. // Index / Vertex
  8517. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8518. var scene = _a[_i];
  8519. scene.resetCachedMaterial();
  8520. scene._rebuildGeometries();
  8521. scene._rebuildTextures();
  8522. }
  8523. // Uniforms
  8524. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8525. var uniformBuffer = _c[_b];
  8526. uniformBuffer._rebuild();
  8527. }
  8528. };
  8529. Engine.prototype._initGLContext = function () {
  8530. // Caps
  8531. this._caps = new EngineCapabilities();
  8532. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8533. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8534. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8535. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8536. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8537. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8538. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8539. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8540. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8541. // Infos
  8542. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8543. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8544. if (rendererInfo != null) {
  8545. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8546. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8547. }
  8548. if (!this._glVendor) {
  8549. this._glVendor = "Unknown vendor";
  8550. }
  8551. if (!this._glRenderer) {
  8552. this._glRenderer = "Unknown renderer";
  8553. }
  8554. // Constants
  8555. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8556. if (this._gl.RGBA16F !== 0x881A) {
  8557. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8558. }
  8559. if (this._gl.RGBA32F !== 0x8814) {
  8560. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8561. }
  8562. this._gl.DEPTH24_STENCIL8 = 35056;
  8563. // Extensions
  8564. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8565. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8566. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8567. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8568. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8569. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8570. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8571. 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');
  8572. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8573. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8574. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8575. this._caps.highPrecisionShaderSupported = true;
  8576. // Checks if some of the format renders first to allow the use of webgl inspector.
  8577. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8578. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8579. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8580. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8581. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8582. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8583. if (this._webGLVersion > 1) {
  8584. this._gl.HALF_FLOAT_OES = 0x140B;
  8585. }
  8586. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8587. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8588. // Draw buffers
  8589. if (this._webGLVersion > 1) {
  8590. this._caps.drawBuffersExtension = true;
  8591. }
  8592. else {
  8593. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  8594. if (drawBuffersExtension !== null) {
  8595. this._caps.drawBuffersExtension = true;
  8596. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  8597. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  8598. for (var i = 0; i < 16; i++) {
  8599. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  8600. }
  8601. }
  8602. else {
  8603. this._caps.drawBuffersExtension = false;
  8604. }
  8605. }
  8606. // Depth Texture
  8607. if (this._webGLVersion > 1) {
  8608. this._caps.depthTextureExtension = true;
  8609. }
  8610. else {
  8611. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  8612. if (depthTextureExtension != null) {
  8613. this._caps.depthTextureExtension = true;
  8614. }
  8615. }
  8616. // Vertex array object
  8617. if (this._webGLVersion > 1) {
  8618. this._caps.vertexArrayObject = true;
  8619. }
  8620. else {
  8621. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8622. if (vertexArrayObjectExtension != null) {
  8623. this._caps.vertexArrayObject = true;
  8624. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8625. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8626. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8627. }
  8628. else {
  8629. this._caps.vertexArrayObject = false;
  8630. }
  8631. }
  8632. // Instances count
  8633. if (this._webGLVersion > 1) {
  8634. this._caps.instancedArrays = true;
  8635. }
  8636. else {
  8637. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8638. if (instanceExtension != null) {
  8639. this._caps.instancedArrays = true;
  8640. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8641. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8642. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8643. }
  8644. else {
  8645. this._caps.instancedArrays = false;
  8646. }
  8647. }
  8648. // Intelligently add supported compressed formats in order to check for.
  8649. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8650. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8651. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8652. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8653. if (this._caps.astc)
  8654. this.texturesSupported.push('-astc.ktx');
  8655. if (this._caps.s3tc)
  8656. this.texturesSupported.push('-dxt.ktx');
  8657. if (this._caps.pvrtc)
  8658. this.texturesSupported.push('-pvrtc.ktx');
  8659. if (this._caps.etc2)
  8660. this.texturesSupported.push('-etc2.ktx');
  8661. if (this._caps.etc1)
  8662. this.texturesSupported.push('-etc1.ktx');
  8663. if (this._gl.getShaderPrecisionFormat) {
  8664. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8665. if (highp) {
  8666. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8667. }
  8668. }
  8669. // Depth buffer
  8670. this.setDepthBuffer(true);
  8671. this.setDepthFunctionToLessOrEqual();
  8672. this.setDepthWrite(true);
  8673. };
  8674. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8675. get: function () {
  8676. return this._webGLVersion;
  8677. },
  8678. enumerable: true,
  8679. configurable: true
  8680. });
  8681. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8682. /**
  8683. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8684. */
  8685. get: function () {
  8686. return this._isStencilEnable;
  8687. },
  8688. enumerable: true,
  8689. configurable: true
  8690. });
  8691. Engine.prototype._prepareWorkingCanvas = function () {
  8692. if (this._workingCanvas) {
  8693. return;
  8694. }
  8695. this._workingCanvas = document.createElement("canvas");
  8696. var context = this._workingCanvas.getContext("2d");
  8697. if (context) {
  8698. this._workingContext = context;
  8699. }
  8700. };
  8701. Engine.prototype.resetTextureCache = function () {
  8702. for (var key in this._activeTexturesCache) {
  8703. this._activeTexturesCache[key] = null;
  8704. }
  8705. };
  8706. Engine.prototype.isDeterministicLockStep = function () {
  8707. return this._deterministicLockstep;
  8708. };
  8709. Engine.prototype.getLockstepMaxSteps = function () {
  8710. return this._lockstepMaxSteps;
  8711. };
  8712. Engine.prototype.getGlInfo = function () {
  8713. return {
  8714. vendor: this._glVendor,
  8715. renderer: this._glRenderer,
  8716. version: this._glVersion
  8717. };
  8718. };
  8719. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8720. if (useScreen === void 0) { useScreen = false; }
  8721. var viewport = camera.viewport;
  8722. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8723. };
  8724. Engine.prototype.getRenderWidth = function (useScreen) {
  8725. if (useScreen === void 0) { useScreen = false; }
  8726. if (!useScreen && this._currentRenderTarget) {
  8727. return this._currentRenderTarget.width;
  8728. }
  8729. return this._gl.drawingBufferWidth;
  8730. };
  8731. Engine.prototype.getRenderHeight = function (useScreen) {
  8732. if (useScreen === void 0) { useScreen = false; }
  8733. if (!useScreen && this._currentRenderTarget) {
  8734. return this._currentRenderTarget.height;
  8735. }
  8736. return this._gl.drawingBufferHeight;
  8737. };
  8738. Engine.prototype.getRenderingCanvas = function () {
  8739. return this._renderingCanvas;
  8740. };
  8741. Engine.prototype.getRenderingCanvasClientRect = function () {
  8742. if (!this._renderingCanvas) {
  8743. return null;
  8744. }
  8745. return this._renderingCanvas.getBoundingClientRect();
  8746. };
  8747. Engine.prototype.setHardwareScalingLevel = function (level) {
  8748. this._hardwareScalingLevel = level;
  8749. this.resize();
  8750. };
  8751. Engine.prototype.getHardwareScalingLevel = function () {
  8752. return this._hardwareScalingLevel;
  8753. };
  8754. Engine.prototype.getLoadedTexturesCache = function () {
  8755. return this._internalTexturesCache;
  8756. };
  8757. Engine.prototype.getCaps = function () {
  8758. return this._caps;
  8759. };
  8760. Object.defineProperty(Engine.prototype, "drawCalls", {
  8761. /** The number of draw calls submitted last frame */
  8762. get: function () {
  8763. return this._drawCalls.current;
  8764. },
  8765. enumerable: true,
  8766. configurable: true
  8767. });
  8768. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8769. get: function () {
  8770. return this._drawCalls;
  8771. },
  8772. enumerable: true,
  8773. configurable: true
  8774. });
  8775. Engine.prototype.getDepthFunction = function () {
  8776. return this._depthCullingState.depthFunc;
  8777. };
  8778. Engine.prototype.setDepthFunction = function (depthFunc) {
  8779. this._depthCullingState.depthFunc = depthFunc;
  8780. };
  8781. Engine.prototype.setDepthFunctionToGreater = function () {
  8782. this._depthCullingState.depthFunc = this._gl.GREATER;
  8783. };
  8784. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8785. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8786. };
  8787. Engine.prototype.setDepthFunctionToLess = function () {
  8788. this._depthCullingState.depthFunc = this._gl.LESS;
  8789. };
  8790. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8791. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8792. };
  8793. Engine.prototype.getStencilBuffer = function () {
  8794. return this._stencilState.stencilTest;
  8795. };
  8796. Engine.prototype.setStencilBuffer = function (enable) {
  8797. this._stencilState.stencilTest = enable;
  8798. };
  8799. Engine.prototype.getStencilMask = function () {
  8800. return this._stencilState.stencilMask;
  8801. };
  8802. Engine.prototype.setStencilMask = function (mask) {
  8803. this._stencilState.stencilMask = mask;
  8804. };
  8805. Engine.prototype.getStencilFunction = function () {
  8806. return this._stencilState.stencilFunc;
  8807. };
  8808. Engine.prototype.getStencilFunctionReference = function () {
  8809. return this._stencilState.stencilFuncRef;
  8810. };
  8811. Engine.prototype.getStencilFunctionMask = function () {
  8812. return this._stencilState.stencilFuncMask;
  8813. };
  8814. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8815. this._stencilState.stencilFunc = stencilFunc;
  8816. };
  8817. Engine.prototype.setStencilFunctionReference = function (reference) {
  8818. this._stencilState.stencilFuncRef = reference;
  8819. };
  8820. Engine.prototype.setStencilFunctionMask = function (mask) {
  8821. this._stencilState.stencilFuncMask = mask;
  8822. };
  8823. Engine.prototype.getStencilOperationFail = function () {
  8824. return this._stencilState.stencilOpStencilFail;
  8825. };
  8826. Engine.prototype.getStencilOperationDepthFail = function () {
  8827. return this._stencilState.stencilOpDepthFail;
  8828. };
  8829. Engine.prototype.getStencilOperationPass = function () {
  8830. return this._stencilState.stencilOpStencilDepthPass;
  8831. };
  8832. Engine.prototype.setStencilOperationFail = function (operation) {
  8833. this._stencilState.stencilOpStencilFail = operation;
  8834. };
  8835. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8836. this._stencilState.stencilOpDepthFail = operation;
  8837. };
  8838. Engine.prototype.setStencilOperationPass = function (operation) {
  8839. this._stencilState.stencilOpStencilDepthPass = operation;
  8840. };
  8841. Engine.prototype.setDitheringState = function (value) {
  8842. if (value) {
  8843. this._gl.enable(this._gl.DITHER);
  8844. }
  8845. else {
  8846. this._gl.disable(this._gl.DITHER);
  8847. }
  8848. };
  8849. /**
  8850. * stop executing a render loop function and remove it from the execution array
  8851. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8852. */
  8853. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8854. if (!renderFunction) {
  8855. this._activeRenderLoops = [];
  8856. return;
  8857. }
  8858. var index = this._activeRenderLoops.indexOf(renderFunction);
  8859. if (index >= 0) {
  8860. this._activeRenderLoops.splice(index, 1);
  8861. }
  8862. };
  8863. Engine.prototype._renderLoop = function () {
  8864. if (!this._contextWasLost) {
  8865. var shouldRender = true;
  8866. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8867. shouldRender = false;
  8868. }
  8869. if (shouldRender) {
  8870. // Start new frame
  8871. this.beginFrame();
  8872. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8873. var renderFunction = this._activeRenderLoops[index];
  8874. renderFunction();
  8875. }
  8876. // Present
  8877. this.endFrame();
  8878. }
  8879. }
  8880. if (this._activeRenderLoops.length > 0) {
  8881. // Register new frame
  8882. var requester = null;
  8883. if (this._vrDisplay && this._vrDisplay.isPresenting)
  8884. requester = this._vrDisplay;
  8885. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  8886. }
  8887. else {
  8888. this._renderingQueueLaunched = false;
  8889. }
  8890. };
  8891. /**
  8892. * Register and execute a render loop. The engine can have more than one render function.
  8893. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8894. * @example
  8895. * engine.runRenderLoop(function () {
  8896. * scene.render()
  8897. * })
  8898. */
  8899. Engine.prototype.runRenderLoop = function (renderFunction) {
  8900. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8901. return;
  8902. }
  8903. this._activeRenderLoops.push(renderFunction);
  8904. if (!this._renderingQueueLaunched) {
  8905. this._renderingQueueLaunched = true;
  8906. this._bindedRenderFunction = this._renderLoop.bind(this);
  8907. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8908. }
  8909. };
  8910. /**
  8911. * Toggle full screen mode.
  8912. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8913. * @param {any} options - an options object to be sent to the requestFullscreen function
  8914. */
  8915. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8916. if (this.isFullscreen) {
  8917. BABYLON.Tools.ExitFullscreen();
  8918. }
  8919. else {
  8920. this._pointerLockRequested = requestPointerLock;
  8921. if (this._renderingCanvas) {
  8922. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8923. }
  8924. }
  8925. };
  8926. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8927. if (stencil === void 0) { stencil = false; }
  8928. this.applyStates();
  8929. var mode = 0;
  8930. if (backBuffer && color) {
  8931. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8932. mode |= this._gl.COLOR_BUFFER_BIT;
  8933. }
  8934. if (depth) {
  8935. this._gl.clearDepth(1.0);
  8936. mode |= this._gl.DEPTH_BUFFER_BIT;
  8937. }
  8938. if (stencil) {
  8939. this._gl.clearStencil(0);
  8940. mode |= this._gl.STENCIL_BUFFER_BIT;
  8941. }
  8942. this._gl.clear(mode);
  8943. };
  8944. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8945. var gl = this._gl;
  8946. // Save state
  8947. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8948. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8949. // Change state
  8950. gl.enable(gl.SCISSOR_TEST);
  8951. gl.scissor(x, y, width, height);
  8952. // Clear
  8953. this.clear(clearColor, true, true, true);
  8954. // Restore state
  8955. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8956. if (curScissor === true) {
  8957. gl.enable(gl.SCISSOR_TEST);
  8958. }
  8959. else {
  8960. gl.disable(gl.SCISSOR_TEST);
  8961. }
  8962. };
  8963. /**
  8964. * Set the WebGL's viewport
  8965. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8966. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8967. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8968. */
  8969. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8970. var width = requiredWidth || this.getRenderWidth();
  8971. var height = requiredHeight || this.getRenderHeight();
  8972. var x = viewport.x || 0;
  8973. var y = viewport.y || 0;
  8974. this._cachedViewport = viewport;
  8975. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8976. };
  8977. /**
  8978. * Directly set the WebGL Viewport
  8979. * The x, y, width & height are directly passed to the WebGL call
  8980. * @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.
  8981. */
  8982. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8983. var currentViewport = this._cachedViewport;
  8984. this._cachedViewport = null;
  8985. this._gl.viewport(x, y, width, height);
  8986. return currentViewport;
  8987. };
  8988. Engine.prototype.beginFrame = function () {
  8989. this._measureFps();
  8990. };
  8991. Engine.prototype.endFrame = function () {
  8992. //force a flush in case we are using a bad OS.
  8993. if (this._badOS) {
  8994. this.flushFramebuffer();
  8995. }
  8996. //submit frame to the vr device, if enabled
  8997. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  8998. // TODO: We should only submit the frame if we read frameData successfully.
  8999. this._vrDisplay.submitFrame();
  9000. }
  9001. };
  9002. /**
  9003. * resize the view according to the canvas' size.
  9004. * @example
  9005. * window.addEventListener("resize", function () {
  9006. * engine.resize();
  9007. * });
  9008. */
  9009. Engine.prototype.resize = function () {
  9010. // We're not resizing the size of the canvas while in VR mode & presenting
  9011. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  9012. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  9013. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  9014. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  9015. }
  9016. };
  9017. /**
  9018. * force a specific size of the canvas
  9019. * @param {number} width - the new canvas' width
  9020. * @param {number} height - the new canvas' height
  9021. */
  9022. Engine.prototype.setSize = function (width, height) {
  9023. if (!this._renderingCanvas) {
  9024. return;
  9025. }
  9026. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  9027. return;
  9028. }
  9029. this._renderingCanvas.width = width;
  9030. this._renderingCanvas.height = height;
  9031. for (var index = 0; index < this.scenes.length; index++) {
  9032. var scene = this.scenes[index];
  9033. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  9034. var cam = scene.cameras[camIndex];
  9035. cam._currentRenderId = 0;
  9036. }
  9037. }
  9038. if (this.onResizeObservable.hasObservers) {
  9039. this.onResizeObservable.notifyObservers(this);
  9040. }
  9041. };
  9042. // WebVR functions
  9043. Engine.prototype.isVRDevicePresent = function () {
  9044. return !!this._vrDisplay;
  9045. };
  9046. Engine.prototype.getVRDevice = function () {
  9047. return this._vrDisplay;
  9048. };
  9049. Engine.prototype.initWebVR = function () {
  9050. var _this = this;
  9051. var notifyObservers = function () {
  9052. var eventArgs = {
  9053. vrDisplay: _this._vrDisplay,
  9054. vrSupported: _this._vrSupported
  9055. };
  9056. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  9057. };
  9058. if (!this._onVrDisplayConnect) {
  9059. this._onVrDisplayConnect = function (event) {
  9060. _this._vrDisplay = event.display;
  9061. notifyObservers();
  9062. };
  9063. this._onVrDisplayDisconnect = function () {
  9064. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  9065. _this._vrDisplay = undefined;
  9066. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  9067. notifyObservers();
  9068. };
  9069. this._onVrDisplayPresentChange = function () {
  9070. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  9071. };
  9072. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  9073. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  9074. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  9075. }
  9076. this._getVRDisplays(notifyObservers);
  9077. return this.onVRDisplayChangedObservable;
  9078. };
  9079. Engine.prototype.enableVR = function () {
  9080. var _this = this;
  9081. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  9082. var onResolved = function () {
  9083. _this.onVRRequestPresentComplete.notifyObservers(true);
  9084. _this._onVRFullScreenTriggered();
  9085. };
  9086. var onRejected = function () {
  9087. _this.onVRRequestPresentComplete.notifyObservers(false);
  9088. };
  9089. this.onVRRequestPresentStart.notifyObservers(this);
  9090. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  9091. }
  9092. };
  9093. Engine.prototype.disableVR = function () {
  9094. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9095. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  9096. }
  9097. };
  9098. Engine.prototype._getVRDisplays = function (callback) {
  9099. var _this = this;
  9100. var getWebVRDevices = function (devices) {
  9101. _this._vrSupported = true;
  9102. // note that devices may actually be an empty array. This is fine;
  9103. // we expect this._vrDisplay to be undefined in this case.
  9104. return _this._vrDisplay = devices[0];
  9105. };
  9106. if (navigator.getVRDisplays) {
  9107. // TODO: Backwards compatible for 1.0?
  9108. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  9109. // TODO: System CANNOT support WebVR, despite API presence.
  9110. _this._vrSupported = false;
  9111. callback();
  9112. });
  9113. }
  9114. else {
  9115. // TODO: Browser does not support WebVR
  9116. this._vrDisplay = undefined;
  9117. this._vrSupported = false;
  9118. callback();
  9119. }
  9120. };
  9121. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  9122. if (this._currentRenderTarget) {
  9123. this.unBindFramebuffer(this._currentRenderTarget);
  9124. }
  9125. this._currentRenderTarget = texture;
  9126. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  9127. var gl = this._gl;
  9128. if (texture.isCube) {
  9129. if (faceIndex === undefined) {
  9130. faceIndex = 0;
  9131. }
  9132. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  9133. }
  9134. if (this._cachedViewport && !forceFullscreenViewport) {
  9135. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  9136. }
  9137. else {
  9138. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  9139. }
  9140. this.wipeCaches();
  9141. };
  9142. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  9143. if (this._currentFramebuffer !== framebuffer) {
  9144. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  9145. this._currentFramebuffer = framebuffer;
  9146. }
  9147. };
  9148. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  9149. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  9150. this._currentRenderTarget = null;
  9151. // If MSAA, we need to bitblt back to main texture
  9152. var gl = this._gl;
  9153. if (texture._MSAAFramebuffer) {
  9154. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  9155. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  9156. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  9157. }
  9158. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  9159. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9160. gl.generateMipmap(gl.TEXTURE_2D);
  9161. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9162. }
  9163. if (onBeforeUnbind) {
  9164. if (texture._MSAAFramebuffer) {
  9165. // Bind the correct framebuffer
  9166. this.bindUnboundFramebuffer(texture._framebuffer);
  9167. }
  9168. onBeforeUnbind();
  9169. }
  9170. this.bindUnboundFramebuffer(null);
  9171. };
  9172. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  9173. if (texture.generateMipMaps) {
  9174. var gl = this._gl;
  9175. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9176. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9177. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9178. }
  9179. };
  9180. Engine.prototype.flushFramebuffer = function () {
  9181. this._gl.flush();
  9182. };
  9183. Engine.prototype.restoreDefaultFramebuffer = function () {
  9184. if (this._currentRenderTarget) {
  9185. this.unBindFramebuffer(this._currentRenderTarget);
  9186. }
  9187. else {
  9188. this.bindUnboundFramebuffer(null);
  9189. }
  9190. if (this._cachedViewport) {
  9191. this.setViewport(this._cachedViewport);
  9192. }
  9193. this.wipeCaches();
  9194. };
  9195. // UBOs
  9196. Engine.prototype.createUniformBuffer = function (elements) {
  9197. var ubo = this._gl.createBuffer();
  9198. if (!ubo) {
  9199. throw new Error("Unable to create uniform buffer");
  9200. }
  9201. this.bindUniformBuffer(ubo);
  9202. if (elements instanceof Float32Array) {
  9203. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  9204. }
  9205. else {
  9206. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  9207. }
  9208. this.bindUniformBuffer(null);
  9209. ubo.references = 1;
  9210. return ubo;
  9211. };
  9212. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  9213. var ubo = this._gl.createBuffer();
  9214. if (!ubo) {
  9215. throw new Error("Unable to create dynamic uniform buffer");
  9216. }
  9217. this.bindUniformBuffer(ubo);
  9218. if (elements instanceof Float32Array) {
  9219. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  9220. }
  9221. else {
  9222. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  9223. }
  9224. this.bindUniformBuffer(null);
  9225. ubo.references = 1;
  9226. return ubo;
  9227. };
  9228. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  9229. this.bindUniformBuffer(uniformBuffer);
  9230. if (offset === undefined) {
  9231. offset = 0;
  9232. }
  9233. if (count === undefined) {
  9234. if (elements instanceof Float32Array) {
  9235. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  9236. }
  9237. else {
  9238. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  9239. }
  9240. }
  9241. else {
  9242. if (elements instanceof Float32Array) {
  9243. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  9244. }
  9245. else {
  9246. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  9247. }
  9248. }
  9249. this.bindUniformBuffer(null);
  9250. };
  9251. // VBOs
  9252. Engine.prototype._resetVertexBufferBinding = function () {
  9253. this.bindArrayBuffer(null);
  9254. this._cachedVertexBuffers = null;
  9255. };
  9256. Engine.prototype.createVertexBuffer = function (vertices) {
  9257. var vbo = this._gl.createBuffer();
  9258. if (!vbo) {
  9259. throw new Error("Unable to create vertex buffer");
  9260. }
  9261. this.bindArrayBuffer(vbo);
  9262. if (vertices instanceof Float32Array) {
  9263. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  9264. }
  9265. else {
  9266. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  9267. }
  9268. this._resetVertexBufferBinding();
  9269. vbo.references = 1;
  9270. return vbo;
  9271. };
  9272. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  9273. var vbo = this._gl.createBuffer();
  9274. if (!vbo) {
  9275. throw new Error("Unable to create dynamic vertex buffer");
  9276. }
  9277. this.bindArrayBuffer(vbo);
  9278. if (vertices instanceof Float32Array) {
  9279. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  9280. }
  9281. else {
  9282. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  9283. }
  9284. this._resetVertexBufferBinding();
  9285. vbo.references = 1;
  9286. return vbo;
  9287. };
  9288. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  9289. if (offset === void 0) { offset = 0; }
  9290. // Force cache update
  9291. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  9292. this.bindIndexBuffer(indexBuffer);
  9293. var arrayBuffer;
  9294. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  9295. arrayBuffer = indices;
  9296. }
  9297. else {
  9298. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9299. }
  9300. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  9301. this._resetIndexBufferBinding();
  9302. };
  9303. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  9304. this.bindArrayBuffer(vertexBuffer);
  9305. if (offset === undefined) {
  9306. offset = 0;
  9307. }
  9308. if (count === undefined) {
  9309. if (vertices instanceof Float32Array) {
  9310. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  9311. }
  9312. else {
  9313. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  9314. }
  9315. }
  9316. else {
  9317. if (vertices instanceof Float32Array) {
  9318. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  9319. }
  9320. else {
  9321. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  9322. }
  9323. }
  9324. this._resetVertexBufferBinding();
  9325. };
  9326. Engine.prototype._resetIndexBufferBinding = function () {
  9327. this.bindIndexBuffer(null);
  9328. this._cachedIndexBuffer = null;
  9329. };
  9330. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  9331. var vbo = this._gl.createBuffer();
  9332. if (!vbo) {
  9333. throw new Error("Unable to create index buffer");
  9334. }
  9335. this.bindIndexBuffer(vbo);
  9336. // Check for 32 bits indices
  9337. var arrayBuffer;
  9338. var need32Bits = false;
  9339. if (indices instanceof Uint16Array) {
  9340. arrayBuffer = indices;
  9341. }
  9342. else {
  9343. //check 32 bit support
  9344. if (this._caps.uintIndices) {
  9345. if (indices instanceof Uint32Array) {
  9346. arrayBuffer = indices;
  9347. need32Bits = true;
  9348. }
  9349. else {
  9350. //number[] or Int32Array, check if 32 bit is necessary
  9351. for (var index = 0; index < indices.length; index++) {
  9352. if (indices[index] > 65535) {
  9353. need32Bits = true;
  9354. break;
  9355. }
  9356. }
  9357. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9358. }
  9359. }
  9360. else {
  9361. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9362. arrayBuffer = new Uint16Array(indices);
  9363. }
  9364. }
  9365. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  9366. this._resetIndexBufferBinding();
  9367. vbo.references = 1;
  9368. vbo.is32Bits = need32Bits;
  9369. return vbo;
  9370. };
  9371. Engine.prototype.bindArrayBuffer = function (buffer) {
  9372. if (!this._vaoRecordInProgress) {
  9373. this._unbindVertexArrayObject();
  9374. }
  9375. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9376. };
  9377. Engine.prototype.bindUniformBuffer = function (buffer) {
  9378. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9379. };
  9380. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9381. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9382. };
  9383. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9384. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9385. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9386. };
  9387. ;
  9388. Engine.prototype.bindIndexBuffer = function (buffer) {
  9389. if (!this._vaoRecordInProgress) {
  9390. this._unbindVertexArrayObject();
  9391. }
  9392. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9393. };
  9394. Engine.prototype.bindBuffer = function (buffer, target) {
  9395. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9396. this._gl.bindBuffer(target, buffer);
  9397. this._currentBoundBuffer[target] = buffer;
  9398. }
  9399. };
  9400. Engine.prototype.updateArrayBuffer = function (data) {
  9401. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9402. };
  9403. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9404. var pointer = this._currentBufferPointers[indx];
  9405. var changed = false;
  9406. if (!pointer.active) {
  9407. changed = true;
  9408. pointer.active = true;
  9409. pointer.index = indx;
  9410. pointer.size = size;
  9411. pointer.type = type;
  9412. pointer.normalized = normalized;
  9413. pointer.stride = stride;
  9414. pointer.offset = offset;
  9415. pointer.buffer = buffer;
  9416. }
  9417. else {
  9418. if (pointer.buffer !== buffer) {
  9419. pointer.buffer = buffer;
  9420. changed = true;
  9421. }
  9422. if (pointer.size !== size) {
  9423. pointer.size = size;
  9424. changed = true;
  9425. }
  9426. if (pointer.type !== type) {
  9427. pointer.type = type;
  9428. changed = true;
  9429. }
  9430. if (pointer.normalized !== normalized) {
  9431. pointer.normalized = normalized;
  9432. changed = true;
  9433. }
  9434. if (pointer.stride !== stride) {
  9435. pointer.stride = stride;
  9436. changed = true;
  9437. }
  9438. if (pointer.offset !== offset) {
  9439. pointer.offset = offset;
  9440. changed = true;
  9441. }
  9442. }
  9443. if (changed || this._vaoRecordInProgress) {
  9444. this.bindArrayBuffer(buffer);
  9445. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9446. }
  9447. };
  9448. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9449. if (indexBuffer == null) {
  9450. return;
  9451. }
  9452. if (this._cachedIndexBuffer !== indexBuffer) {
  9453. this._cachedIndexBuffer = indexBuffer;
  9454. this.bindIndexBuffer(indexBuffer);
  9455. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9456. }
  9457. };
  9458. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9459. var attributes = effect.getAttributesNames();
  9460. if (!this._vaoRecordInProgress) {
  9461. this._unbindVertexArrayObject();
  9462. }
  9463. this.unbindAllAttributes();
  9464. for (var index = 0; index < attributes.length; index++) {
  9465. var order = effect.getAttributeLocation(index);
  9466. if (order >= 0) {
  9467. var vertexBuffer = vertexBuffers[attributes[index]];
  9468. if (!vertexBuffer) {
  9469. continue;
  9470. }
  9471. this._gl.enableVertexAttribArray(order);
  9472. if (!this._vaoRecordInProgress) {
  9473. this._vertexAttribArraysEnabled[order] = true;
  9474. }
  9475. var buffer = vertexBuffer.getBuffer();
  9476. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9477. if (vertexBuffer.getIsInstanced()) {
  9478. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9479. if (!this._vaoRecordInProgress) {
  9480. this._currentInstanceLocations.push(order);
  9481. this._currentInstanceBuffers.push(buffer);
  9482. }
  9483. }
  9484. }
  9485. }
  9486. };
  9487. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9488. var vao = this._gl.createVertexArray();
  9489. this._vaoRecordInProgress = true;
  9490. this._gl.bindVertexArray(vao);
  9491. this._mustWipeVertexAttributes = true;
  9492. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9493. this.bindIndexBuffer(indexBuffer);
  9494. this._vaoRecordInProgress = false;
  9495. this._gl.bindVertexArray(null);
  9496. return vao;
  9497. };
  9498. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9499. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9500. this._cachedVertexArrayObject = vertexArrayObject;
  9501. this._gl.bindVertexArray(vertexArrayObject);
  9502. this._cachedVertexBuffers = null;
  9503. this._cachedIndexBuffer = null;
  9504. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9505. this._mustWipeVertexAttributes = true;
  9506. }
  9507. };
  9508. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9509. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9510. this._cachedVertexBuffers = vertexBuffer;
  9511. this._cachedEffectForVertexBuffers = effect;
  9512. var attributesCount = effect.getAttributesCount();
  9513. this._unbindVertexArrayObject();
  9514. this.unbindAllAttributes();
  9515. var offset = 0;
  9516. for (var index = 0; index < attributesCount; index++) {
  9517. if (index < vertexDeclaration.length) {
  9518. var order = effect.getAttributeLocation(index);
  9519. if (order >= 0) {
  9520. this._gl.enableVertexAttribArray(order);
  9521. this._vertexAttribArraysEnabled[order] = true;
  9522. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9523. }
  9524. offset += vertexDeclaration[index] * 4;
  9525. }
  9526. }
  9527. }
  9528. this._bindIndexBufferWithCache(indexBuffer);
  9529. };
  9530. Engine.prototype._unbindVertexArrayObject = function () {
  9531. if (!this._cachedVertexArrayObject) {
  9532. return;
  9533. }
  9534. this._cachedVertexArrayObject = null;
  9535. this._gl.bindVertexArray(null);
  9536. };
  9537. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9538. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9539. this._cachedVertexBuffers = vertexBuffers;
  9540. this._cachedEffectForVertexBuffers = effect;
  9541. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9542. }
  9543. this._bindIndexBufferWithCache(indexBuffer);
  9544. };
  9545. Engine.prototype.unbindInstanceAttributes = function () {
  9546. var boundBuffer;
  9547. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9548. var instancesBuffer = this._currentInstanceBuffers[i];
  9549. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9550. boundBuffer = instancesBuffer;
  9551. this.bindArrayBuffer(instancesBuffer);
  9552. }
  9553. var offsetLocation = this._currentInstanceLocations[i];
  9554. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9555. }
  9556. this._currentInstanceBuffers.length = 0;
  9557. this._currentInstanceLocations.length = 0;
  9558. };
  9559. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9560. this._gl.deleteVertexArray(vao);
  9561. };
  9562. Engine.prototype._releaseBuffer = function (buffer) {
  9563. buffer.references--;
  9564. if (buffer.references === 0) {
  9565. this._gl.deleteBuffer(buffer);
  9566. return true;
  9567. }
  9568. return false;
  9569. };
  9570. Engine.prototype.createInstancesBuffer = function (capacity) {
  9571. var buffer = this._gl.createBuffer();
  9572. if (!buffer) {
  9573. throw new Error("Unable to create instance buffer");
  9574. }
  9575. buffer.capacity = capacity;
  9576. this.bindArrayBuffer(buffer);
  9577. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9578. return buffer;
  9579. };
  9580. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9581. this._gl.deleteBuffer(buffer);
  9582. };
  9583. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9584. this.bindArrayBuffer(instancesBuffer);
  9585. if (data) {
  9586. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9587. }
  9588. if (offsetLocations[0].index !== undefined) {
  9589. var stride = 0;
  9590. for (var i = 0; i < offsetLocations.length; i++) {
  9591. var ai = offsetLocations[i];
  9592. stride += ai.attributeSize * 4;
  9593. }
  9594. for (var i = 0; i < offsetLocations.length; i++) {
  9595. var ai = offsetLocations[i];
  9596. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9597. this._gl.enableVertexAttribArray(ai.index);
  9598. this._vertexAttribArraysEnabled[ai.index] = true;
  9599. }
  9600. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9601. this._gl.vertexAttribDivisor(ai.index, 1);
  9602. this._currentInstanceLocations.push(ai.index);
  9603. this._currentInstanceBuffers.push(instancesBuffer);
  9604. }
  9605. }
  9606. else {
  9607. for (var index = 0; index < 4; index++) {
  9608. var offsetLocation = offsetLocations[index];
  9609. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9610. this._gl.enableVertexAttribArray(offsetLocation);
  9611. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9612. }
  9613. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9614. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9615. this._currentInstanceLocations.push(offsetLocation);
  9616. this._currentInstanceBuffers.push(instancesBuffer);
  9617. }
  9618. }
  9619. };
  9620. Engine.prototype.applyStates = function () {
  9621. this._depthCullingState.apply(this._gl);
  9622. this._stencilState.apply(this._gl);
  9623. this._alphaState.apply(this._gl);
  9624. };
  9625. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9626. // Apply states
  9627. this.applyStates();
  9628. this._drawCalls.addCount(1, false);
  9629. // Render
  9630. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9631. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9632. if (instancesCount) {
  9633. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9634. return;
  9635. }
  9636. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9637. };
  9638. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9639. // Apply states
  9640. this.applyStates();
  9641. this._drawCalls.addCount(1, false);
  9642. if (instancesCount) {
  9643. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9644. return;
  9645. }
  9646. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9647. };
  9648. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9649. // Apply states
  9650. this.applyStates();
  9651. this._drawCalls.addCount(1, false);
  9652. if (instancesCount) {
  9653. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9654. return;
  9655. }
  9656. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9657. };
  9658. // Shaders
  9659. Engine.prototype._releaseEffect = function (effect) {
  9660. if (this._compiledEffects[effect._key]) {
  9661. delete this._compiledEffects[effect._key];
  9662. this._deleteProgram(effect.getProgram());
  9663. }
  9664. };
  9665. Engine.prototype._deleteProgram = function (program) {
  9666. if (program) {
  9667. program.__SPECTOR_rebuildProgram = null;
  9668. this._gl.deleteProgram(program);
  9669. }
  9670. };
  9671. /**
  9672. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9673. * @param samplers An array of string used to represent textures
  9674. */
  9675. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9676. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9677. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9678. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9679. if (this._compiledEffects[name]) {
  9680. var compiledEffect = this._compiledEffects[name];
  9681. if (onCompiled && compiledEffect.isReady()) {
  9682. onCompiled(compiledEffect);
  9683. }
  9684. return compiledEffect;
  9685. }
  9686. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9687. effect._key = name;
  9688. this._compiledEffects[name] = effect;
  9689. return effect;
  9690. };
  9691. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9692. if (uniformsNames === void 0) { uniformsNames = []; }
  9693. if (samplers === void 0) { samplers = []; }
  9694. if (defines === void 0) { defines = ""; }
  9695. return this.createEffect({
  9696. vertex: "particles",
  9697. fragmentElement: fragmentName
  9698. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9699. };
  9700. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context) {
  9701. context = context || this._gl;
  9702. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  9703. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  9704. return this._createShaderProgram(vertexShader, fragmentShader, context);
  9705. };
  9706. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9707. context = context || this._gl;
  9708. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9709. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9710. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9711. return this._createShaderProgram(vertexShader, fragmentShader, context);
  9712. };
  9713. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context) {
  9714. var shaderProgram = context.createProgram();
  9715. if (!shaderProgram) {
  9716. throw new Error("Unable to create program");
  9717. }
  9718. context.attachShader(shaderProgram, vertexShader);
  9719. context.attachShader(shaderProgram, fragmentShader);
  9720. context.linkProgram(shaderProgram);
  9721. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9722. if (!linked) {
  9723. context.validateProgram(shaderProgram);
  9724. var error = context.getProgramInfoLog(shaderProgram);
  9725. if (error) {
  9726. throw new Error(error);
  9727. }
  9728. }
  9729. context.deleteShader(vertexShader);
  9730. context.deleteShader(fragmentShader);
  9731. return shaderProgram;
  9732. };
  9733. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9734. var results = new Array();
  9735. for (var index = 0; index < uniformsNames.length; index++) {
  9736. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9737. }
  9738. return results;
  9739. };
  9740. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9741. var results = [];
  9742. for (var index = 0; index < attributesNames.length; index++) {
  9743. try {
  9744. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9745. }
  9746. catch (e) {
  9747. results.push(-1);
  9748. }
  9749. }
  9750. return results;
  9751. };
  9752. Engine.prototype.enableEffect = function (effect) {
  9753. // Use program
  9754. this.setProgram(effect.getProgram());
  9755. this._currentEffect = effect;
  9756. if (effect.onBind) {
  9757. effect.onBind(effect);
  9758. }
  9759. effect.onBindObservable.notifyObservers(effect);
  9760. };
  9761. Engine.prototype.setIntArray = function (uniform, array) {
  9762. if (!uniform)
  9763. return;
  9764. this._gl.uniform1iv(uniform, array);
  9765. };
  9766. Engine.prototype.setIntArray2 = function (uniform, array) {
  9767. if (!uniform || array.length % 2 !== 0)
  9768. return;
  9769. this._gl.uniform2iv(uniform, array);
  9770. };
  9771. Engine.prototype.setIntArray3 = function (uniform, array) {
  9772. if (!uniform || array.length % 3 !== 0)
  9773. return;
  9774. this._gl.uniform3iv(uniform, array);
  9775. };
  9776. Engine.prototype.setIntArray4 = function (uniform, array) {
  9777. if (!uniform || array.length % 4 !== 0)
  9778. return;
  9779. this._gl.uniform4iv(uniform, array);
  9780. };
  9781. Engine.prototype.setFloatArray = function (uniform, array) {
  9782. if (!uniform)
  9783. return;
  9784. this._gl.uniform1fv(uniform, array);
  9785. };
  9786. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9787. if (!uniform || array.length % 2 !== 0)
  9788. return;
  9789. this._gl.uniform2fv(uniform, array);
  9790. };
  9791. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9792. if (!uniform || array.length % 3 !== 0)
  9793. return;
  9794. this._gl.uniform3fv(uniform, array);
  9795. };
  9796. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9797. if (!uniform || array.length % 4 !== 0)
  9798. return;
  9799. this._gl.uniform4fv(uniform, array);
  9800. };
  9801. Engine.prototype.setArray = function (uniform, array) {
  9802. if (!uniform)
  9803. return;
  9804. this._gl.uniform1fv(uniform, array);
  9805. };
  9806. Engine.prototype.setArray2 = function (uniform, array) {
  9807. if (!uniform || array.length % 2 !== 0)
  9808. return;
  9809. this._gl.uniform2fv(uniform, array);
  9810. };
  9811. Engine.prototype.setArray3 = function (uniform, array) {
  9812. if (!uniform || array.length % 3 !== 0)
  9813. return;
  9814. this._gl.uniform3fv(uniform, array);
  9815. };
  9816. Engine.prototype.setArray4 = function (uniform, array) {
  9817. if (!uniform || array.length % 4 !== 0)
  9818. return;
  9819. this._gl.uniform4fv(uniform, array);
  9820. };
  9821. Engine.prototype.setMatrices = function (uniform, matrices) {
  9822. if (!uniform)
  9823. return;
  9824. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9825. };
  9826. Engine.prototype.setMatrix = function (uniform, matrix) {
  9827. if (!uniform)
  9828. return;
  9829. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9830. };
  9831. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9832. if (!uniform)
  9833. return;
  9834. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9835. };
  9836. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9837. if (!uniform)
  9838. return;
  9839. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9840. };
  9841. Engine.prototype.setFloat = function (uniform, value) {
  9842. if (!uniform)
  9843. return;
  9844. this._gl.uniform1f(uniform, value);
  9845. };
  9846. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9847. if (!uniform)
  9848. return;
  9849. this._gl.uniform2f(uniform, x, y);
  9850. };
  9851. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9852. if (!uniform)
  9853. return;
  9854. this._gl.uniform3f(uniform, x, y, z);
  9855. };
  9856. Engine.prototype.setBool = function (uniform, bool) {
  9857. if (!uniform)
  9858. return;
  9859. this._gl.uniform1i(uniform, bool);
  9860. };
  9861. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9862. if (!uniform)
  9863. return;
  9864. this._gl.uniform4f(uniform, x, y, z, w);
  9865. };
  9866. Engine.prototype.setColor3 = function (uniform, color3) {
  9867. if (!uniform)
  9868. return;
  9869. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9870. };
  9871. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9872. if (!uniform)
  9873. return;
  9874. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9875. };
  9876. // States
  9877. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9878. if (zOffset === void 0) { zOffset = 0; }
  9879. if (reverseSide === void 0) { reverseSide = false; }
  9880. // Culling
  9881. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9882. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9883. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9884. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9885. if (culling) {
  9886. this._depthCullingState.cullFace = cullFace;
  9887. this._depthCullingState.cull = true;
  9888. }
  9889. else {
  9890. this._depthCullingState.cull = false;
  9891. }
  9892. }
  9893. // Z offset
  9894. this.setZOffset(zOffset);
  9895. };
  9896. Engine.prototype.setZOffset = function (value) {
  9897. this._depthCullingState.zOffset = value;
  9898. };
  9899. Engine.prototype.getZOffset = function () {
  9900. return this._depthCullingState.zOffset;
  9901. };
  9902. Engine.prototype.setDepthBuffer = function (enable) {
  9903. this._depthCullingState.depthTest = enable;
  9904. };
  9905. Engine.prototype.getDepthWrite = function () {
  9906. return this._depthCullingState.depthMask;
  9907. };
  9908. Engine.prototype.setDepthWrite = function (enable) {
  9909. this._depthCullingState.depthMask = enable;
  9910. };
  9911. Engine.prototype.setColorWrite = function (enable) {
  9912. this._gl.colorMask(enable, enable, enable, enable);
  9913. this._colorWrite = enable;
  9914. };
  9915. Engine.prototype.getColorWrite = function () {
  9916. return this._colorWrite;
  9917. };
  9918. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  9919. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  9920. };
  9921. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9922. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9923. if (this._alphaMode === mode) {
  9924. return;
  9925. }
  9926. switch (mode) {
  9927. case Engine.ALPHA_DISABLE:
  9928. this._alphaState.alphaBlend = false;
  9929. break;
  9930. case Engine.ALPHA_PREMULTIPLIED:
  9931. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9932. this._alphaState.alphaBlend = true;
  9933. break;
  9934. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  9935. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9936. this._alphaState.alphaBlend = true;
  9937. break;
  9938. case Engine.ALPHA_COMBINE:
  9939. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9940. this._alphaState.alphaBlend = true;
  9941. break;
  9942. case Engine.ALPHA_ONEONE:
  9943. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9944. this._alphaState.alphaBlend = true;
  9945. break;
  9946. case Engine.ALPHA_ADD:
  9947. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9948. this._alphaState.alphaBlend = true;
  9949. break;
  9950. case Engine.ALPHA_SUBTRACT:
  9951. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9952. this._alphaState.alphaBlend = true;
  9953. break;
  9954. case Engine.ALPHA_MULTIPLY:
  9955. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9956. this._alphaState.alphaBlend = true;
  9957. break;
  9958. case Engine.ALPHA_MAXIMIZED:
  9959. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9960. this._alphaState.alphaBlend = true;
  9961. break;
  9962. case Engine.ALPHA_INTERPOLATE:
  9963. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  9964. this._alphaState.alphaBlend = true;
  9965. break;
  9966. case Engine.ALPHA_SCREENMODE:
  9967. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9968. this._alphaState.alphaBlend = true;
  9969. break;
  9970. }
  9971. if (!noDepthWriteChange) {
  9972. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9973. }
  9974. this._alphaMode = mode;
  9975. };
  9976. Engine.prototype.getAlphaMode = function () {
  9977. return this._alphaMode;
  9978. };
  9979. Engine.prototype.setAlphaTesting = function (enable) {
  9980. this._alphaTest = enable;
  9981. };
  9982. Engine.prototype.getAlphaTesting = function () {
  9983. return !!this._alphaTest;
  9984. };
  9985. // Textures
  9986. Engine.prototype.wipeCaches = function (bruteForce) {
  9987. if (this.preventCacheWipeBetweenFrames) {
  9988. return;
  9989. }
  9990. this.resetTextureCache();
  9991. this._currentEffect = null;
  9992. // 6/8/2017: deltakosh: Should not be required anymore.
  9993. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9994. if (bruteForce) {
  9995. this._currentProgram = null;
  9996. this._stencilState.reset();
  9997. this._depthCullingState.reset();
  9998. this.setDepthFunctionToLessOrEqual();
  9999. this._alphaState.reset();
  10000. }
  10001. this._cachedVertexBuffers = null;
  10002. this._cachedIndexBuffer = null;
  10003. this._cachedEffectForVertexBuffers = null;
  10004. this._unbindVertexArrayObject();
  10005. this.bindIndexBuffer(null);
  10006. this.bindArrayBuffer(null);
  10007. };
  10008. /**
  10009. * Set the compressed texture format to use, based on the formats you have, and the formats
  10010. * supported by the hardware / browser.
  10011. *
  10012. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  10013. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  10014. * to API arguments needed to compressed textures. This puts the burden on the container
  10015. * generator to house the arcane code for determining these for current & future formats.
  10016. *
  10017. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  10018. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  10019. *
  10020. * Note: The result of this call is not taken into account when a texture is base64.
  10021. *
  10022. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  10023. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  10024. *
  10025. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  10026. * @returns The extension selected.
  10027. */
  10028. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  10029. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  10030. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  10031. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  10032. return this._textureFormatInUse = this._texturesSupported[i];
  10033. }
  10034. }
  10035. }
  10036. // actively set format to nothing, to allow this to be called more than once
  10037. // and possibly fail the 2nd time
  10038. this._textureFormatInUse = null;
  10039. return null;
  10040. };
  10041. Engine.prototype._createTexture = function () {
  10042. var texture = this._gl.createTexture();
  10043. if (!texture) {
  10044. throw new Error("Unable to create texture");
  10045. }
  10046. return texture;
  10047. };
  10048. /**
  10049. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  10050. * @param {string} urlArg- This contains one of the following:
  10051. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  10052. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  10053. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  10054. *
  10055. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  10056. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  10057. * @param {Scene} scene- Needed for loading to the correct scene.
  10058. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  10059. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  10060. * @param {callback} onError- Optional callback to be called upon failure.
  10061. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  10062. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  10063. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  10064. *
  10065. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  10066. */
  10067. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  10068. var _this = this;
  10069. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10070. if (onLoad === void 0) { onLoad = null; }
  10071. if (onError === void 0) { onError = null; }
  10072. if (buffer === void 0) { buffer = null; }
  10073. if (fallBack === void 0) { fallBack = null; }
  10074. if (format === void 0) { format = null; }
  10075. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  10076. var fromData = url.substr(0, 5) === "data:";
  10077. var fromBlob = url.substr(0, 5) === "blob:";
  10078. var isBase64 = fromData && url.indexOf("base64") !== -1;
  10079. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  10080. // establish the file extension, if possible
  10081. var lastDot = url.lastIndexOf('.');
  10082. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  10083. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  10084. var isTGA = (extension === ".tga");
  10085. // determine if a ktx file should be substituted
  10086. var isKTX = false;
  10087. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  10088. url = url.substring(0, lastDot) + this._textureFormatInUse;
  10089. isKTX = true;
  10090. }
  10091. if (scene) {
  10092. scene._addPendingData(texture);
  10093. }
  10094. texture.url = url;
  10095. texture.generateMipMaps = !noMipmap;
  10096. texture.samplingMode = samplingMode;
  10097. texture.invertY = invertY;
  10098. if (!this._doNotHandleContextLost) {
  10099. // Keep a link to the buffer only if we plan to handle context lost
  10100. texture._buffer = buffer;
  10101. }
  10102. if (onLoad) {
  10103. texture.onLoadedObservable.add(onLoad);
  10104. }
  10105. if (!fallBack)
  10106. this._internalTexturesCache.push(texture);
  10107. var onerror = function () {
  10108. if (scene) {
  10109. scene._removePendingData(texture);
  10110. }
  10111. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  10112. if (isKTX) {
  10113. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10114. }
  10115. else if (onError) {
  10116. onError();
  10117. }
  10118. };
  10119. var callback = null;
  10120. // processing for non-image formats
  10121. if (isKTX || isTGA || isDDS) {
  10122. if (isKTX) {
  10123. callback = function (data) {
  10124. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  10125. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  10126. ktx.uploadLevels(_this._gl, !noMipmap);
  10127. return false;
  10128. }, samplingMode);
  10129. };
  10130. }
  10131. else if (isTGA) {
  10132. callback = function (arrayBuffer) {
  10133. var data = new Uint8Array(arrayBuffer);
  10134. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  10135. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  10136. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  10137. return false;
  10138. }, samplingMode);
  10139. };
  10140. }
  10141. else if (isDDS) {
  10142. callback = function (data) {
  10143. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10144. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  10145. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  10146. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  10147. return false;
  10148. }, samplingMode);
  10149. };
  10150. }
  10151. if (!buffer) {
  10152. BABYLON.Tools.LoadFile(url, function (data) {
  10153. if (callback) {
  10154. callback(data);
  10155. }
  10156. }, undefined, scene ? scene.database : undefined, true, onerror);
  10157. }
  10158. else {
  10159. if (callback) {
  10160. callback(buffer);
  10161. }
  10162. }
  10163. // image format processing
  10164. }
  10165. else {
  10166. var onload = function (img) {
  10167. if (fromBlob && !_this._doNotHandleContextLost) {
  10168. // We need to store the image if we need to rebuild the texture
  10169. // in case of a webgl context lost
  10170. texture._buffer = img;
  10171. }
  10172. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  10173. var gl = _this._gl;
  10174. var isPot = (img.width === potWidth && img.height === potHeight);
  10175. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  10176. if (isPot) {
  10177. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10178. return false;
  10179. }
  10180. // Using shaders to rescale because canvas.drawImage is lossy
  10181. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10182. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  10183. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10184. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10185. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10186. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10187. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10188. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  10189. _this._releaseTexture(source);
  10190. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10191. continuationCallback();
  10192. });
  10193. return true;
  10194. }, samplingMode);
  10195. };
  10196. if (!fromData || isBase64)
  10197. if (buffer instanceof HTMLImageElement) {
  10198. onload(buffer);
  10199. }
  10200. else {
  10201. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10202. }
  10203. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  10204. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  10205. else
  10206. onload(buffer);
  10207. }
  10208. return texture;
  10209. };
  10210. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  10211. var _this = this;
  10212. var rtt = this.createRenderTargetTexture({
  10213. width: destination.width,
  10214. height: destination.height,
  10215. }, {
  10216. generateMipMaps: false,
  10217. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  10218. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  10219. generateDepthBuffer: false,
  10220. generateStencilBuffer: false
  10221. });
  10222. if (!this._rescalePostProcess) {
  10223. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  10224. }
  10225. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  10226. _this._rescalePostProcess.onApply = function (effect) {
  10227. effect._bindTexture("textureSampler", source);
  10228. };
  10229. var hostingScene = scene;
  10230. if (!hostingScene) {
  10231. hostingScene = _this.scenes[_this.scenes.length - 1];
  10232. }
  10233. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  10234. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  10235. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  10236. _this.unBindFramebuffer(rtt);
  10237. _this._releaseTexture(rtt);
  10238. if (onComplete) {
  10239. onComplete();
  10240. }
  10241. });
  10242. };
  10243. Engine.prototype._getInternalFormat = function (format) {
  10244. var internalFormat = this._gl.RGBA;
  10245. switch (format) {
  10246. case Engine.TEXTUREFORMAT_ALPHA:
  10247. internalFormat = this._gl.ALPHA;
  10248. break;
  10249. case Engine.TEXTUREFORMAT_LUMINANCE:
  10250. internalFormat = this._gl.LUMINANCE;
  10251. break;
  10252. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  10253. internalFormat = this._gl.LUMINANCE_ALPHA;
  10254. break;
  10255. case Engine.TEXTUREFORMAT_RGB:
  10256. internalFormat = this._gl.RGB;
  10257. break;
  10258. case Engine.TEXTUREFORMAT_RGBA:
  10259. internalFormat = this._gl.RGBA;
  10260. break;
  10261. }
  10262. return internalFormat;
  10263. };
  10264. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  10265. if (compression === void 0) { compression = null; }
  10266. var internalFormat = this._getInternalFormat(format);
  10267. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10268. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10269. if (!this._doNotHandleContextLost) {
  10270. texture._bufferView = data;
  10271. texture.format = format;
  10272. texture.invertY = invertY;
  10273. texture._compression = compression;
  10274. }
  10275. if (texture.width % 4 !== 0) {
  10276. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  10277. }
  10278. if (compression) {
  10279. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  10280. }
  10281. else {
  10282. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  10283. }
  10284. if (texture.generateMipMaps) {
  10285. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10286. }
  10287. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10288. this.resetTextureCache();
  10289. texture.isReady = true;
  10290. };
  10291. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  10292. if (compression === void 0) { compression = null; }
  10293. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  10294. texture.baseWidth = width;
  10295. texture.baseHeight = height;
  10296. texture.width = width;
  10297. texture.height = height;
  10298. texture.format = format;
  10299. texture.generateMipMaps = generateMipMaps;
  10300. texture.samplingMode = samplingMode;
  10301. texture.invertY = invertY;
  10302. texture._compression = compression;
  10303. if (!this._doNotHandleContextLost) {
  10304. texture._bufferView = data;
  10305. }
  10306. this.updateRawTexture(texture, data, format, invertY, compression);
  10307. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10308. // Filters
  10309. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  10310. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10311. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10312. if (generateMipMaps) {
  10313. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10314. }
  10315. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10316. this._internalTexturesCache.push(texture);
  10317. return texture;
  10318. };
  10319. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  10320. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  10321. texture.baseWidth = width;
  10322. texture.baseHeight = height;
  10323. if (generateMipMaps) {
  10324. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  10325. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  10326. }
  10327. this.resetTextureCache();
  10328. texture.width = width;
  10329. texture.height = height;
  10330. texture.isReady = false;
  10331. texture.generateMipMaps = generateMipMaps;
  10332. texture.samplingMode = samplingMode;
  10333. this.updateTextureSamplingMode(samplingMode, texture);
  10334. this._internalTexturesCache.push(texture);
  10335. return texture;
  10336. };
  10337. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  10338. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  10339. if (texture.isCube) {
  10340. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10341. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10342. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10343. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10344. }
  10345. else {
  10346. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10347. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10348. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10349. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10350. }
  10351. texture.samplingMode = samplingMode;
  10352. };
  10353. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  10354. if (premulAlpha === void 0) { premulAlpha = false; }
  10355. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10356. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  10357. if (premulAlpha) {
  10358. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  10359. }
  10360. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  10361. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  10362. if (texture.generateMipMaps) {
  10363. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10364. }
  10365. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10366. if (premulAlpha) {
  10367. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  10368. }
  10369. this.resetTextureCache();
  10370. texture.isReady = true;
  10371. };
  10372. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10373. if (texture._isDisabled) {
  10374. return;
  10375. }
  10376. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10377. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10378. try {
  10379. // Testing video texture support
  10380. if (this._videoTextureSupported === undefined) {
  10381. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10382. if (this._gl.getError() !== 0) {
  10383. this._videoTextureSupported = false;
  10384. }
  10385. else {
  10386. this._videoTextureSupported = true;
  10387. }
  10388. }
  10389. // Copy video through the current working canvas if video texture is not supported
  10390. if (!this._videoTextureSupported) {
  10391. if (!texture._workingCanvas) {
  10392. texture._workingCanvas = document.createElement("canvas");
  10393. var context = texture._workingCanvas.getContext("2d");
  10394. if (!context) {
  10395. throw new Error("Unable to get 2d context");
  10396. }
  10397. texture._workingContext = context;
  10398. texture._workingCanvas.width = texture.width;
  10399. texture._workingCanvas.height = texture.height;
  10400. }
  10401. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10402. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10403. }
  10404. else {
  10405. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10406. }
  10407. if (texture.generateMipMaps) {
  10408. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10409. }
  10410. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10411. this.resetTextureCache();
  10412. texture.isReady = true;
  10413. }
  10414. catch (ex) {
  10415. // Something unexpected
  10416. // Let's disable the texture
  10417. texture._isDisabled = true;
  10418. }
  10419. };
  10420. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10421. var fullOptions = new RenderTargetCreationOptions();
  10422. if (options !== undefined && typeof options === "object") {
  10423. fullOptions.generateMipMaps = options.generateMipMaps;
  10424. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10425. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10426. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10427. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10428. }
  10429. else {
  10430. fullOptions.generateMipMaps = options;
  10431. fullOptions.generateDepthBuffer = true;
  10432. fullOptions.generateStencilBuffer = false;
  10433. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10434. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10435. }
  10436. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10437. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10438. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10439. }
  10440. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10441. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10442. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10443. }
  10444. var gl = this._gl;
  10445. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10446. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10447. var width = size.width || size;
  10448. var height = size.height || size;
  10449. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  10450. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10451. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10452. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10453. }
  10454. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10455. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10456. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10457. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10458. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10459. // Create the framebuffer
  10460. var framebuffer = gl.createFramebuffer();
  10461. this.bindUnboundFramebuffer(framebuffer);
  10462. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10463. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  10464. if (fullOptions.generateMipMaps) {
  10465. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10466. }
  10467. // Unbind
  10468. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10469. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10470. this.bindUnboundFramebuffer(null);
  10471. texture._framebuffer = framebuffer;
  10472. texture.baseWidth = width;
  10473. texture.baseHeight = height;
  10474. texture.width = width;
  10475. texture.height = height;
  10476. texture.isReady = true;
  10477. texture.samples = 1;
  10478. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  10479. texture.samplingMode = fullOptions.samplingMode;
  10480. texture.type = fullOptions.type;
  10481. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10482. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  10483. this.resetTextureCache();
  10484. this._internalTexturesCache.push(texture);
  10485. return texture;
  10486. };
  10487. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10488. var generateMipMaps = false;
  10489. var generateDepthBuffer = true;
  10490. var generateStencilBuffer = false;
  10491. var generateDepthTexture = false;
  10492. var textureCount = 1;
  10493. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10494. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10495. var types = [], samplingModes = [];
  10496. if (options !== undefined) {
  10497. generateMipMaps = options.generateMipMaps;
  10498. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10499. generateStencilBuffer = options.generateStencilBuffer;
  10500. generateDepthTexture = options.generateDepthTexture;
  10501. textureCount = options.textureCount || 1;
  10502. if (options.types) {
  10503. types = options.types;
  10504. }
  10505. if (options.samplingModes) {
  10506. samplingModes = options.samplingModes;
  10507. }
  10508. }
  10509. var gl = this._gl;
  10510. // Create the framebuffer
  10511. var framebuffer = gl.createFramebuffer();
  10512. this.bindUnboundFramebuffer(framebuffer);
  10513. var width = size.width || size;
  10514. var height = size.height || size;
  10515. var textures = [];
  10516. var attachments = [];
  10517. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10518. for (var i = 0; i < textureCount; i++) {
  10519. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10520. var type = types[i] || defaultType;
  10521. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10522. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10523. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10524. }
  10525. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10526. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10527. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10528. }
  10529. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10530. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10531. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10532. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10533. }
  10534. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10535. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10536. textures.push(texture);
  10537. attachments.push(attachment);
  10538. gl.activeTexture(gl["TEXTURE" + i]);
  10539. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10540. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10541. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10542. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10543. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10544. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10545. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10546. if (generateMipMaps) {
  10547. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10548. }
  10549. // Unbind
  10550. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10551. texture._framebuffer = framebuffer;
  10552. texture._depthStencilBuffer = depthStencilBuffer;
  10553. texture.baseWidth = width;
  10554. texture.baseHeight = height;
  10555. texture.width = width;
  10556. texture.height = height;
  10557. texture.isReady = true;
  10558. texture.samples = 1;
  10559. texture.generateMipMaps = generateMipMaps;
  10560. texture.samplingMode = samplingMode;
  10561. texture.type = type;
  10562. texture._generateDepthBuffer = generateDepthBuffer;
  10563. texture._generateStencilBuffer = generateStencilBuffer;
  10564. this._internalTexturesCache.push(texture);
  10565. }
  10566. if (generateDepthTexture && this._caps.depthTextureExtension) {
  10567. // Depth texture
  10568. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10569. gl.activeTexture(gl.TEXTURE0);
  10570. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10571. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10572. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10573. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10574. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10575. 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);
  10576. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10577. depthTexture._framebuffer = framebuffer;
  10578. depthTexture.baseWidth = width;
  10579. depthTexture.baseHeight = height;
  10580. depthTexture.width = width;
  10581. depthTexture.height = height;
  10582. depthTexture.isReady = true;
  10583. depthTexture.samples = 1;
  10584. depthTexture.generateMipMaps = generateMipMaps;
  10585. depthTexture.samplingMode = gl.NEAREST;
  10586. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10587. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10588. textures.push(depthTexture);
  10589. this._internalTexturesCache.push(depthTexture);
  10590. }
  10591. gl.drawBuffers(attachments);
  10592. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10593. this.bindUnboundFramebuffer(null);
  10594. this.resetTextureCache();
  10595. return textures;
  10596. };
  10597. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10598. if (samples === void 0) { samples = 1; }
  10599. var depthStencilBuffer = null;
  10600. var gl = this._gl;
  10601. // Create the depth/stencil buffer
  10602. if (generateStencilBuffer) {
  10603. depthStencilBuffer = gl.createRenderbuffer();
  10604. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10605. if (samples > 1) {
  10606. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10607. }
  10608. else {
  10609. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10610. }
  10611. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10612. }
  10613. else if (generateDepthBuffer) {
  10614. depthStencilBuffer = gl.createRenderbuffer();
  10615. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10616. if (samples > 1) {
  10617. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10618. }
  10619. else {
  10620. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10621. }
  10622. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10623. }
  10624. return depthStencilBuffer;
  10625. };
  10626. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10627. if (this.webGLVersion < 2 || !texture) {
  10628. return 1;
  10629. }
  10630. if (texture.samples === samples) {
  10631. return samples;
  10632. }
  10633. var gl = this._gl;
  10634. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10635. // Dispose previous render buffers
  10636. if (texture._depthStencilBuffer) {
  10637. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10638. }
  10639. if (texture._MSAAFramebuffer) {
  10640. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10641. }
  10642. if (texture._MSAARenderBuffer) {
  10643. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10644. }
  10645. if (samples > 1) {
  10646. var framebuffer = gl.createFramebuffer();
  10647. if (!framebuffer) {
  10648. throw new Error("Unable to create multi sampled framebuffer");
  10649. }
  10650. texture._MSAAFramebuffer = framebuffer;
  10651. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10652. var colorRenderbuffer = gl.createRenderbuffer();
  10653. if (!colorRenderbuffer) {
  10654. throw new Error("Unable to create multi sampled framebuffer");
  10655. }
  10656. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10657. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10658. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10659. texture._MSAARenderBuffer = colorRenderbuffer;
  10660. }
  10661. else {
  10662. this.bindUnboundFramebuffer(texture._framebuffer);
  10663. }
  10664. texture.samples = samples;
  10665. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10666. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10667. this.bindUnboundFramebuffer(null);
  10668. return samples;
  10669. };
  10670. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10671. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10672. };
  10673. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10674. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10675. };
  10676. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10677. var gl = this._gl;
  10678. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10679. var generateMipMaps = true;
  10680. var generateDepthBuffer = true;
  10681. var generateStencilBuffer = false;
  10682. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10683. if (options !== undefined) {
  10684. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10685. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10686. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  10687. if (options.samplingMode !== undefined) {
  10688. samplingMode = options.samplingMode;
  10689. }
  10690. }
  10691. texture.isCube = true;
  10692. texture.generateMipMaps = generateMipMaps;
  10693. texture.samples = 1;
  10694. texture.samplingMode = samplingMode;
  10695. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10696. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10697. for (var face = 0; face < 6; face++) {
  10698. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10699. }
  10700. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10701. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10702. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10703. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10704. // Create the framebuffer
  10705. var framebuffer = gl.createFramebuffer();
  10706. this.bindUnboundFramebuffer(framebuffer);
  10707. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10708. // Mipmaps
  10709. if (texture.generateMipMaps) {
  10710. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10711. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10712. }
  10713. // Unbind
  10714. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10715. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10716. this.bindUnboundFramebuffer(null);
  10717. texture._framebuffer = framebuffer;
  10718. texture.width = size;
  10719. texture.height = size;
  10720. texture.isReady = true;
  10721. this.resetTextureCache();
  10722. this._internalTexturesCache.push(texture);
  10723. return texture;
  10724. };
  10725. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10726. var _this = this;
  10727. if (onError === void 0) { onError = null; }
  10728. if (forcedExtension === void 0) { forcedExtension = null; }
  10729. var callback = function (loadData) {
  10730. if (!loadData) {
  10731. if (onLoad) {
  10732. onLoad(null);
  10733. }
  10734. return;
  10735. }
  10736. var texture = loadData.texture;
  10737. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10738. texture._lodGenerationScale = scale;
  10739. texture._lodGenerationOffset = offset;
  10740. if (_this._caps.textureLOD) {
  10741. // Do not add extra process if texture lod is supported.
  10742. if (onLoad) {
  10743. onLoad(texture);
  10744. }
  10745. return;
  10746. }
  10747. var mipSlices = 3;
  10748. var gl = _this._gl;
  10749. var width = loadData.width;
  10750. if (!width) {
  10751. return;
  10752. }
  10753. var textures = [];
  10754. for (var i = 0; i < mipSlices; i++) {
  10755. //compute LOD from even spacing in smoothness (matching shader calculation)
  10756. var smoothness = i / (mipSlices - 1);
  10757. var roughness = 1 - smoothness;
  10758. var minLODIndex = offset; // roughness = 0
  10759. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10760. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10761. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10762. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10763. glTextureFromLod.isCube = true;
  10764. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10765. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10766. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10767. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10768. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10769. if (loadData.isDDS) {
  10770. var info = loadData.info;
  10771. var data = loadData.data;
  10772. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10773. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  10774. }
  10775. else {
  10776. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10777. }
  10778. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10779. // Wrap in a base texture for easy binding.
  10780. var lodTexture = new BABYLON.BaseTexture(scene);
  10781. lodTexture.isCube = true;
  10782. lodTexture._texture = glTextureFromLod;
  10783. glTextureFromLod.isReady = true;
  10784. textures.push(lodTexture);
  10785. }
  10786. texture._lodTextureHigh = textures[2];
  10787. texture._lodTextureMid = textures[1];
  10788. texture._lodTextureLow = textures[0];
  10789. if (onLoad) {
  10790. onLoad(texture);
  10791. }
  10792. };
  10793. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10794. };
  10795. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10796. var _this = this;
  10797. if (onLoad === void 0) { onLoad = null; }
  10798. if (onError === void 0) { onError = null; }
  10799. if (forcedExtension === void 0) { forcedExtension = null; }
  10800. var gl = this._gl;
  10801. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  10802. texture.isCube = true;
  10803. texture.url = rootUrl;
  10804. texture.generateMipMaps = !noMipmap;
  10805. if (!this._doNotHandleContextLost) {
  10806. texture._extension = forcedExtension;
  10807. texture._files = files;
  10808. }
  10809. var isKTX = false;
  10810. var isDDS = false;
  10811. var lastDot = rootUrl.lastIndexOf('.');
  10812. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  10813. if (this._textureFormatInUse) {
  10814. extension = this._textureFormatInUse;
  10815. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  10816. isKTX = true;
  10817. }
  10818. else {
  10819. isDDS = (extension === ".dds");
  10820. }
  10821. var onerror = function (request, exception) {
  10822. if (onError) {
  10823. onError(request.status + " " + request.statusText, exception);
  10824. }
  10825. };
  10826. if (isKTX) {
  10827. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10828. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10829. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10830. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10831. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10832. ktx.uploadLevels(_this._gl, !noMipmap);
  10833. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10834. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10835. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10836. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10837. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10838. _this.resetTextureCache();
  10839. texture.width = ktx.pixelWidth;
  10840. texture.height = ktx.pixelHeight;
  10841. texture.isReady = true;
  10842. }, undefined, undefined, true, onerror);
  10843. }
  10844. else if (isDDS) {
  10845. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10846. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10847. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10848. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10849. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10850. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  10851. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10852. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10853. }
  10854. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10855. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10856. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10857. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10858. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10859. _this.resetTextureCache();
  10860. texture.width = info.width;
  10861. texture.height = info.height;
  10862. texture.isReady = true;
  10863. texture.type = info.textureType;
  10864. if (onLoad) {
  10865. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  10866. }
  10867. }, undefined, undefined, true, onerror);
  10868. }
  10869. else {
  10870. if (!files) {
  10871. throw new Error("Cannot load cubemap because files were not defined");
  10872. }
  10873. cascadeLoad(rootUrl, scene, function (imgs) {
  10874. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  10875. var height = width;
  10876. _this._prepareWorkingCanvas();
  10877. if (!_this._workingCanvas || !_this._workingContext) {
  10878. return;
  10879. }
  10880. _this._workingCanvas.width = width;
  10881. _this._workingCanvas.height = height;
  10882. var faces = [
  10883. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10884. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10885. ];
  10886. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10887. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10888. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10889. for (var index = 0; index < faces.length; index++) {
  10890. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10891. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10892. }
  10893. if (!noMipmap) {
  10894. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10895. }
  10896. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10897. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10898. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10899. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10900. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10901. _this.resetTextureCache();
  10902. texture.width = width;
  10903. texture.height = height;
  10904. texture.isReady = true;
  10905. if (format) {
  10906. texture.format = format;
  10907. }
  10908. texture.onLoadedObservable.notifyObservers(texture);
  10909. texture.onLoadedObservable.clear();
  10910. if (onLoad) {
  10911. onLoad();
  10912. }
  10913. }, files, onError);
  10914. }
  10915. this._internalTexturesCache.push(texture);
  10916. return texture;
  10917. };
  10918. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  10919. if (compression === void 0) { compression = null; }
  10920. if (level === void 0) { level = 0; }
  10921. texture._bufferViewArray = data;
  10922. texture.format = format;
  10923. texture.type = type;
  10924. texture.invertY = invertY;
  10925. texture._compression = compression;
  10926. var gl = this._gl;
  10927. var textureType = this._getWebGLTextureType(type);
  10928. var internalFormat = this._getInternalFormat(format);
  10929. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10930. var needConversion = false;
  10931. if (internalFormat === gl.RGB) {
  10932. internalFormat = gl.RGBA;
  10933. needConversion = true;
  10934. }
  10935. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10936. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10937. if (texture.width % 4 !== 0) {
  10938. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  10939. }
  10940. // Data are known to be in +X +Y +Z -X -Y -Z
  10941. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10942. var faceData = data[faceIndex];
  10943. if (compression) {
  10944. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  10945. }
  10946. else {
  10947. if (needConversion) {
  10948. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  10949. }
  10950. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  10951. }
  10952. }
  10953. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10954. if (isPot && texture.generateMipMaps && level === 0) {
  10955. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10956. }
  10957. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10958. this.resetTextureCache();
  10959. texture.isReady = true;
  10960. };
  10961. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  10962. if (compression === void 0) { compression = null; }
  10963. var gl = this._gl;
  10964. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  10965. texture.isCube = true;
  10966. texture.generateMipMaps = generateMipMaps;
  10967. texture.format = format;
  10968. texture.type = type;
  10969. if (!this._doNotHandleContextLost) {
  10970. texture._bufferViewArray = data;
  10971. }
  10972. var textureType = this._getWebGLTextureType(type);
  10973. var internalFormat = this._getInternalFormat(format);
  10974. var needConversion = false;
  10975. if (internalFormat === gl.RGB) {
  10976. internalFormat = gl.RGBA;
  10977. needConversion = true;
  10978. }
  10979. var width = size;
  10980. var height = width;
  10981. texture.width = width;
  10982. texture.height = height;
  10983. // Double check on POT to generate Mips.
  10984. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10985. if (!isPot) {
  10986. generateMipMaps = false;
  10987. }
  10988. // Upload data if needed. The texture won't be ready until then.
  10989. if (data) {
  10990. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  10991. }
  10992. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10993. // Filters
  10994. if (data && generateMipMaps) {
  10995. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10996. }
  10997. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  10998. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10999. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11000. }
  11001. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  11002. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11003. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11004. }
  11005. else {
  11006. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11007. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  11008. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  11009. }
  11010. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11011. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11012. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11013. return texture;
  11014. };
  11015. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  11016. var _this = this;
  11017. if (onLoad === void 0) { onLoad = null; }
  11018. if (onError === void 0) { onError = null; }
  11019. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11020. if (invertY === void 0) { invertY = false; }
  11021. var gl = this._gl;
  11022. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  11023. scene._addPendingData(texture);
  11024. texture.url = url;
  11025. this._internalTexturesCache.push(texture);
  11026. var onerror = function (request, exception) {
  11027. scene._removePendingData(texture);
  11028. if (onError) {
  11029. onError(request.status + " " + request.statusText, exception);
  11030. }
  11031. };
  11032. var internalCallback = function (data) {
  11033. var width = texture.width;
  11034. var faceDataArrays = callback(data);
  11035. if (mipmmapGenerator) {
  11036. var textureType = _this._getWebGLTextureType(type);
  11037. var internalFormat = _this._getInternalFormat(format);
  11038. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  11039. var needConversion = false;
  11040. if (internalFormat === gl.RGB) {
  11041. internalFormat = gl.RGBA;
  11042. needConversion = true;
  11043. }
  11044. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11045. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11046. var mipData = mipmmapGenerator(faceDataArrays);
  11047. for (var level = 0; level < mipData.length; level++) {
  11048. var mipSize = width >> level;
  11049. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11050. var mipFaceData = mipData[level][faceIndex];
  11051. if (needConversion) {
  11052. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  11053. }
  11054. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  11055. }
  11056. }
  11057. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11058. }
  11059. else {
  11060. texture.generateMipMaps = !noMipmap;
  11061. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  11062. }
  11063. texture.isReady = true;
  11064. _this.resetTextureCache();
  11065. scene._removePendingData(texture);
  11066. if (onLoad) {
  11067. onLoad();
  11068. }
  11069. };
  11070. BABYLON.Tools.LoadFile(url, function (data) {
  11071. internalCallback(data);
  11072. }, undefined, scene.database, true, onerror);
  11073. return texture;
  11074. };
  11075. ;
  11076. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  11077. var gl = this._gl;
  11078. if (!gl) {
  11079. return;
  11080. }
  11081. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  11082. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11083. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11084. if (!noMipmap && !isCompressed) {
  11085. gl.generateMipmap(gl.TEXTURE_2D);
  11086. }
  11087. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11088. this.resetTextureCache();
  11089. if (scene) {
  11090. scene._removePendingData(texture);
  11091. }
  11092. texture.onLoadedObservable.notifyObservers(texture);
  11093. texture.onLoadedObservable.clear();
  11094. };
  11095. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  11096. var _this = this;
  11097. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11098. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  11099. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  11100. var gl = this._gl;
  11101. if (!gl) {
  11102. return;
  11103. }
  11104. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11105. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11106. texture.baseWidth = width;
  11107. texture.baseHeight = height;
  11108. texture.width = potWidth;
  11109. texture.height = potHeight;
  11110. texture.isReady = true;
  11111. if (processFunction(potWidth, potHeight, function () {
  11112. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11113. })) {
  11114. // Returning as texture needs extra async steps
  11115. return;
  11116. }
  11117. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11118. };
  11119. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  11120. // Create new RGBA data container.
  11121. var rgbaData;
  11122. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  11123. rgbaData = new Float32Array(width * height * 4);
  11124. }
  11125. else {
  11126. rgbaData = new Uint32Array(width * height * 4);
  11127. }
  11128. // Convert each pixel.
  11129. for (var x = 0; x < width; x++) {
  11130. for (var y = 0; y < height; y++) {
  11131. var index = (y * width + x) * 3;
  11132. var newIndex = (y * width + x) * 4;
  11133. // Map Old Value to new value.
  11134. rgbaData[newIndex + 0] = rgbData[index + 0];
  11135. rgbaData[newIndex + 1] = rgbData[index + 1];
  11136. rgbaData[newIndex + 2] = rgbData[index + 2];
  11137. // Add fully opaque alpha channel.
  11138. rgbaData[newIndex + 3] = 1;
  11139. }
  11140. }
  11141. return rgbaData;
  11142. };
  11143. Engine.prototype._releaseFramebufferObjects = function (texture) {
  11144. var gl = this._gl;
  11145. if (texture._framebuffer) {
  11146. gl.deleteFramebuffer(texture._framebuffer);
  11147. texture._framebuffer = null;
  11148. }
  11149. if (texture._depthStencilBuffer) {
  11150. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11151. texture._depthStencilBuffer = null;
  11152. }
  11153. if (texture._MSAAFramebuffer) {
  11154. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11155. texture._MSAAFramebuffer = null;
  11156. }
  11157. if (texture._MSAARenderBuffer) {
  11158. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11159. texture._MSAARenderBuffer = null;
  11160. }
  11161. };
  11162. Engine.prototype._releaseTexture = function (texture) {
  11163. var gl = this._gl;
  11164. this._releaseFramebufferObjects(texture);
  11165. gl.deleteTexture(texture._webGLTexture);
  11166. // Unbind channels
  11167. this.unbindAllTextures();
  11168. var index = this._internalTexturesCache.indexOf(texture);
  11169. if (index !== -1) {
  11170. this._internalTexturesCache.splice(index, 1);
  11171. }
  11172. // Integrated fixed lod samplers.
  11173. if (texture._lodTextureHigh) {
  11174. texture._lodTextureHigh.dispose();
  11175. }
  11176. if (texture._lodTextureMid) {
  11177. texture._lodTextureMid.dispose();
  11178. }
  11179. if (texture._lodTextureLow) {
  11180. texture._lodTextureLow.dispose();
  11181. }
  11182. };
  11183. Engine.prototype.setProgram = function (program) {
  11184. if (this._currentProgram !== program) {
  11185. this._gl.useProgram(program);
  11186. this._currentProgram = program;
  11187. }
  11188. };
  11189. Engine.prototype.bindSamplers = function (effect) {
  11190. this.setProgram(effect.getProgram());
  11191. var samplers = effect.getSamplers();
  11192. for (var index = 0; index < samplers.length; index++) {
  11193. var uniform = effect.getUniform(samplers[index]);
  11194. this._gl.uniform1i(uniform, index);
  11195. }
  11196. this._currentEffect = null;
  11197. };
  11198. Engine.prototype.activateTexture = function (texture) {
  11199. if (this._activeTexture !== texture) {
  11200. this._gl.activeTexture(texture);
  11201. this._activeTexture = texture;
  11202. }
  11203. };
  11204. Engine.prototype._bindTextureDirectly = function (target, texture) {
  11205. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  11206. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  11207. this._activeTexturesCache[this._activeTexture] = texture;
  11208. }
  11209. };
  11210. Engine.prototype._bindTexture = function (channel, texture) {
  11211. if (channel < 0) {
  11212. return;
  11213. }
  11214. this.activateTexture(this._gl.TEXTURE0 + channel);
  11215. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  11216. };
  11217. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  11218. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  11219. };
  11220. Engine.prototype.unbindAllTextures = function () {
  11221. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  11222. this.activateTexture(this._gl["TEXTURE" + channel]);
  11223. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11224. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11225. }
  11226. };
  11227. Engine.prototype.setTexture = function (channel, uniform, texture) {
  11228. if (channel < 0) {
  11229. return;
  11230. }
  11231. this._gl.uniform1i(uniform, channel);
  11232. this._setTexture(channel, texture);
  11233. };
  11234. Engine.prototype._setTexture = function (channel, texture) {
  11235. // Not ready?
  11236. if (!texture) {
  11237. if (this._activeTexturesCache[channel] != null) {
  11238. this.activateTexture(this._gl["TEXTURE" + channel]);
  11239. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11240. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11241. }
  11242. return;
  11243. }
  11244. // Video
  11245. var alreadyActivated = false;
  11246. if (texture.video) {
  11247. this.activateTexture(this._gl["TEXTURE" + channel]);
  11248. alreadyActivated = true;
  11249. texture.update();
  11250. }
  11251. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  11252. texture.delayLoad();
  11253. return;
  11254. }
  11255. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  11256. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  11257. if (this._activeTexturesCache[channel] === internalTexture) {
  11258. return;
  11259. }
  11260. if (!alreadyActivated) {
  11261. this.activateTexture(this._gl["TEXTURE" + channel]);
  11262. }
  11263. if (internalTexture && internalTexture.isCube) {
  11264. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  11265. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  11266. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  11267. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  11268. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  11269. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  11270. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  11271. }
  11272. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  11273. }
  11274. else {
  11275. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  11276. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11277. internalTexture._cachedWrapU = texture.wrapU;
  11278. switch (texture.wrapU) {
  11279. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11280. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11281. break;
  11282. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11283. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11284. break;
  11285. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11286. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11287. break;
  11288. }
  11289. }
  11290. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11291. internalTexture._cachedWrapV = texture.wrapV;
  11292. switch (texture.wrapV) {
  11293. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11294. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11295. break;
  11296. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11297. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11298. break;
  11299. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11300. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11301. break;
  11302. }
  11303. }
  11304. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  11305. }
  11306. };
  11307. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  11308. if (channel < 0 || !uniform) {
  11309. return;
  11310. }
  11311. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  11312. this._textureUnits = new Int32Array(textures.length);
  11313. }
  11314. for (var i = 0; i < textures.length; i++) {
  11315. this._textureUnits[i] = channel + i;
  11316. }
  11317. this._gl.uniform1iv(uniform, this._textureUnits);
  11318. for (var index = 0; index < textures.length; index++) {
  11319. this._setTexture(channel + index, textures[index]);
  11320. }
  11321. };
  11322. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  11323. var internalTexture = texture.getInternalTexture();
  11324. if (!internalTexture) {
  11325. return;
  11326. }
  11327. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  11328. var value = texture.anisotropicFilteringLevel;
  11329. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  11330. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  11331. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  11332. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  11333. }
  11334. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  11335. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  11336. internalTexture._cachedAnisotropicFilteringLevel = value;
  11337. }
  11338. };
  11339. Engine.prototype.readPixels = function (x, y, width, height) {
  11340. var data = new Uint8Array(height * width * 4);
  11341. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  11342. return data;
  11343. };
  11344. /**
  11345. * Add an externaly attached data from its key.
  11346. * This method call will fail and return false, if such key already exists.
  11347. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  11348. * @param key the unique key that identifies the data
  11349. * @param data the data object to associate to the key for this Engine instance
  11350. * @return true if no such key were already present and the data was added successfully, false otherwise
  11351. */
  11352. Engine.prototype.addExternalData = function (key, data) {
  11353. if (!this._externalData) {
  11354. this._externalData = new BABYLON.StringDictionary();
  11355. }
  11356. return this._externalData.add(key, data);
  11357. };
  11358. /**
  11359. * Get an externaly attached data from its key
  11360. * @param key the unique key that identifies the data
  11361. * @return the associated data, if present (can be null), or undefined if not present
  11362. */
  11363. Engine.prototype.getExternalData = function (key) {
  11364. if (!this._externalData) {
  11365. this._externalData = new BABYLON.StringDictionary();
  11366. }
  11367. return this._externalData.get(key);
  11368. };
  11369. /**
  11370. * Get an externaly attached data from its key, create it using a factory if it's not already present
  11371. * @param key the unique key that identifies the data
  11372. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  11373. * @return the associated data, can be null if the factory returned null.
  11374. */
  11375. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  11376. if (!this._externalData) {
  11377. this._externalData = new BABYLON.StringDictionary();
  11378. }
  11379. return this._externalData.getOrAddWithFactory(key, factory);
  11380. };
  11381. /**
  11382. * Remove an externaly attached data from the Engine instance
  11383. * @param key the unique key that identifies the data
  11384. * @return true if the data was successfully removed, false if it doesn't exist
  11385. */
  11386. Engine.prototype.removeExternalData = function (key) {
  11387. if (!this._externalData) {
  11388. this._externalData = new BABYLON.StringDictionary();
  11389. }
  11390. return this._externalData.remove(key);
  11391. };
  11392. Engine.prototype.unbindAllAttributes = function () {
  11393. if (this._mustWipeVertexAttributes) {
  11394. this._mustWipeVertexAttributes = false;
  11395. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11396. this._gl.disableVertexAttribArray(i);
  11397. this._vertexAttribArraysEnabled[i] = false;
  11398. this._currentBufferPointers[i].active = false;
  11399. }
  11400. return;
  11401. }
  11402. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  11403. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  11404. continue;
  11405. }
  11406. this._gl.disableVertexAttribArray(i);
  11407. this._vertexAttribArraysEnabled[i] = false;
  11408. this._currentBufferPointers[i].active = false;
  11409. }
  11410. };
  11411. Engine.prototype.releaseEffects = function () {
  11412. for (var name in this._compiledEffects) {
  11413. this._deleteProgram(this._compiledEffects[name]._program);
  11414. }
  11415. this._compiledEffects = {};
  11416. };
  11417. // Dispose
  11418. Engine.prototype.dispose = function () {
  11419. this.hideLoadingUI();
  11420. this.stopRenderLoop();
  11421. // Release postProcesses
  11422. while (this.postProcesses.length) {
  11423. this.postProcesses[0].dispose();
  11424. }
  11425. // Empty texture
  11426. if (this._emptyTexture) {
  11427. this._releaseTexture(this._emptyTexture);
  11428. this._emptyTexture = null;
  11429. }
  11430. if (this._emptyCubeTexture) {
  11431. this._releaseTexture(this._emptyCubeTexture);
  11432. this._emptyCubeTexture = null;
  11433. }
  11434. // Rescale PP
  11435. if (this._rescalePostProcess) {
  11436. this._rescalePostProcess.dispose();
  11437. }
  11438. // Release scenes
  11439. while (this.scenes.length) {
  11440. this.scenes[0].dispose();
  11441. }
  11442. // Release audio engine
  11443. if (Engine.audioEngine) {
  11444. Engine.audioEngine.dispose();
  11445. }
  11446. // Release effects
  11447. this.releaseEffects();
  11448. // Unbind
  11449. this.unbindAllAttributes();
  11450. if (this._dummyFramebuffer) {
  11451. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  11452. }
  11453. //WebVR
  11454. this.disableVR();
  11455. // Events
  11456. window.removeEventListener("blur", this._onBlur);
  11457. window.removeEventListener("focus", this._onFocus);
  11458. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  11459. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  11460. if (this._renderingCanvas) {
  11461. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  11462. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  11463. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  11464. if (!this._doNotHandleContextLost) {
  11465. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  11466. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  11467. }
  11468. }
  11469. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  11470. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  11471. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  11472. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  11473. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  11474. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  11475. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  11476. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  11477. if (this._onVrDisplayConnect) {
  11478. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11479. if (this._onVrDisplayDisconnect) {
  11480. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11481. }
  11482. if (this._onVrDisplayPresentChange) {
  11483. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11484. }
  11485. this._onVrDisplayConnect = null;
  11486. this._onVrDisplayDisconnect = null;
  11487. }
  11488. // Remove from Instances
  11489. var index = Engine.Instances.indexOf(this);
  11490. if (index >= 0) {
  11491. Engine.Instances.splice(index, 1);
  11492. }
  11493. this._workingCanvas = null;
  11494. this._workingContext = null;
  11495. this._currentBufferPointers = [];
  11496. this._renderingCanvas = null;
  11497. this._currentProgram = null;
  11498. this.onResizeObservable.clear();
  11499. this.onCanvasBlurObservable.clear();
  11500. this.onCanvasFocusObservable.clear();
  11501. this.onCanvasPointerOutObservable.clear();
  11502. BABYLON.Effect.ResetCache();
  11503. };
  11504. // Loading screen
  11505. Engine.prototype.displayLoadingUI = function () {
  11506. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11507. return;
  11508. }
  11509. var loadingScreen = this.loadingScreen;
  11510. if (loadingScreen) {
  11511. loadingScreen.displayLoadingUI();
  11512. }
  11513. };
  11514. Engine.prototype.hideLoadingUI = function () {
  11515. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11516. return;
  11517. }
  11518. var loadingScreen = this.loadingScreen;
  11519. if (loadingScreen) {
  11520. loadingScreen.hideLoadingUI();
  11521. }
  11522. };
  11523. Object.defineProperty(Engine.prototype, "loadingScreen", {
  11524. get: function () {
  11525. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  11526. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  11527. return this._loadingScreen;
  11528. },
  11529. set: function (loadingScreen) {
  11530. this._loadingScreen = loadingScreen;
  11531. },
  11532. enumerable: true,
  11533. configurable: true
  11534. });
  11535. Object.defineProperty(Engine.prototype, "loadingUIText", {
  11536. set: function (text) {
  11537. this.loadingScreen.loadingUIText = text;
  11538. },
  11539. enumerable: true,
  11540. configurable: true
  11541. });
  11542. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  11543. set: function (color) {
  11544. this.loadingScreen.loadingUIBackgroundColor = color;
  11545. },
  11546. enumerable: true,
  11547. configurable: true
  11548. });
  11549. Engine.prototype.attachContextLostEvent = function (callback) {
  11550. if (this._renderingCanvas) {
  11551. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  11552. }
  11553. };
  11554. Engine.prototype.attachContextRestoredEvent = function (callback) {
  11555. if (this._renderingCanvas) {
  11556. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  11557. }
  11558. };
  11559. Engine.prototype.getVertexShaderSource = function (program) {
  11560. var shaders = this._gl.getAttachedShaders(program);
  11561. if (!shaders) {
  11562. return null;
  11563. }
  11564. return this._gl.getShaderSource(shaders[0]);
  11565. };
  11566. Engine.prototype.getFragmentShaderSource = function (program) {
  11567. var shaders = this._gl.getAttachedShaders(program);
  11568. if (!shaders) {
  11569. return null;
  11570. }
  11571. return this._gl.getShaderSource(shaders[1]);
  11572. };
  11573. Engine.prototype.getError = function () {
  11574. return this._gl.getError();
  11575. };
  11576. // FPS
  11577. Engine.prototype.getFps = function () {
  11578. return this._fps;
  11579. };
  11580. Engine.prototype.getDeltaTime = function () {
  11581. return this._deltaTime;
  11582. };
  11583. Engine.prototype._measureFps = function () {
  11584. this._performanceMonitor.sampleFrame();
  11585. this._fps = this._performanceMonitor.averageFPS;
  11586. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  11587. };
  11588. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  11589. if (faceIndex === void 0) { faceIndex = -1; }
  11590. var gl = this._gl;
  11591. if (!this._dummyFramebuffer) {
  11592. var dummy = gl.createFramebuffer();
  11593. if (!dummy) {
  11594. throw new Error("Unable to create dummy framebuffer");
  11595. }
  11596. this._dummyFramebuffer = dummy;
  11597. }
  11598. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  11599. if (faceIndex > -1) {
  11600. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11601. }
  11602. else {
  11603. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11604. }
  11605. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  11606. var buffer;
  11607. switch (readType) {
  11608. case gl.UNSIGNED_BYTE:
  11609. buffer = new Uint8Array(4 * width * height);
  11610. readType = gl.UNSIGNED_BYTE;
  11611. break;
  11612. default:
  11613. buffer = new Float32Array(4 * width * height);
  11614. readType = gl.FLOAT;
  11615. break;
  11616. }
  11617. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  11618. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  11619. return buffer;
  11620. };
  11621. Engine.prototype._canRenderToFloatFramebuffer = function () {
  11622. if (this._webGLVersion > 1) {
  11623. return this._caps.colorBufferFloat;
  11624. }
  11625. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  11626. };
  11627. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  11628. if (this._webGLVersion > 1) {
  11629. return this._caps.colorBufferFloat;
  11630. }
  11631. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  11632. };
  11633. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  11634. Engine.prototype._canRenderToFramebuffer = function (type) {
  11635. var gl = this._gl;
  11636. //clear existing errors
  11637. while (gl.getError() !== gl.NO_ERROR) { }
  11638. var successful = true;
  11639. var texture = gl.createTexture();
  11640. gl.bindTexture(gl.TEXTURE_2D, texture);
  11641. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11642. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11643. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11644. var fb = gl.createFramebuffer();
  11645. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  11646. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  11647. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  11648. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  11649. successful = successful && (gl.getError() === gl.NO_ERROR);
  11650. //try render by clearing frame buffer's color buffer
  11651. if (successful) {
  11652. gl.clear(gl.COLOR_BUFFER_BIT);
  11653. successful = successful && (gl.getError() === gl.NO_ERROR);
  11654. }
  11655. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  11656. if (successful) {
  11657. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  11658. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11659. var readFormat = gl.RGBA;
  11660. var readType = gl.UNSIGNED_BYTE;
  11661. var buffer = new Uint8Array(4);
  11662. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  11663. successful = successful && (gl.getError() === gl.NO_ERROR);
  11664. }
  11665. //clean up
  11666. gl.deleteTexture(texture);
  11667. gl.deleteFramebuffer(fb);
  11668. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11669. //clear accumulated errors
  11670. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  11671. return successful;
  11672. };
  11673. Engine.prototype._getWebGLTextureType = function (type) {
  11674. if (type === Engine.TEXTURETYPE_FLOAT) {
  11675. return this._gl.FLOAT;
  11676. }
  11677. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11678. // Add Half Float Constant.
  11679. return this._gl.HALF_FLOAT_OES;
  11680. }
  11681. return this._gl.UNSIGNED_BYTE;
  11682. };
  11683. ;
  11684. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  11685. if (this._webGLVersion === 1) {
  11686. return this._gl.RGBA;
  11687. }
  11688. if (type === Engine.TEXTURETYPE_FLOAT) {
  11689. return this._gl.RGBA32F;
  11690. }
  11691. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11692. return this._gl.RGBA16F;
  11693. }
  11694. return this._gl.RGBA;
  11695. };
  11696. ;
  11697. Engine.prototype.createQuery = function () {
  11698. return this._gl.createQuery();
  11699. };
  11700. Engine.prototype.deleteQuery = function (query) {
  11701. this._gl.deleteQuery(query);
  11702. return this;
  11703. };
  11704. Engine.prototype.isQueryResultAvailable = function (query) {
  11705. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  11706. };
  11707. Engine.prototype.getQueryResult = function (query) {
  11708. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  11709. };
  11710. Engine.prototype.beginQuery = function (algorithmType, query) {
  11711. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11712. this._gl.beginQuery(glAlgorithm, query);
  11713. };
  11714. Engine.prototype.endQuery = function (algorithmType) {
  11715. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11716. this._gl.endQuery(glAlgorithm);
  11717. return this;
  11718. };
  11719. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  11720. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  11721. };
  11722. // Statics
  11723. Engine.isSupported = function () {
  11724. try {
  11725. var tempcanvas = document.createElement("canvas");
  11726. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  11727. return gl != null && !!window.WebGLRenderingContext;
  11728. }
  11729. catch (e) {
  11730. return false;
  11731. }
  11732. };
  11733. Engine.Instances = new Array();
  11734. // Const statics
  11735. Engine._ALPHA_DISABLE = 0;
  11736. Engine._ALPHA_ADD = 1;
  11737. Engine._ALPHA_COMBINE = 2;
  11738. Engine._ALPHA_SUBTRACT = 3;
  11739. Engine._ALPHA_MULTIPLY = 4;
  11740. Engine._ALPHA_MAXIMIZED = 5;
  11741. Engine._ALPHA_ONEONE = 6;
  11742. Engine._ALPHA_PREMULTIPLIED = 7;
  11743. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  11744. Engine._ALPHA_INTERPOLATE = 9;
  11745. Engine._ALPHA_SCREENMODE = 10;
  11746. Engine._DELAYLOADSTATE_NONE = 0;
  11747. Engine._DELAYLOADSTATE_LOADED = 1;
  11748. Engine._DELAYLOADSTATE_LOADING = 2;
  11749. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  11750. Engine._TEXTUREFORMAT_ALPHA = 0;
  11751. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  11752. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  11753. Engine._TEXTUREFORMAT_RGB = 4;
  11754. Engine._TEXTUREFORMAT_RGBA = 5;
  11755. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  11756. Engine._TEXTURETYPE_FLOAT = 1;
  11757. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  11758. // Depht or Stencil test Constants.
  11759. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  11760. 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.
  11761. 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.
  11762. 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.
  11763. 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.
  11764. 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.
  11765. 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.
  11766. 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.
  11767. // Stencil Actions Constants.
  11768. Engine._KEEP = 0x1E00;
  11769. Engine._REPLACE = 0x1E01;
  11770. Engine._INCR = 0x1E02;
  11771. Engine._DECR = 0x1E03;
  11772. Engine._INVERT = 0x150A;
  11773. Engine._INCR_WRAP = 0x8507;
  11774. Engine._DECR_WRAP = 0x8508;
  11775. // Texture rescaling mode
  11776. Engine._SCALEMODE_FLOOR = 1;
  11777. Engine._SCALEMODE_NEAREST = 2;
  11778. Engine._SCALEMODE_CEILING = 3;
  11779. // Updatable statics so stick with vars here
  11780. Engine.CollisionsEpsilon = 0.001;
  11781. Engine.CodeRepository = "src/";
  11782. Engine.ShadersRepository = "src/Shaders/";
  11783. return Engine;
  11784. }());
  11785. BABYLON.Engine = Engine;
  11786. })(BABYLON || (BABYLON = {}));
  11787. //# sourceMappingURL=babylon.engine.js.map
  11788. /// <reference path="Tools\babylon.decorators.ts" />
  11789. var BABYLON;
  11790. (function (BABYLON) {
  11791. /**
  11792. * Node is the basic class for all scene objects (Mesh, Light Camera).
  11793. */
  11794. var Node = /** @class */ (function () {
  11795. /**
  11796. * @constructor
  11797. * @param {string} name - the name and id to be given to this node
  11798. * @param {BABYLON.Scene} the scene this node will be added to
  11799. */
  11800. function Node(name, scene) {
  11801. this.state = "";
  11802. this.metadata = null;
  11803. this.doNotSerialize = false;
  11804. this.animations = new Array();
  11805. this._ranges = {};
  11806. this._isEnabled = true;
  11807. this._isReady = true;
  11808. this._currentRenderId = -1;
  11809. this._parentRenderId = -1;
  11810. /**
  11811. * An event triggered when the mesh is disposed.
  11812. * @type {BABYLON.Observable}
  11813. */
  11814. this.onDisposeObservable = new BABYLON.Observable();
  11815. // Behaviors
  11816. this._behaviors = new Array();
  11817. this.name = name;
  11818. this.id = name;
  11819. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  11820. this.uniqueId = this._scene.getUniqueId();
  11821. this._initCache();
  11822. }
  11823. Object.defineProperty(Node.prototype, "parent", {
  11824. get: function () {
  11825. return this._parentNode;
  11826. },
  11827. set: function (parent) {
  11828. if (this._parentNode === parent) {
  11829. return;
  11830. }
  11831. if (this._parentNode) {
  11832. var index = this._parentNode._children.indexOf(this);
  11833. if (index !== -1) {
  11834. this._parentNode._children.splice(index, 1);
  11835. }
  11836. }
  11837. this._parentNode = parent;
  11838. if (this._parentNode) {
  11839. if (!this._parentNode._children) {
  11840. this._parentNode._children = new Array();
  11841. }
  11842. this._parentNode._children.push(this);
  11843. }
  11844. },
  11845. enumerable: true,
  11846. configurable: true
  11847. });
  11848. Node.prototype.getClassName = function () {
  11849. return "Node";
  11850. };
  11851. Object.defineProperty(Node.prototype, "onDispose", {
  11852. set: function (callback) {
  11853. if (this._onDisposeObserver) {
  11854. this.onDisposeObservable.remove(this._onDisposeObserver);
  11855. }
  11856. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  11857. },
  11858. enumerable: true,
  11859. configurable: true
  11860. });
  11861. Node.prototype.getScene = function () {
  11862. return this._scene;
  11863. };
  11864. Node.prototype.getEngine = function () {
  11865. return this._scene.getEngine();
  11866. };
  11867. Node.prototype.addBehavior = function (behavior) {
  11868. var index = this._behaviors.indexOf(behavior);
  11869. if (index !== -1) {
  11870. return this;
  11871. }
  11872. behavior.attach(this);
  11873. this._behaviors.push(behavior);
  11874. return this;
  11875. };
  11876. Node.prototype.removeBehavior = function (behavior) {
  11877. var index = this._behaviors.indexOf(behavior);
  11878. if (index === -1) {
  11879. return this;
  11880. }
  11881. this._behaviors[index].detach();
  11882. this._behaviors.splice(index, 1);
  11883. return this;
  11884. };
  11885. Object.defineProperty(Node.prototype, "behaviors", {
  11886. get: function () {
  11887. return this._behaviors;
  11888. },
  11889. enumerable: true,
  11890. configurable: true
  11891. });
  11892. Node.prototype.getBehaviorByName = function (name) {
  11893. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11894. var behavior = _a[_i];
  11895. if (behavior.name === name) {
  11896. return behavior;
  11897. }
  11898. }
  11899. return null;
  11900. };
  11901. // override it in derived class
  11902. Node.prototype.getWorldMatrix = function () {
  11903. return BABYLON.Matrix.Identity();
  11904. };
  11905. // override it in derived class if you add new variables to the cache
  11906. // and call the parent class method
  11907. Node.prototype._initCache = function () {
  11908. this._cache = {};
  11909. this._cache.parent = undefined;
  11910. };
  11911. Node.prototype.updateCache = function (force) {
  11912. if (!force && this.isSynchronized())
  11913. return;
  11914. this._cache.parent = this.parent;
  11915. this._updateCache();
  11916. };
  11917. // override it in derived class if you add new variables to the cache
  11918. // and call the parent class method if !ignoreParentClass
  11919. Node.prototype._updateCache = function (ignoreParentClass) {
  11920. };
  11921. // override it in derived class if you add new variables to the cache
  11922. Node.prototype._isSynchronized = function () {
  11923. return true;
  11924. };
  11925. Node.prototype._markSyncedWithParent = function () {
  11926. if (this.parent) {
  11927. this._parentRenderId = this.parent._currentRenderId;
  11928. }
  11929. };
  11930. Node.prototype.isSynchronizedWithParent = function () {
  11931. if (!this.parent) {
  11932. return true;
  11933. }
  11934. if (this._parentRenderId !== this.parent._currentRenderId) {
  11935. return false;
  11936. }
  11937. return this.parent.isSynchronized();
  11938. };
  11939. Node.prototype.isSynchronized = function (updateCache) {
  11940. var check = this.hasNewParent();
  11941. check = check || !this.isSynchronizedWithParent();
  11942. check = check || !this._isSynchronized();
  11943. if (updateCache)
  11944. this.updateCache(true);
  11945. return !check;
  11946. };
  11947. Node.prototype.hasNewParent = function (update) {
  11948. if (this._cache.parent === this.parent)
  11949. return false;
  11950. if (update)
  11951. this._cache.parent = this.parent;
  11952. return true;
  11953. };
  11954. /**
  11955. * Is this node ready to be used/rendered
  11956. * @return {boolean} is it ready
  11957. */
  11958. Node.prototype.isReady = function () {
  11959. return this._isReady;
  11960. };
  11961. /**
  11962. * Is this node enabled.
  11963. * If the node has a parent and is enabled, the parent will be inspected as well.
  11964. * @return {boolean} whether this node (and its parent) is enabled.
  11965. * @see setEnabled
  11966. */
  11967. Node.prototype.isEnabled = function () {
  11968. if (!this._isEnabled) {
  11969. return false;
  11970. }
  11971. if (this.parent) {
  11972. return this.parent.isEnabled();
  11973. }
  11974. return true;
  11975. };
  11976. /**
  11977. * Set the enabled state of this node.
  11978. * @param {boolean} value - the new enabled state
  11979. * @see isEnabled
  11980. */
  11981. Node.prototype.setEnabled = function (value) {
  11982. this._isEnabled = value;
  11983. };
  11984. /**
  11985. * Is this node a descendant of the given node.
  11986. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  11987. * @param {BABYLON.Node} ancestor - The parent node to inspect
  11988. * @see parent
  11989. */
  11990. Node.prototype.isDescendantOf = function (ancestor) {
  11991. if (this.parent) {
  11992. if (this.parent === ancestor) {
  11993. return true;
  11994. }
  11995. return this.parent.isDescendantOf(ancestor);
  11996. }
  11997. return false;
  11998. };
  11999. /**
  12000. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  12001. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  12002. * @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.
  12003. * @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.
  12004. */
  12005. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  12006. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  12007. if (!this._children) {
  12008. return;
  12009. }
  12010. for (var index = 0; index < this._children.length; index++) {
  12011. var item = this._children[index];
  12012. if (!predicate || predicate(item)) {
  12013. results.push(item);
  12014. }
  12015. if (!directDescendantsOnly) {
  12016. item._getDescendants(results, false, predicate);
  12017. }
  12018. }
  12019. };
  12020. /**
  12021. * Will return all nodes that have this node as ascendant.
  12022. * @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.
  12023. * @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.
  12024. * @return {BABYLON.Node[]} all children nodes of all types.
  12025. */
  12026. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  12027. var results = new Array();
  12028. this._getDescendants(results, directDescendantsOnly, predicate);
  12029. return results;
  12030. };
  12031. /**
  12032. * Get all child-meshes of this node.
  12033. */
  12034. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  12035. var results = [];
  12036. this._getDescendants(results, directDecendantsOnly, function (node) {
  12037. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  12038. });
  12039. return results;
  12040. };
  12041. /**
  12042. * Get all direct children of this node.
  12043. */
  12044. Node.prototype.getChildren = function (predicate) {
  12045. return this.getDescendants(true, predicate);
  12046. };
  12047. Node.prototype._setReady = function (state) {
  12048. if (state === this._isReady) {
  12049. return;
  12050. }
  12051. if (!state) {
  12052. this._isReady = false;
  12053. return;
  12054. }
  12055. this._isReady = true;
  12056. if (this.onReady) {
  12057. this.onReady(this);
  12058. }
  12059. };
  12060. Node.prototype.getAnimationByName = function (name) {
  12061. for (var i = 0; i < this.animations.length; i++) {
  12062. var animation = this.animations[i];
  12063. if (animation.name === name) {
  12064. return animation;
  12065. }
  12066. }
  12067. return null;
  12068. };
  12069. Node.prototype.createAnimationRange = function (name, from, to) {
  12070. // check name not already in use
  12071. if (!this._ranges[name]) {
  12072. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  12073. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12074. if (this.animations[i]) {
  12075. this.animations[i].createRange(name, from, to);
  12076. }
  12077. }
  12078. }
  12079. };
  12080. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  12081. if (deleteFrames === void 0) { deleteFrames = true; }
  12082. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12083. if (this.animations[i]) {
  12084. this.animations[i].deleteRange(name, deleteFrames);
  12085. }
  12086. }
  12087. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  12088. };
  12089. Node.prototype.getAnimationRange = function (name) {
  12090. return this._ranges[name];
  12091. };
  12092. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  12093. var range = this.getAnimationRange(name);
  12094. if (!range) {
  12095. return;
  12096. }
  12097. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  12098. };
  12099. Node.prototype.serializeAnimationRanges = function () {
  12100. var serializationRanges = [];
  12101. for (var name in this._ranges) {
  12102. var localRange = this._ranges[name];
  12103. if (!localRange) {
  12104. continue;
  12105. }
  12106. var range = {};
  12107. range.name = name;
  12108. range.from = localRange.from;
  12109. range.to = localRange.to;
  12110. serializationRanges.push(range);
  12111. }
  12112. return serializationRanges;
  12113. };
  12114. Node.prototype.dispose = function () {
  12115. this.parent = null;
  12116. // Callback
  12117. this.onDisposeObservable.notifyObservers(this);
  12118. this.onDisposeObservable.clear();
  12119. // Behaviors
  12120. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12121. var behavior = _a[_i];
  12122. behavior.detach();
  12123. }
  12124. this._behaviors = [];
  12125. };
  12126. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  12127. if (parsedNode.ranges) {
  12128. for (var index = 0; index < parsedNode.ranges.length; index++) {
  12129. var data = parsedNode.ranges[index];
  12130. node.createAnimationRange(data.name, data.from, data.to);
  12131. }
  12132. }
  12133. };
  12134. __decorate([
  12135. BABYLON.serialize()
  12136. ], Node.prototype, "name", void 0);
  12137. __decorate([
  12138. BABYLON.serialize()
  12139. ], Node.prototype, "id", void 0);
  12140. __decorate([
  12141. BABYLON.serialize()
  12142. ], Node.prototype, "uniqueId", void 0);
  12143. __decorate([
  12144. BABYLON.serialize()
  12145. ], Node.prototype, "state", void 0);
  12146. __decorate([
  12147. BABYLON.serialize()
  12148. ], Node.prototype, "metadata", void 0);
  12149. return Node;
  12150. }());
  12151. BABYLON.Node = Node;
  12152. })(BABYLON || (BABYLON = {}));
  12153. //# sourceMappingURL=babylon.node.js.map
  12154. var BABYLON;
  12155. (function (BABYLON) {
  12156. var BoundingSphere = /** @class */ (function () {
  12157. function BoundingSphere(minimum, maximum) {
  12158. this.minimum = minimum;
  12159. this.maximum = maximum;
  12160. this._tempRadiusVector = BABYLON.Vector3.Zero();
  12161. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  12162. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  12163. this.radius = distance * 0.5;
  12164. this.centerWorld = BABYLON.Vector3.Zero();
  12165. this._update(BABYLON.Matrix.Identity());
  12166. }
  12167. // Methods
  12168. BoundingSphere.prototype._update = function (world) {
  12169. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  12170. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  12171. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  12172. };
  12173. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  12174. for (var i = 0; i < 6; i++) {
  12175. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  12176. return false;
  12177. }
  12178. return true;
  12179. };
  12180. BoundingSphere.prototype.intersectsPoint = function (point) {
  12181. var x = this.centerWorld.x - point.x;
  12182. var y = this.centerWorld.y - point.y;
  12183. var z = this.centerWorld.z - point.z;
  12184. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12185. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  12186. return false;
  12187. return true;
  12188. };
  12189. // Statics
  12190. BoundingSphere.Intersects = function (sphere0, sphere1) {
  12191. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  12192. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  12193. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  12194. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12195. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  12196. return false;
  12197. return true;
  12198. };
  12199. return BoundingSphere;
  12200. }());
  12201. BABYLON.BoundingSphere = BoundingSphere;
  12202. })(BABYLON || (BABYLON = {}));
  12203. //# sourceMappingURL=babylon.boundingSphere.js.map
  12204. var BABYLON;
  12205. (function (BABYLON) {
  12206. var BoundingBox = /** @class */ (function () {
  12207. function BoundingBox(minimum, maximum) {
  12208. this.minimum = minimum;
  12209. this.maximum = maximum;
  12210. this.vectors = new Array();
  12211. this.vectorsWorld = new Array();
  12212. // Bounding vectors
  12213. this.vectors.push(this.minimum.clone());
  12214. this.vectors.push(this.maximum.clone());
  12215. this.vectors.push(this.minimum.clone());
  12216. this.vectors[2].x = this.maximum.x;
  12217. this.vectors.push(this.minimum.clone());
  12218. this.vectors[3].y = this.maximum.y;
  12219. this.vectors.push(this.minimum.clone());
  12220. this.vectors[4].z = this.maximum.z;
  12221. this.vectors.push(this.maximum.clone());
  12222. this.vectors[5].z = this.minimum.z;
  12223. this.vectors.push(this.maximum.clone());
  12224. this.vectors[6].x = this.minimum.x;
  12225. this.vectors.push(this.maximum.clone());
  12226. this.vectors[7].y = this.minimum.y;
  12227. // OBB
  12228. this.center = this.maximum.add(this.minimum).scale(0.5);
  12229. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  12230. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  12231. // World
  12232. for (var index = 0; index < this.vectors.length; index++) {
  12233. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  12234. }
  12235. this.minimumWorld = BABYLON.Vector3.Zero();
  12236. this.maximumWorld = BABYLON.Vector3.Zero();
  12237. this.centerWorld = BABYLON.Vector3.Zero();
  12238. this.extendSizeWorld = BABYLON.Vector3.Zero();
  12239. this._update(BABYLON.Matrix.Identity());
  12240. }
  12241. // Methods
  12242. BoundingBox.prototype.getWorldMatrix = function () {
  12243. return this._worldMatrix;
  12244. };
  12245. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  12246. this._worldMatrix.copyFrom(matrix);
  12247. return this;
  12248. };
  12249. BoundingBox.prototype._update = function (world) {
  12250. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  12251. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  12252. for (var index = 0; index < this.vectors.length; index++) {
  12253. var v = this.vectorsWorld[index];
  12254. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  12255. if (v.x < this.minimumWorld.x)
  12256. this.minimumWorld.x = v.x;
  12257. if (v.y < this.minimumWorld.y)
  12258. this.minimumWorld.y = v.y;
  12259. if (v.z < this.minimumWorld.z)
  12260. this.minimumWorld.z = v.z;
  12261. if (v.x > this.maximumWorld.x)
  12262. this.maximumWorld.x = v.x;
  12263. if (v.y > this.maximumWorld.y)
  12264. this.maximumWorld.y = v.y;
  12265. if (v.z > this.maximumWorld.z)
  12266. this.maximumWorld.z = v.z;
  12267. }
  12268. // Extend
  12269. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  12270. this.extendSizeWorld.scaleInPlace(0.5);
  12271. // OBB
  12272. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  12273. this.centerWorld.scaleInPlace(0.5);
  12274. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  12275. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  12276. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  12277. this._worldMatrix = world;
  12278. };
  12279. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  12280. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  12281. };
  12282. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12283. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  12284. };
  12285. BoundingBox.prototype.intersectsPoint = function (point) {
  12286. var delta = -BABYLON.Epsilon;
  12287. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  12288. return false;
  12289. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  12290. return false;
  12291. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  12292. return false;
  12293. return true;
  12294. };
  12295. BoundingBox.prototype.intersectsSphere = function (sphere) {
  12296. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  12297. };
  12298. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  12299. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  12300. return false;
  12301. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  12302. return false;
  12303. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  12304. return false;
  12305. return true;
  12306. };
  12307. // Statics
  12308. BoundingBox.Intersects = function (box0, box1) {
  12309. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  12310. return false;
  12311. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  12312. return false;
  12313. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  12314. return false;
  12315. return true;
  12316. };
  12317. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  12318. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  12319. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  12320. return (num <= (sphereRadius * sphereRadius));
  12321. };
  12322. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  12323. for (var p = 0; p < 6; p++) {
  12324. for (var i = 0; i < 8; i++) {
  12325. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12326. return false;
  12327. }
  12328. }
  12329. }
  12330. return true;
  12331. };
  12332. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  12333. for (var p = 0; p < 6; p++) {
  12334. var inCount = 8;
  12335. for (var i = 0; i < 8; i++) {
  12336. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12337. --inCount;
  12338. }
  12339. else {
  12340. break;
  12341. }
  12342. }
  12343. if (inCount === 0)
  12344. return false;
  12345. }
  12346. return true;
  12347. };
  12348. return BoundingBox;
  12349. }());
  12350. BABYLON.BoundingBox = BoundingBox;
  12351. })(BABYLON || (BABYLON = {}));
  12352. //# sourceMappingURL=babylon.boundingBox.js.map
  12353. var BABYLON;
  12354. (function (BABYLON) {
  12355. var computeBoxExtents = function (axis, box) {
  12356. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  12357. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  12358. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  12359. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  12360. var r = r0 + r1 + r2;
  12361. return {
  12362. min: p - r,
  12363. max: p + r
  12364. };
  12365. };
  12366. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  12367. var axisOverlap = function (axis, box0, box1) {
  12368. var result0 = computeBoxExtents(axis, box0);
  12369. var result1 = computeBoxExtents(axis, box1);
  12370. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  12371. };
  12372. var BoundingInfo = /** @class */ (function () {
  12373. function BoundingInfo(minimum, maximum) {
  12374. this.minimum = minimum;
  12375. this.maximum = maximum;
  12376. this._isLocked = false;
  12377. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  12378. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  12379. }
  12380. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  12381. get: function () {
  12382. return this._isLocked;
  12383. },
  12384. set: function (value) {
  12385. this._isLocked = value;
  12386. },
  12387. enumerable: true,
  12388. configurable: true
  12389. });
  12390. // Methods
  12391. BoundingInfo.prototype.update = function (world) {
  12392. if (this._isLocked) {
  12393. return;
  12394. }
  12395. this.boundingBox._update(world);
  12396. this.boundingSphere._update(world);
  12397. };
  12398. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  12399. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  12400. return false;
  12401. return this.boundingBox.isInFrustum(frustumPlanes);
  12402. };
  12403. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  12404. /**
  12405. * Gets the world distance between the min and max points of the bounding box
  12406. */
  12407. get: function () {
  12408. var boundingBox = this.boundingBox;
  12409. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  12410. return size.length();
  12411. },
  12412. enumerable: true,
  12413. configurable: true
  12414. });
  12415. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12416. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  12417. };
  12418. BoundingInfo.prototype._checkCollision = function (collider) {
  12419. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  12420. };
  12421. BoundingInfo.prototype.intersectsPoint = function (point) {
  12422. if (!this.boundingSphere.centerWorld) {
  12423. return false;
  12424. }
  12425. if (!this.boundingSphere.intersectsPoint(point)) {
  12426. return false;
  12427. }
  12428. if (!this.boundingBox.intersectsPoint(point)) {
  12429. return false;
  12430. }
  12431. return true;
  12432. };
  12433. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  12434. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  12435. return false;
  12436. }
  12437. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  12438. return false;
  12439. }
  12440. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  12441. return false;
  12442. }
  12443. if (!precise) {
  12444. return true;
  12445. }
  12446. var box0 = this.boundingBox;
  12447. var box1 = boundingInfo.boundingBox;
  12448. if (!axisOverlap(box0.directions[0], box0, box1))
  12449. return false;
  12450. if (!axisOverlap(box0.directions[1], box0, box1))
  12451. return false;
  12452. if (!axisOverlap(box0.directions[2], box0, box1))
  12453. return false;
  12454. if (!axisOverlap(box1.directions[0], box0, box1))
  12455. return false;
  12456. if (!axisOverlap(box1.directions[1], box0, box1))
  12457. return false;
  12458. if (!axisOverlap(box1.directions[2], box0, box1))
  12459. return false;
  12460. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  12461. return false;
  12462. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  12463. return false;
  12464. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  12465. return false;
  12466. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  12467. return false;
  12468. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  12469. return false;
  12470. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  12471. return false;
  12472. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  12473. return false;
  12474. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  12475. return false;
  12476. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  12477. return false;
  12478. return true;
  12479. };
  12480. return BoundingInfo;
  12481. }());
  12482. BABYLON.BoundingInfo = BoundingInfo;
  12483. })(BABYLON || (BABYLON = {}));
  12484. //# sourceMappingURL=babylon.boundingInfo.js.map
  12485. var BABYLON;
  12486. (function (BABYLON) {
  12487. var AbstractMesh = /** @class */ (function (_super) {
  12488. __extends(AbstractMesh, _super);
  12489. // Constructor
  12490. function AbstractMesh(name, scene) {
  12491. var _this = _super.call(this, name, scene) || this;
  12492. _this._facetNb = 0; // facet number
  12493. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  12494. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  12495. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  12496. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  12497. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  12498. _this._subDiv = {
  12499. max: 1,
  12500. X: 1,
  12501. Y: 1,
  12502. Z: 1
  12503. };
  12504. // Normal matrix
  12505. _this._nonUniformScaling = false;
  12506. // Events
  12507. /**
  12508. * An event triggered when this mesh collides with another one
  12509. * @type {BABYLON.Observable}
  12510. */
  12511. _this.onCollideObservable = new BABYLON.Observable();
  12512. /**
  12513. * An event triggered when the collision's position changes
  12514. * @type {BABYLON.Observable}
  12515. */
  12516. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  12517. /**
  12518. * An event triggered after the world matrix is updated
  12519. * @type {BABYLON.Observable}
  12520. */
  12521. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  12522. /**
  12523. * An event triggered when material is changed
  12524. * @type {BABYLON.Observable}
  12525. */
  12526. _this.onMaterialChangedObservable = new BABYLON.Observable();
  12527. // Properties
  12528. _this.definedFacingForward = true; // orientation for POV movement & rotation
  12529. _this.position = BABYLON.Vector3.Zero();
  12530. /**
  12531. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  12532. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  12533. * or
  12534. * 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.
  12535. * for more info check WebGl documentations
  12536. */
  12537. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  12538. /**
  12539. * 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:
  12540. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  12541. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  12542. * 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.
  12543. */
  12544. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  12545. /**
  12546. * 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.
  12547. * The default value is -1 which means don't break the query and wait till the result.
  12548. */
  12549. _this.occlusionRetryCount = -1;
  12550. _this._occlusionInternalRetryCounter = 0;
  12551. _this._isOccluded = false;
  12552. _this._isOcclusionQueryInProgress = false;
  12553. _this._rotation = BABYLON.Vector3.Zero();
  12554. _this._scaling = BABYLON.Vector3.One();
  12555. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  12556. _this.visibility = 1.0;
  12557. _this.alphaIndex = Number.MAX_VALUE;
  12558. _this.infiniteDistance = false;
  12559. _this.isVisible = true;
  12560. _this.isPickable = true;
  12561. _this.showBoundingBox = false;
  12562. _this.showSubMeshesBoundingBox = false;
  12563. _this.isBlocker = false;
  12564. _this.enablePointerMoveEvents = false;
  12565. _this.renderingGroupId = 0;
  12566. _this._receiveShadows = false;
  12567. _this.renderOutline = false;
  12568. _this.outlineColor = BABYLON.Color3.Red();
  12569. _this.outlineWidth = 0.02;
  12570. _this.renderOverlay = false;
  12571. _this.overlayColor = BABYLON.Color3.Red();
  12572. _this.overlayAlpha = 0.5;
  12573. _this._hasVertexAlpha = false;
  12574. _this._useVertexColors = true;
  12575. _this._computeBonesUsingShaders = true;
  12576. _this._numBoneInfluencers = 4;
  12577. _this._applyFog = true;
  12578. _this.scalingDeterminant = 1;
  12579. _this.useOctreeForRenderingSelection = true;
  12580. _this.useOctreeForPicking = true;
  12581. _this.useOctreeForCollisions = true;
  12582. _this._layerMask = 0x0FFFFFFF;
  12583. /**
  12584. * True if the mesh must be rendered in any case.
  12585. */
  12586. _this.alwaysSelectAsActiveMesh = false;
  12587. // Collisions
  12588. _this._checkCollisions = false;
  12589. _this._collisionMask = -1;
  12590. _this._collisionGroup = -1;
  12591. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12592. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  12593. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12594. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12595. // Edges
  12596. _this.edgesWidth = 1;
  12597. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  12598. // Cache
  12599. _this._localWorld = BABYLON.Matrix.Zero();
  12600. _this._worldMatrix = BABYLON.Matrix.Zero();
  12601. _this._absolutePosition = BABYLON.Vector3.Zero();
  12602. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  12603. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  12604. _this._isDirty = false;
  12605. _this._pivotMatrix = BABYLON.Matrix.Identity();
  12606. _this._postMultiplyPivotMatrix = false;
  12607. _this._isDisposed = false;
  12608. _this._renderId = 0;
  12609. _this._intersectionsInProgress = new Array();
  12610. _this._isWorldMatrixFrozen = false;
  12611. _this._unIndexed = false;
  12612. _this._lightSources = new Array();
  12613. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12614. if (collidedMesh === void 0) { collidedMesh = null; }
  12615. //TODO move this to the collision coordinator!
  12616. if (_this.getScene().workerCollisions)
  12617. newPosition.multiplyInPlace(_this._collider.radius);
  12618. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  12619. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  12620. _this.position.addInPlace(_this._diffPositionForCollisions);
  12621. }
  12622. if (collidedMesh) {
  12623. _this.onCollideObservable.notifyObservers(collidedMesh);
  12624. }
  12625. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  12626. };
  12627. _this.getScene().addMesh(_this);
  12628. _this._resyncLightSources();
  12629. return _this;
  12630. }
  12631. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  12632. get: function () {
  12633. return AbstractMesh._BILLBOARDMODE_NONE;
  12634. },
  12635. enumerable: true,
  12636. configurable: true
  12637. });
  12638. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  12639. get: function () {
  12640. return AbstractMesh._BILLBOARDMODE_X;
  12641. },
  12642. enumerable: true,
  12643. configurable: true
  12644. });
  12645. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  12646. get: function () {
  12647. return AbstractMesh._BILLBOARDMODE_Y;
  12648. },
  12649. enumerable: true,
  12650. configurable: true
  12651. });
  12652. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  12653. get: function () {
  12654. return AbstractMesh._BILLBOARDMODE_Z;
  12655. },
  12656. enumerable: true,
  12657. configurable: true
  12658. });
  12659. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  12660. get: function () {
  12661. return AbstractMesh._BILLBOARDMODE_ALL;
  12662. },
  12663. enumerable: true,
  12664. configurable: true
  12665. });
  12666. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  12667. /**
  12668. * Read-only : the number of facets in the mesh
  12669. */
  12670. get: function () {
  12671. return this._facetNb;
  12672. },
  12673. enumerable: true,
  12674. configurable: true
  12675. });
  12676. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  12677. /**
  12678. * The number (integer) of subdivisions per axis in the partioning space
  12679. */
  12680. get: function () {
  12681. return this._partitioningSubdivisions;
  12682. },
  12683. set: function (nb) {
  12684. this._partitioningSubdivisions = nb;
  12685. },
  12686. enumerable: true,
  12687. configurable: true
  12688. });
  12689. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  12690. /**
  12691. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  12692. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  12693. */
  12694. get: function () {
  12695. return this._partitioningBBoxRatio;
  12696. },
  12697. set: function (ratio) {
  12698. this._partitioningBBoxRatio = ratio;
  12699. },
  12700. enumerable: true,
  12701. configurable: true
  12702. });
  12703. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  12704. /**
  12705. * Read-only boolean : is the feature facetData enabled ?
  12706. */
  12707. get: function () {
  12708. return this._facetDataEnabled;
  12709. },
  12710. enumerable: true,
  12711. configurable: true
  12712. });
  12713. Object.defineProperty(AbstractMesh.prototype, "nonUniformScaling", {
  12714. get: function () {
  12715. return this._nonUniformScaling;
  12716. },
  12717. set: function (value) {
  12718. if (this._nonUniformScaling === value) {
  12719. return;
  12720. }
  12721. this._nonUniformScaling = true;
  12722. this._markSubMeshesAsMiscDirty();
  12723. },
  12724. enumerable: true,
  12725. configurable: true
  12726. });
  12727. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  12728. set: function (callback) {
  12729. if (this._onCollideObserver) {
  12730. this.onCollideObservable.remove(this._onCollideObserver);
  12731. }
  12732. this._onCollideObserver = this.onCollideObservable.add(callback);
  12733. },
  12734. enumerable: true,
  12735. configurable: true
  12736. });
  12737. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  12738. set: function (callback) {
  12739. if (this._onCollisionPositionChangeObserver) {
  12740. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  12741. }
  12742. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  12743. },
  12744. enumerable: true,
  12745. configurable: true
  12746. });
  12747. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  12748. /**
  12749. * 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.
  12750. */
  12751. get: function () {
  12752. return this._isOccluded;
  12753. },
  12754. set: function (value) {
  12755. this._isOccluded = value;
  12756. },
  12757. enumerable: true,
  12758. configurable: true
  12759. });
  12760. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  12761. /**
  12762. * Flag to check the progress status of the query
  12763. */
  12764. get: function () {
  12765. return this._isOcclusionQueryInProgress;
  12766. },
  12767. enumerable: true,
  12768. configurable: true
  12769. });
  12770. Object.defineProperty(AbstractMesh.prototype, "material", {
  12771. get: function () {
  12772. return this._material;
  12773. },
  12774. set: function (value) {
  12775. if (this._material === value) {
  12776. return;
  12777. }
  12778. this._material = value;
  12779. if (this.onMaterialChangedObservable.hasObservers) {
  12780. this.onMaterialChangedObservable.notifyObservers(this);
  12781. }
  12782. if (!this.subMeshes) {
  12783. return;
  12784. }
  12785. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12786. var subMesh = _a[_i];
  12787. subMesh.setEffect(null);
  12788. }
  12789. },
  12790. enumerable: true,
  12791. configurable: true
  12792. });
  12793. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  12794. get: function () {
  12795. return this._receiveShadows;
  12796. },
  12797. set: function (value) {
  12798. if (this._receiveShadows === value) {
  12799. return;
  12800. }
  12801. this._receiveShadows = value;
  12802. this._markSubMeshesAsLightDirty();
  12803. },
  12804. enumerable: true,
  12805. configurable: true
  12806. });
  12807. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  12808. get: function () {
  12809. return this._hasVertexAlpha;
  12810. },
  12811. set: function (value) {
  12812. if (this._hasVertexAlpha === value) {
  12813. return;
  12814. }
  12815. this._hasVertexAlpha = value;
  12816. this._markSubMeshesAsAttributesDirty();
  12817. },
  12818. enumerable: true,
  12819. configurable: true
  12820. });
  12821. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  12822. get: function () {
  12823. return this._useVertexColors;
  12824. },
  12825. set: function (value) {
  12826. if (this._useVertexColors === value) {
  12827. return;
  12828. }
  12829. this._useVertexColors = value;
  12830. this._markSubMeshesAsAttributesDirty();
  12831. },
  12832. enumerable: true,
  12833. configurable: true
  12834. });
  12835. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  12836. get: function () {
  12837. return this._computeBonesUsingShaders;
  12838. },
  12839. set: function (value) {
  12840. if (this._computeBonesUsingShaders === value) {
  12841. return;
  12842. }
  12843. this._computeBonesUsingShaders = value;
  12844. this._markSubMeshesAsAttributesDirty();
  12845. },
  12846. enumerable: true,
  12847. configurable: true
  12848. });
  12849. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  12850. get: function () {
  12851. return this._numBoneInfluencers;
  12852. },
  12853. set: function (value) {
  12854. if (this._numBoneInfluencers === value) {
  12855. return;
  12856. }
  12857. this._numBoneInfluencers = value;
  12858. this._markSubMeshesAsAttributesDirty();
  12859. },
  12860. enumerable: true,
  12861. configurable: true
  12862. });
  12863. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  12864. get: function () {
  12865. return this._applyFog;
  12866. },
  12867. set: function (value) {
  12868. if (this._applyFog === value) {
  12869. return;
  12870. }
  12871. this._applyFog = value;
  12872. this._markSubMeshesAsMiscDirty();
  12873. },
  12874. enumerable: true,
  12875. configurable: true
  12876. });
  12877. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  12878. get: function () {
  12879. return this._layerMask;
  12880. },
  12881. set: function (value) {
  12882. if (value === this._layerMask) {
  12883. return;
  12884. }
  12885. this._layerMask = value;
  12886. this._resyncLightSources();
  12887. },
  12888. enumerable: true,
  12889. configurable: true
  12890. });
  12891. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  12892. get: function () {
  12893. return this._collisionMask;
  12894. },
  12895. set: function (mask) {
  12896. this._collisionMask = !isNaN(mask) ? mask : -1;
  12897. },
  12898. enumerable: true,
  12899. configurable: true
  12900. });
  12901. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  12902. get: function () {
  12903. return this._collisionGroup;
  12904. },
  12905. set: function (mask) {
  12906. this._collisionGroup = !isNaN(mask) ? mask : -1;
  12907. },
  12908. enumerable: true,
  12909. configurable: true
  12910. });
  12911. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  12912. get: function () {
  12913. return null;
  12914. },
  12915. enumerable: true,
  12916. configurable: true
  12917. });
  12918. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  12919. get: function () {
  12920. return this._skeleton;
  12921. },
  12922. set: function (value) {
  12923. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  12924. this._skeleton._unregisterMeshWithPoseMatrix(this);
  12925. }
  12926. if (value && value.needInitialSkinMatrix) {
  12927. value._registerMeshWithPoseMatrix(this);
  12928. }
  12929. this._skeleton = value;
  12930. if (!this._skeleton) {
  12931. this._bonesTransformMatrices = null;
  12932. }
  12933. this._markSubMeshesAsAttributesDirty();
  12934. },
  12935. enumerable: true,
  12936. configurable: true
  12937. });
  12938. /**
  12939. * Boolean : true if the mesh has been disposed.
  12940. */
  12941. AbstractMesh.prototype.isDisposed = function () {
  12942. return this._isDisposed;
  12943. };
  12944. /**
  12945. * Returns the string "AbstractMesh"
  12946. */
  12947. AbstractMesh.prototype.getClassName = function () {
  12948. return "AbstractMesh";
  12949. };
  12950. /**
  12951. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12952. */
  12953. AbstractMesh.prototype.toString = function (fullDetails) {
  12954. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  12955. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  12956. if (this._skeleton) {
  12957. ret += ", skeleton: " + this._skeleton.name;
  12958. }
  12959. if (fullDetails) {
  12960. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  12961. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  12962. }
  12963. return ret;
  12964. };
  12965. AbstractMesh.prototype._rebuild = function () {
  12966. if (this._occlusionQuery) {
  12967. this._occlusionQuery = null;
  12968. }
  12969. if (this._edgesRenderer) {
  12970. this._edgesRenderer._rebuild();
  12971. }
  12972. if (!this.subMeshes) {
  12973. return;
  12974. }
  12975. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12976. var subMesh = _a[_i];
  12977. subMesh._rebuild();
  12978. }
  12979. };
  12980. AbstractMesh.prototype._resyncLightSources = function () {
  12981. this._lightSources.length = 0;
  12982. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  12983. var light = _a[_i];
  12984. if (!light.isEnabled()) {
  12985. continue;
  12986. }
  12987. if (light.canAffectMesh(this)) {
  12988. this._lightSources.push(light);
  12989. }
  12990. }
  12991. this._markSubMeshesAsLightDirty();
  12992. };
  12993. AbstractMesh.prototype._resyncLighSource = function (light) {
  12994. var isIn = light.isEnabled() && light.canAffectMesh(this);
  12995. var index = this._lightSources.indexOf(light);
  12996. if (index === -1) {
  12997. if (!isIn) {
  12998. return;
  12999. }
  13000. this._lightSources.push(light);
  13001. }
  13002. else {
  13003. if (isIn) {
  13004. return;
  13005. }
  13006. this._lightSources.splice(index, 1);
  13007. }
  13008. this._markSubMeshesAsLightDirty();
  13009. };
  13010. AbstractMesh.prototype._removeLightSource = function (light) {
  13011. var index = this._lightSources.indexOf(light);
  13012. if (index === -1) {
  13013. return;
  13014. }
  13015. this._lightSources.splice(index, 1);
  13016. };
  13017. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  13018. if (!this.subMeshes) {
  13019. return;
  13020. }
  13021. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13022. var subMesh = _a[_i];
  13023. if (subMesh._materialDefines) {
  13024. func(subMesh._materialDefines);
  13025. }
  13026. }
  13027. };
  13028. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  13029. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  13030. };
  13031. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  13032. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  13033. };
  13034. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  13035. if (!this.subMeshes) {
  13036. return;
  13037. }
  13038. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13039. var subMesh = _a[_i];
  13040. var material = subMesh.getMaterial();
  13041. if (material) {
  13042. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  13043. }
  13044. }
  13045. };
  13046. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  13047. /**
  13048. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  13049. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  13050. * Default : (0.0, 0.0, 0.0)
  13051. */
  13052. get: function () {
  13053. return this._rotation;
  13054. },
  13055. set: function (newRotation) {
  13056. this._rotation = newRotation;
  13057. },
  13058. enumerable: true,
  13059. configurable: true
  13060. });
  13061. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  13062. /**
  13063. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13064. * Default : (1.0, 1.0, 1.0)
  13065. */
  13066. get: function () {
  13067. return this._scaling;
  13068. },
  13069. set: function (newScaling) {
  13070. this._scaling = newScaling;
  13071. if (this.physicsImpostor) {
  13072. this.physicsImpostor.forceUpdate();
  13073. }
  13074. },
  13075. enumerable: true,
  13076. configurable: true
  13077. });
  13078. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  13079. /**
  13080. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  13081. * It's null by default.
  13082. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  13083. */
  13084. get: function () {
  13085. return this._rotationQuaternion;
  13086. },
  13087. set: function (quaternion) {
  13088. this._rotationQuaternion = quaternion;
  13089. //reset the rotation vector.
  13090. if (quaternion && this.rotation.length()) {
  13091. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  13092. }
  13093. },
  13094. enumerable: true,
  13095. configurable: true
  13096. });
  13097. // Methods
  13098. /**
  13099. * Copies the paramater passed Matrix into the mesh Pose matrix.
  13100. * Returns the AbstractMesh.
  13101. */
  13102. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  13103. this._poseMatrix.copyFrom(matrix);
  13104. return this;
  13105. };
  13106. /**
  13107. * Returns the mesh Pose matrix.
  13108. * Returned object : Matrix
  13109. */
  13110. AbstractMesh.prototype.getPoseMatrix = function () {
  13111. return this._poseMatrix;
  13112. };
  13113. /**
  13114. * Disables the mesh edger rendering mode.
  13115. * Returns the AbstractMesh.
  13116. */
  13117. AbstractMesh.prototype.disableEdgesRendering = function () {
  13118. if (this._edgesRenderer) {
  13119. this._edgesRenderer.dispose();
  13120. this._edgesRenderer = null;
  13121. }
  13122. return this;
  13123. };
  13124. /**
  13125. * Enables the edge rendering mode on the mesh.
  13126. * This mode makes the mesh edges visible.
  13127. * Returns the AbstractMesh.
  13128. */
  13129. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  13130. if (epsilon === void 0) { epsilon = 0.95; }
  13131. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  13132. this.disableEdgesRendering();
  13133. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  13134. return this;
  13135. };
  13136. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  13137. /**
  13138. * Returns true if the mesh is blocked. Used by the class Mesh.
  13139. * Returns the boolean `false` by default.
  13140. */
  13141. get: function () {
  13142. return false;
  13143. },
  13144. enumerable: true,
  13145. configurable: true
  13146. });
  13147. /**
  13148. * Returns the mesh itself by default, used by the class Mesh.
  13149. * Returned type : AbstractMesh
  13150. */
  13151. AbstractMesh.prototype.getLOD = function (camera) {
  13152. return this;
  13153. };
  13154. /**
  13155. * Returns 0 by default, used by the class Mesh.
  13156. * Returns an integer.
  13157. */
  13158. AbstractMesh.prototype.getTotalVertices = function () {
  13159. return 0;
  13160. };
  13161. /**
  13162. * Returns null by default, used by the class Mesh.
  13163. * Returned type : integer array
  13164. */
  13165. AbstractMesh.prototype.getIndices = function () {
  13166. return null;
  13167. };
  13168. /**
  13169. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  13170. * Returned type : float array or Float32Array
  13171. */
  13172. AbstractMesh.prototype.getVerticesData = function (kind) {
  13173. return null;
  13174. };
  13175. /**
  13176. * Sets the vertex data of the mesh geometry for the requested `kind`.
  13177. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  13178. * The `data` are either a numeric array either a Float32Array.
  13179. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  13180. * 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).
  13181. * Note that a new underlying VertexBuffer object is created each call.
  13182. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  13183. *
  13184. * Possible `kind` values :
  13185. * - BABYLON.VertexBuffer.PositionKind
  13186. * - BABYLON.VertexBuffer.UVKind
  13187. * - BABYLON.VertexBuffer.UV2Kind
  13188. * - BABYLON.VertexBuffer.UV3Kind
  13189. * - BABYLON.VertexBuffer.UV4Kind
  13190. * - BABYLON.VertexBuffer.UV5Kind
  13191. * - BABYLON.VertexBuffer.UV6Kind
  13192. * - BABYLON.VertexBuffer.ColorKind
  13193. * - BABYLON.VertexBuffer.MatricesIndicesKind
  13194. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  13195. * - BABYLON.VertexBuffer.MatricesWeightsKind
  13196. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  13197. *
  13198. * Returns the Mesh.
  13199. */
  13200. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  13201. return this;
  13202. };
  13203. /**
  13204. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  13205. * If the mesh has no geometry, it is simply returned as it is.
  13206. * The `data` are either a numeric array either a Float32Array.
  13207. * No new underlying VertexBuffer object is created.
  13208. * 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.
  13209. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  13210. *
  13211. * Possible `kind` values :
  13212. * - BABYLON.VertexBuffer.PositionKind
  13213. * - BABYLON.VertexBuffer.UVKind
  13214. * - BABYLON.VertexBuffer.UV2Kind
  13215. * - BABYLON.VertexBuffer.UV3Kind
  13216. * - BABYLON.VertexBuffer.UV4Kind
  13217. * - BABYLON.VertexBuffer.UV5Kind
  13218. * - BABYLON.VertexBuffer.UV6Kind
  13219. * - BABYLON.VertexBuffer.ColorKind
  13220. * - BABYLON.VertexBuffer.MatricesIndicesKind
  13221. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  13222. * - BABYLON.VertexBuffer.MatricesWeightsKind
  13223. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  13224. *
  13225. * Returns the Mesh.
  13226. */
  13227. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  13228. return this;
  13229. };
  13230. /**
  13231. * Sets the mesh indices.
  13232. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  13233. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  13234. * This method creates a new index buffer each call.
  13235. * Returns the Mesh.
  13236. */
  13237. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  13238. return this;
  13239. };
  13240. /** Returns false by default, used by the class Mesh.
  13241. * Returns a boolean
  13242. */
  13243. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  13244. return false;
  13245. };
  13246. /**
  13247. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  13248. * Returns a BoundingInfo
  13249. */
  13250. AbstractMesh.prototype.getBoundingInfo = function () {
  13251. if (this._masterMesh) {
  13252. return this._masterMesh.getBoundingInfo();
  13253. }
  13254. if (!this._boundingInfo) {
  13255. this._updateBoundingInfo();
  13256. }
  13257. return this._boundingInfo;
  13258. };
  13259. /**
  13260. * Sets a mesh new object BoundingInfo.
  13261. * Returns the AbstractMesh.
  13262. */
  13263. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  13264. this._boundingInfo = boundingInfo;
  13265. return this;
  13266. };
  13267. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  13268. get: function () {
  13269. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  13270. },
  13271. enumerable: true,
  13272. configurable: true
  13273. });
  13274. AbstractMesh.prototype._preActivate = function () {
  13275. };
  13276. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  13277. };
  13278. AbstractMesh.prototype._activate = function (renderId) {
  13279. this._renderId = renderId;
  13280. };
  13281. /**
  13282. * Returns the last update of the World matrix
  13283. * Returns a Matrix.
  13284. */
  13285. AbstractMesh.prototype.getWorldMatrix = function () {
  13286. if (this._masterMesh) {
  13287. return this._masterMesh.getWorldMatrix();
  13288. }
  13289. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  13290. this.computeWorldMatrix();
  13291. }
  13292. return this._worldMatrix;
  13293. };
  13294. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  13295. /**
  13296. * Returns directly the last state of the mesh World matrix.
  13297. * A Matrix is returned.
  13298. */
  13299. get: function () {
  13300. return this._worldMatrix;
  13301. },
  13302. enumerable: true,
  13303. configurable: true
  13304. });
  13305. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  13306. /**
  13307. * Returns the current mesh absolute position.
  13308. * Retuns a Vector3.
  13309. */
  13310. get: function () {
  13311. return this._absolutePosition;
  13312. },
  13313. enumerable: true,
  13314. configurable: true
  13315. });
  13316. /**
  13317. * Prevents the World matrix to be computed any longer.
  13318. * Returns the AbstractMesh.
  13319. */
  13320. AbstractMesh.prototype.freezeWorldMatrix = function () {
  13321. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  13322. this.computeWorldMatrix(true);
  13323. this._isWorldMatrixFrozen = true;
  13324. return this;
  13325. };
  13326. /**
  13327. * Allows back the World matrix computation.
  13328. * Returns the AbstractMesh.
  13329. */
  13330. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  13331. this._isWorldMatrixFrozen = false;
  13332. this.computeWorldMatrix(true);
  13333. return this;
  13334. };
  13335. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  13336. /**
  13337. * True if the World matrix has been frozen.
  13338. * Returns a boolean.
  13339. */
  13340. get: function () {
  13341. return this._isWorldMatrixFrozen;
  13342. },
  13343. enumerable: true,
  13344. configurable: true
  13345. });
  13346. /**
  13347. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  13348. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13349. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13350. * The passed axis is also normalized.
  13351. * Returns the AbstractMesh.
  13352. */
  13353. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  13354. axis.normalize();
  13355. if (!this.rotationQuaternion) {
  13356. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13357. this.rotation = BABYLON.Vector3.Zero();
  13358. }
  13359. var rotationQuaternion;
  13360. if (!space || space === BABYLON.Space.LOCAL) {
  13361. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13362. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  13363. }
  13364. else {
  13365. if (this.parent) {
  13366. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13367. invertParentWorldMatrix.invert();
  13368. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  13369. }
  13370. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13371. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13372. }
  13373. return this;
  13374. };
  13375. /**
  13376. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  13377. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13378. * The passed axis is also normalized.
  13379. * Returns the AbstractMesh.
  13380. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  13381. */
  13382. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  13383. axis.normalize();
  13384. if (!this.rotationQuaternion) {
  13385. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13386. this.rotation.copyFromFloats(0, 0, 0);
  13387. }
  13388. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  13389. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  13390. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  13391. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  13392. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  13393. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  13394. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  13395. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  13396. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13397. return this;
  13398. };
  13399. /**
  13400. * Translates the mesh along the axis vector for the passed distance in the given space.
  13401. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13402. * Returns the AbstractMesh.
  13403. */
  13404. AbstractMesh.prototype.translate = function (axis, distance, space) {
  13405. var displacementVector = axis.scale(distance);
  13406. if (!space || space === BABYLON.Space.LOCAL) {
  13407. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  13408. this.setPositionWithLocalVector(tempV3);
  13409. }
  13410. else {
  13411. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  13412. }
  13413. return this;
  13414. };
  13415. /**
  13416. * Adds a rotation step to the mesh current rotation.
  13417. * x, y, z are Euler angles expressed in radians.
  13418. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  13419. * This means this rotation is made in the mesh local space only.
  13420. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  13421. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  13422. * ```javascript
  13423. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  13424. * ```
  13425. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  13426. * 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.
  13427. * Returns the AbstractMesh.
  13428. */
  13429. AbstractMesh.prototype.addRotation = function (x, y, z) {
  13430. var rotationQuaternion;
  13431. if (this.rotationQuaternion) {
  13432. rotationQuaternion = this.rotationQuaternion;
  13433. }
  13434. else {
  13435. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  13436. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  13437. }
  13438. var accumulation = BABYLON.Tmp.Quaternion[0];
  13439. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  13440. rotationQuaternion.multiplyInPlace(accumulation);
  13441. if (!this.rotationQuaternion) {
  13442. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  13443. }
  13444. return this;
  13445. };
  13446. /**
  13447. * Retuns the mesh absolute position in the World.
  13448. * Returns a Vector3.
  13449. */
  13450. AbstractMesh.prototype.getAbsolutePosition = function () {
  13451. this.computeWorldMatrix();
  13452. return this._absolutePosition;
  13453. };
  13454. /**
  13455. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13456. * Returns the AbstractMesh.
  13457. */
  13458. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  13459. if (!absolutePosition) {
  13460. return this;
  13461. }
  13462. var absolutePositionX;
  13463. var absolutePositionY;
  13464. var absolutePositionZ;
  13465. if (absolutePosition.x === undefined) {
  13466. if (arguments.length < 3) {
  13467. return this;
  13468. }
  13469. absolutePositionX = arguments[0];
  13470. absolutePositionY = arguments[1];
  13471. absolutePositionZ = arguments[2];
  13472. }
  13473. else {
  13474. absolutePositionX = absolutePosition.x;
  13475. absolutePositionY = absolutePosition.y;
  13476. absolutePositionZ = absolutePosition.z;
  13477. }
  13478. if (this.parent) {
  13479. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13480. invertParentWorldMatrix.invert();
  13481. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13482. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13483. }
  13484. else {
  13485. this.position.x = absolutePositionX;
  13486. this.position.y = absolutePositionY;
  13487. this.position.z = absolutePositionZ;
  13488. }
  13489. return this;
  13490. };
  13491. // ================================== Point of View Movement =================================
  13492. /**
  13493. * Perform relative position change from the point of view of behind the front of the mesh.
  13494. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13495. * Supports definition of mesh facing forward or backward.
  13496. * @param {number} amountRight
  13497. * @param {number} amountUp
  13498. * @param {number} amountForward
  13499. *
  13500. * Returns the AbstractMesh.
  13501. */
  13502. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  13503. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  13504. return this;
  13505. };
  13506. /**
  13507. * Calculate relative position change from the point of view of behind the front of the mesh.
  13508. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13509. * Supports definition of mesh facing forward or backward.
  13510. * @param {number} amountRight
  13511. * @param {number} amountUp
  13512. * @param {number} amountForward
  13513. *
  13514. * Returns a new Vector3.
  13515. */
  13516. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  13517. var rotMatrix = new BABYLON.Matrix();
  13518. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13519. rotQuaternion.toRotationMatrix(rotMatrix);
  13520. var translationDelta = BABYLON.Vector3.Zero();
  13521. var defForwardMult = this.definedFacingForward ? -1 : 1;
  13522. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  13523. return translationDelta;
  13524. };
  13525. // ================================== Point of View Rotation =================================
  13526. /**
  13527. * Perform relative rotation change from the point of view of behind the front of the mesh.
  13528. * Supports definition of mesh facing forward or backward.
  13529. * @param {number} flipBack
  13530. * @param {number} twirlClockwise
  13531. * @param {number} tiltRight
  13532. *
  13533. * Returns the AbstractMesh.
  13534. */
  13535. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13536. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  13537. return this;
  13538. };
  13539. /**
  13540. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  13541. * Supports definition of mesh facing forward or backward.
  13542. * @param {number} flipBack
  13543. * @param {number} twirlClockwise
  13544. * @param {number} tiltRight
  13545. *
  13546. * Returns a new Vector3.
  13547. */
  13548. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13549. var defForwardMult = this.definedFacingForward ? 1 : -1;
  13550. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  13551. };
  13552. /**
  13553. * Sets a new pivot matrix to the mesh.
  13554. * Returns the AbstractMesh.
  13555. */
  13556. AbstractMesh.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  13557. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  13558. this._pivotMatrix = matrix.clone();
  13559. this._cache.pivotMatrixUpdated = true;
  13560. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  13561. if (this._postMultiplyPivotMatrix) {
  13562. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  13563. }
  13564. return this;
  13565. };
  13566. /**
  13567. * Returns the mesh pivot matrix.
  13568. * Default : Identity.
  13569. * A Matrix is returned.
  13570. */
  13571. AbstractMesh.prototype.getPivotMatrix = function () {
  13572. return this._pivotMatrix;
  13573. };
  13574. AbstractMesh.prototype._isSynchronized = function () {
  13575. if (this._isDirty) {
  13576. return false;
  13577. }
  13578. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  13579. return false;
  13580. if (this._cache.pivotMatrixUpdated) {
  13581. return false;
  13582. }
  13583. if (this.infiniteDistance) {
  13584. return false;
  13585. }
  13586. if (!this._cache.position.equals(this.position))
  13587. return false;
  13588. if (this.rotationQuaternion) {
  13589. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13590. return false;
  13591. }
  13592. if (!this._cache.rotation.equals(this.rotation))
  13593. return false;
  13594. if (!this._cache.scaling.equals(this.scaling))
  13595. return false;
  13596. return true;
  13597. };
  13598. AbstractMesh.prototype._initCache = function () {
  13599. _super.prototype._initCache.call(this);
  13600. this._cache.localMatrixUpdated = false;
  13601. this._cache.position = BABYLON.Vector3.Zero();
  13602. this._cache.scaling = BABYLON.Vector3.Zero();
  13603. this._cache.rotation = BABYLON.Vector3.Zero();
  13604. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  13605. this._cache.billboardMode = -1;
  13606. };
  13607. AbstractMesh.prototype.markAsDirty = function (property) {
  13608. if (property === "rotation") {
  13609. this.rotationQuaternion = null;
  13610. }
  13611. this._currentRenderId = Number.MAX_VALUE;
  13612. this._isDirty = true;
  13613. return this;
  13614. };
  13615. /**
  13616. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  13617. */
  13618. AbstractMesh.prototype.getHierarchyBoundingVectors = function () {
  13619. this.computeWorldMatrix(true);
  13620. var min;
  13621. var max;
  13622. var boundingInfo = this.getBoundingInfo();
  13623. if (!this.subMeshes || !boundingInfo) {
  13624. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13625. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13626. }
  13627. else {
  13628. min = boundingInfo.boundingBox.minimumWorld;
  13629. max = boundingInfo.boundingBox.maximumWorld;
  13630. }
  13631. var descendants = this.getDescendants(false);
  13632. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  13633. var descendant = descendants_1[_i];
  13634. var childMesh = descendant;
  13635. childMesh.computeWorldMatrix(true);
  13636. var childBoundingInfo = childMesh.getBoundingInfo();
  13637. if (childMesh.getTotalVertices() === 0 || !childBoundingInfo) {
  13638. continue;
  13639. }
  13640. var boundingBox = childBoundingInfo.boundingBox;
  13641. var minBox = boundingBox.minimumWorld;
  13642. var maxBox = boundingBox.maximumWorld;
  13643. BABYLON.Tools.CheckExtends(minBox, min, max);
  13644. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13645. }
  13646. return {
  13647. min: min,
  13648. max: max
  13649. };
  13650. };
  13651. /**
  13652. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  13653. * Returns the AbstractMesh.
  13654. */
  13655. AbstractMesh.prototype._updateBoundingInfo = function () {
  13656. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  13657. this._boundingInfo.update(this.worldMatrixFromCache);
  13658. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  13659. return this;
  13660. };
  13661. /**
  13662. * Update a mesh's children BoundingInfo objects only.
  13663. * Returns the AbstractMesh.
  13664. */
  13665. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  13666. if (!this.subMeshes) {
  13667. return this;
  13668. }
  13669. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  13670. var subMesh = this.subMeshes[subIndex];
  13671. if (!subMesh.IsGlobal) {
  13672. subMesh.updateBoundingInfo(matrix);
  13673. }
  13674. }
  13675. return this;
  13676. };
  13677. /**
  13678. * Computes the mesh World matrix and returns it.
  13679. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  13680. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  13681. * If the parameter `force`is set to `true`, the actual computation is done.
  13682. * Returns the mesh World Matrix.
  13683. */
  13684. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  13685. if (this._isWorldMatrixFrozen) {
  13686. return this._worldMatrix;
  13687. }
  13688. if (!force && this.isSynchronized(true)) {
  13689. this._currentRenderId = this.getScene().getRenderId();
  13690. return this._worldMatrix;
  13691. }
  13692. this._cache.position.copyFrom(this.position);
  13693. this._cache.scaling.copyFrom(this.scaling);
  13694. this._cache.pivotMatrixUpdated = false;
  13695. this._cache.billboardMode = this.billboardMode;
  13696. this._currentRenderId = this.getScene().getRenderId();
  13697. this._isDirty = false;
  13698. // Scaling
  13699. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  13700. // Rotation
  13701. //rotate, if quaternion is set and rotation was used
  13702. if (this.rotationQuaternion) {
  13703. var len = this.rotation.length();
  13704. if (len) {
  13705. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  13706. this.rotation.copyFromFloats(0, 0, 0);
  13707. }
  13708. }
  13709. if (this.rotationQuaternion) {
  13710. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  13711. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13712. }
  13713. else {
  13714. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  13715. this._cache.rotation.copyFrom(this.rotation);
  13716. }
  13717. // Translation
  13718. var camera = this.getScene().activeCamera;
  13719. if (this.infiniteDistance && !this.parent && camera) {
  13720. var cameraWorldMatrix = camera.getWorldMatrix();
  13721. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  13722. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  13723. }
  13724. else {
  13725. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  13726. }
  13727. // Composing transformations
  13728. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  13729. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13730. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  13731. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && camera) {
  13732. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  13733. // Need to decompose each rotation here
  13734. var currentPosition = BABYLON.Tmp.Vector3[3];
  13735. if (this.parent && this.parent.getWorldMatrix) {
  13736. if (this._meshToBoneReferal) {
  13737. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13738. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  13739. }
  13740. else {
  13741. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  13742. }
  13743. }
  13744. else {
  13745. currentPosition.copyFrom(this.position);
  13746. }
  13747. currentPosition.subtractInPlace(camera.globalPosition);
  13748. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  13749. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  13750. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  13751. }
  13752. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  13753. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  13754. }
  13755. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  13756. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  13757. }
  13758. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  13759. }
  13760. else {
  13761. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  13762. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  13763. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  13764. }
  13765. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  13766. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13767. }
  13768. // Local world
  13769. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  13770. // Parent
  13771. if (this.parent && this.parent.getWorldMatrix) {
  13772. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  13773. if (this._meshToBoneReferal) {
  13774. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13775. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  13776. }
  13777. else {
  13778. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  13779. }
  13780. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  13781. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  13782. this._worldMatrix.copyFrom(this._localWorld);
  13783. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  13784. }
  13785. else {
  13786. if (this._meshToBoneReferal) {
  13787. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13788. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  13789. }
  13790. else {
  13791. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  13792. }
  13793. }
  13794. this._markSyncedWithParent();
  13795. }
  13796. else {
  13797. this._worldMatrix.copyFrom(this._localWorld);
  13798. }
  13799. // Post multiply inverse of pivotMatrix
  13800. if (this._postMultiplyPivotMatrix) {
  13801. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  13802. }
  13803. // Normal matrix
  13804. if (this.scaling.isNonUniform) {
  13805. this.nonUniformScaling = true;
  13806. }
  13807. else if (this.parent && this.parent._nonUniformScaling) {
  13808. this.nonUniformScaling = this.parent._nonUniformScaling;
  13809. }
  13810. else {
  13811. this.nonUniformScaling = false;
  13812. }
  13813. // Bounding info
  13814. this._updateBoundingInfo();
  13815. // Absolute position
  13816. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  13817. // Callbacks
  13818. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  13819. if (!this._poseMatrix) {
  13820. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  13821. }
  13822. return this._worldMatrix;
  13823. };
  13824. /**
  13825. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  13826. * @param func: callback function to add
  13827. *
  13828. * Returns the AbstractMesh.
  13829. */
  13830. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  13831. this.onAfterWorldMatrixUpdateObservable.add(func);
  13832. return this;
  13833. };
  13834. /**
  13835. * Removes a registered callback function.
  13836. * Returns the AbstractMesh.
  13837. */
  13838. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  13839. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  13840. return this;
  13841. };
  13842. /**
  13843. * Sets the mesh position in its local space.
  13844. * Returns the AbstractMesh.
  13845. */
  13846. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  13847. this.computeWorldMatrix();
  13848. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13849. return this;
  13850. };
  13851. /**
  13852. * Returns the mesh position in the local space from the current World matrix values.
  13853. * Returns a new Vector3.
  13854. */
  13855. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  13856. this.computeWorldMatrix();
  13857. var invLocalWorldMatrix = this._localWorld.clone();
  13858. invLocalWorldMatrix.invert();
  13859. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13860. };
  13861. /**
  13862. * Translates the mesh along the passed Vector3 in its local space.
  13863. * Returns the AbstractMesh.
  13864. */
  13865. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  13866. this.computeWorldMatrix(true);
  13867. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13868. return this;
  13869. };
  13870. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13871. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  13872. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  13873. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  13874. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  13875. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  13876. /// <returns>Mesh oriented towards targetMesh</returns>
  13877. if (yawCor === void 0) { yawCor = 0; }
  13878. if (pitchCor === void 0) { pitchCor = 0; }
  13879. if (rollCor === void 0) { rollCor = 0; }
  13880. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13881. var dv = AbstractMesh._lookAtVectorCache;
  13882. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13883. targetPoint.subtractToRef(pos, dv);
  13884. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13885. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13886. var pitch = Math.atan2(dv.y, len);
  13887. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  13888. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13889. return this;
  13890. };
  13891. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  13892. this._meshToBoneReferal = affectedMesh;
  13893. this.parent = bone;
  13894. if (bone.getWorldMatrix().determinant() < 0) {
  13895. this.scalingDeterminant *= -1;
  13896. }
  13897. return this;
  13898. };
  13899. AbstractMesh.prototype.detachFromBone = function () {
  13900. if (!this.parent) {
  13901. return this;
  13902. }
  13903. if (this.parent.getWorldMatrix().determinant() < 0) {
  13904. this.scalingDeterminant *= -1;
  13905. }
  13906. this._meshToBoneReferal = null;
  13907. this.parent = null;
  13908. return this;
  13909. };
  13910. /**
  13911. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  13912. * A mesh is in the frustum if its bounding box intersects the frustum.
  13913. * Boolean returned.
  13914. */
  13915. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  13916. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  13917. };
  13918. /**
  13919. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  13920. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  13921. * Boolean returned.
  13922. */
  13923. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13924. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  13925. ;
  13926. };
  13927. /**
  13928. * True if the mesh intersects another mesh or a SolidParticle object.
  13929. * 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)
  13930. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  13931. * Returns a boolean.
  13932. */
  13933. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  13934. if (precise === void 0) { precise = false; }
  13935. if (!this._boundingInfo || !mesh._boundingInfo) {
  13936. return false;
  13937. }
  13938. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  13939. return true;
  13940. }
  13941. if (includeDescendants) {
  13942. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  13943. var child = _a[_i];
  13944. if (child.intersectsMesh(mesh, precise, true)) {
  13945. return true;
  13946. }
  13947. }
  13948. }
  13949. return false;
  13950. };
  13951. /**
  13952. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  13953. * Returns a boolean.
  13954. */
  13955. AbstractMesh.prototype.intersectsPoint = function (point) {
  13956. if (!this._boundingInfo) {
  13957. return false;
  13958. }
  13959. return this._boundingInfo.intersectsPoint(point);
  13960. };
  13961. AbstractMesh.prototype.getPhysicsImpostor = function () {
  13962. return this.physicsImpostor;
  13963. };
  13964. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  13965. if (camera === void 0) { camera = null; }
  13966. if (!camera) {
  13967. camera = this.getScene().activeCamera;
  13968. }
  13969. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  13970. };
  13971. /**
  13972. * Returns the distance from the mesh to the active camera.
  13973. * Returns a float.
  13974. */
  13975. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  13976. if (camera === void 0) { camera = null; }
  13977. if (!camera) {
  13978. camera = this.getScene().activeCamera;
  13979. }
  13980. return this.absolutePosition.subtract(camera.position).length();
  13981. };
  13982. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  13983. if (!this.physicsImpostor) {
  13984. return this;
  13985. }
  13986. this.physicsImpostor.applyImpulse(force, contactPoint);
  13987. return this;
  13988. };
  13989. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  13990. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  13991. return this;
  13992. }
  13993. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  13994. mainPivot: pivot1,
  13995. connectedPivot: pivot2,
  13996. nativeParams: options
  13997. });
  13998. return this;
  13999. };
  14000. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  14001. // Collisions
  14002. /**
  14003. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  14004. * Default `false`.
  14005. */
  14006. get: function () {
  14007. return this._checkCollisions;
  14008. },
  14009. set: function (collisionEnabled) {
  14010. this._checkCollisions = collisionEnabled;
  14011. if (this.getScene().workerCollisions) {
  14012. this.getScene().collisionCoordinator.onMeshUpdated(this);
  14013. }
  14014. },
  14015. enumerable: true,
  14016. configurable: true
  14017. });
  14018. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  14019. var globalPosition = this.getAbsolutePosition();
  14020. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  14021. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  14022. if (!this._collider) {
  14023. this._collider = new BABYLON.Collider();
  14024. }
  14025. this._collider.radius = this.ellipsoid;
  14026. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  14027. return this;
  14028. };
  14029. // Submeshes octree
  14030. /**
  14031. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  14032. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  14033. * Returns an Octree of submeshes.
  14034. */
  14035. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  14036. if (maxCapacity === void 0) { maxCapacity = 64; }
  14037. if (maxDepth === void 0) { maxDepth = 2; }
  14038. if (!this._submeshesOctree) {
  14039. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  14040. }
  14041. this.computeWorldMatrix(true);
  14042. var boundingInfo = this.getBoundingInfo();
  14043. // Update octree
  14044. if (boundingInfo) {
  14045. var bbox = boundingInfo.boundingBox;
  14046. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  14047. }
  14048. return this._submeshesOctree;
  14049. };
  14050. // Collisions
  14051. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  14052. this._generatePointsArray();
  14053. if (!this._positions) {
  14054. return this;
  14055. }
  14056. // Transformation
  14057. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  14058. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  14059. subMesh._lastColliderWorldVertices = [];
  14060. subMesh._trianglePlanes = [];
  14061. var start = subMesh.verticesStart;
  14062. var end = (subMesh.verticesStart + subMesh.verticesCount);
  14063. for (var i = start; i < end; i++) {
  14064. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  14065. }
  14066. }
  14067. // Collide
  14068. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  14069. if (collider.collisionFound) {
  14070. collider.collidedMesh = this;
  14071. }
  14072. return this;
  14073. };
  14074. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  14075. var subMeshes;
  14076. var len;
  14077. // Octrees
  14078. if (this._submeshesOctree && this.useOctreeForCollisions) {
  14079. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  14080. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  14081. len = intersections.length;
  14082. subMeshes = intersections.data;
  14083. }
  14084. else {
  14085. subMeshes = this.subMeshes;
  14086. len = subMeshes.length;
  14087. }
  14088. for (var index = 0; index < len; index++) {
  14089. var subMesh = subMeshes[index];
  14090. // Bounding test
  14091. if (len > 1 && !subMesh._checkCollision(collider))
  14092. continue;
  14093. this._collideForSubMesh(subMesh, transformMatrix, collider);
  14094. }
  14095. return this;
  14096. };
  14097. AbstractMesh.prototype._checkCollision = function (collider) {
  14098. // Bounding box test
  14099. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  14100. return this;
  14101. // Transformation matrix
  14102. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  14103. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  14104. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  14105. return this;
  14106. };
  14107. // Picking
  14108. AbstractMesh.prototype._generatePointsArray = function () {
  14109. return false;
  14110. };
  14111. /**
  14112. * Checks if the passed Ray intersects with the mesh.
  14113. * Returns an object PickingInfo.
  14114. */
  14115. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  14116. var pickingInfo = new BABYLON.PickingInfo();
  14117. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  14118. return pickingInfo;
  14119. }
  14120. if (!this._generatePointsArray()) {
  14121. return pickingInfo;
  14122. }
  14123. var intersectInfo = null;
  14124. // Octrees
  14125. var subMeshes;
  14126. var len;
  14127. if (this._submeshesOctree && this.useOctreeForPicking) {
  14128. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  14129. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  14130. len = intersections.length;
  14131. subMeshes = intersections.data;
  14132. }
  14133. else {
  14134. subMeshes = this.subMeshes;
  14135. len = subMeshes.length;
  14136. }
  14137. for (var index = 0; index < len; index++) {
  14138. var subMesh = subMeshes[index];
  14139. // Bounding test
  14140. if (len > 1 && !subMesh.canIntersects(ray))
  14141. continue;
  14142. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  14143. if (currentIntersectInfo) {
  14144. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  14145. intersectInfo = currentIntersectInfo;
  14146. intersectInfo.subMeshId = index;
  14147. if (fastCheck) {
  14148. break;
  14149. }
  14150. }
  14151. }
  14152. }
  14153. if (intersectInfo) {
  14154. // Get picked point
  14155. var world = this.getWorldMatrix();
  14156. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  14157. var direction = ray.direction.clone();
  14158. direction = direction.scale(intersectInfo.distance);
  14159. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  14160. var pickedPoint = worldOrigin.add(worldDirection);
  14161. // Return result
  14162. pickingInfo.hit = true;
  14163. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  14164. pickingInfo.pickedPoint = pickedPoint;
  14165. pickingInfo.pickedMesh = this;
  14166. pickingInfo.bu = intersectInfo.bu || 0;
  14167. pickingInfo.bv = intersectInfo.bv || 0;
  14168. pickingInfo.faceId = intersectInfo.faceId;
  14169. pickingInfo.subMeshId = intersectInfo.subMeshId;
  14170. return pickingInfo;
  14171. }
  14172. return pickingInfo;
  14173. };
  14174. /**
  14175. * Clones the mesh, used by the class Mesh.
  14176. * Just returns `null` for an AbstractMesh.
  14177. */
  14178. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14179. return null;
  14180. };
  14181. /**
  14182. * Disposes all the mesh submeshes.
  14183. * Returns the AbstractMesh.
  14184. */
  14185. AbstractMesh.prototype.releaseSubMeshes = function () {
  14186. if (this.subMeshes) {
  14187. while (this.subMeshes.length) {
  14188. this.subMeshes[0].dispose();
  14189. }
  14190. }
  14191. else {
  14192. this.subMeshes = new Array();
  14193. }
  14194. return this;
  14195. };
  14196. /**
  14197. * Disposes the AbstractMesh.
  14198. * Some internal references are kept for further use.
  14199. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  14200. * Returns nothing.
  14201. */
  14202. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  14203. var _this = this;
  14204. var index;
  14205. // Action manager
  14206. if (this.actionManager) {
  14207. this.actionManager.dispose();
  14208. this.actionManager = null;
  14209. }
  14210. // Skeleton
  14211. this.skeleton = null;
  14212. // Animations
  14213. this.getScene().stopAnimation(this);
  14214. // Physics
  14215. if (this.physicsImpostor) {
  14216. this.physicsImpostor.dispose();
  14217. }
  14218. // Intersections in progress
  14219. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  14220. var other = this._intersectionsInProgress[index];
  14221. var pos = other._intersectionsInProgress.indexOf(this);
  14222. other._intersectionsInProgress.splice(pos, 1);
  14223. }
  14224. this._intersectionsInProgress = [];
  14225. // Lights
  14226. var lights = this.getScene().lights;
  14227. lights.forEach(function (light) {
  14228. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  14229. if (meshIndex !== -1) {
  14230. light.includedOnlyMeshes.splice(meshIndex, 1);
  14231. }
  14232. meshIndex = light.excludedMeshes.indexOf(_this);
  14233. if (meshIndex !== -1) {
  14234. light.excludedMeshes.splice(meshIndex, 1);
  14235. }
  14236. // Shadow generators
  14237. var generator = light.getShadowGenerator();
  14238. if (generator) {
  14239. var shadowMap = generator.getShadowMap();
  14240. if (shadowMap && shadowMap.renderList) {
  14241. meshIndex = shadowMap.renderList.indexOf(_this);
  14242. if (meshIndex !== -1) {
  14243. shadowMap.renderList.splice(meshIndex, 1);
  14244. }
  14245. }
  14246. }
  14247. });
  14248. // Edges
  14249. if (this._edgesRenderer) {
  14250. this._edgesRenderer.dispose();
  14251. this._edgesRenderer = null;
  14252. }
  14253. // SubMeshes
  14254. if (this.getClassName() !== "InstancedMesh") {
  14255. this.releaseSubMeshes();
  14256. }
  14257. // Octree
  14258. var sceneOctree = this.getScene().selectionOctree;
  14259. if (sceneOctree) {
  14260. var index = sceneOctree.dynamicContent.indexOf(this);
  14261. if (index !== -1) {
  14262. sceneOctree.dynamicContent.splice(index, 1);
  14263. }
  14264. }
  14265. // Query
  14266. var engine = this.getScene().getEngine();
  14267. if (this._occlusionQuery) {
  14268. this._isOcclusionQueryInProgress = false;
  14269. engine.deleteQuery(this._occlusionQuery);
  14270. this._occlusionQuery = null;
  14271. }
  14272. // Engine
  14273. engine.wipeCaches();
  14274. // Remove from scene
  14275. this.getScene().removeMesh(this);
  14276. if (!doNotRecurse) {
  14277. // Particles
  14278. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  14279. if (this.getScene().particleSystems[index].emitter === this) {
  14280. this.getScene().particleSystems[index].dispose();
  14281. index--;
  14282. }
  14283. }
  14284. // Children
  14285. var objects = this.getDescendants(true);
  14286. for (index = 0; index < objects.length; index++) {
  14287. objects[index].dispose();
  14288. }
  14289. }
  14290. else {
  14291. var childMeshes = this.getChildMeshes(true);
  14292. for (index = 0; index < childMeshes.length; index++) {
  14293. var child = childMeshes[index];
  14294. child.parent = null;
  14295. child.computeWorldMatrix(true);
  14296. }
  14297. }
  14298. // facet data
  14299. if (this._facetDataEnabled) {
  14300. this.disableFacetData();
  14301. }
  14302. this.onAfterWorldMatrixUpdateObservable.clear();
  14303. this.onCollideObservable.clear();
  14304. this.onCollisionPositionChangeObservable.clear();
  14305. this._isDisposed = true;
  14306. _super.prototype.dispose.call(this);
  14307. };
  14308. /**
  14309. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  14310. * This Vector3 is expressed in the World space.
  14311. */
  14312. AbstractMesh.prototype.getDirection = function (localAxis) {
  14313. var result = BABYLON.Vector3.Zero();
  14314. this.getDirectionToRef(localAxis, result);
  14315. return result;
  14316. };
  14317. /**
  14318. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  14319. * localAxis is expressed in the mesh local space.
  14320. * result is computed in the Wordl space from the mesh World matrix.
  14321. * Returns the AbstractMesh.
  14322. */
  14323. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  14324. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14325. return this;
  14326. };
  14327. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  14328. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14329. if (this.getScene().getRenderId() == 0) {
  14330. this.computeWorldMatrix(true);
  14331. }
  14332. var wm = this.getWorldMatrix();
  14333. if (space == BABYLON.Space.WORLD) {
  14334. var tmat = BABYLON.Tmp.Matrix[0];
  14335. wm.invertToRef(tmat);
  14336. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  14337. }
  14338. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  14339. this._pivotMatrix.m[12] = -point.x;
  14340. this._pivotMatrix.m[13] = -point.y;
  14341. this._pivotMatrix.m[14] = -point.z;
  14342. this._cache.pivotMatrixUpdated = true;
  14343. return this;
  14344. };
  14345. /**
  14346. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  14347. */
  14348. AbstractMesh.prototype.getPivotPoint = function () {
  14349. var point = BABYLON.Vector3.Zero();
  14350. this.getPivotPointToRef(point);
  14351. return point;
  14352. };
  14353. /**
  14354. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  14355. * Returns the AbstractMesh.
  14356. */
  14357. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  14358. result.x = -this._pivotMatrix.m[12];
  14359. result.y = -this._pivotMatrix.m[13];
  14360. result.z = -this._pivotMatrix.m[14];
  14361. return this;
  14362. };
  14363. /**
  14364. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  14365. */
  14366. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  14367. var point = BABYLON.Vector3.Zero();
  14368. this.getAbsolutePivotPointToRef(point);
  14369. return point;
  14370. };
  14371. /**
  14372. * Defines the passed mesh as the parent of the current mesh.
  14373. * Returns the AbstractMesh.
  14374. */
  14375. AbstractMesh.prototype.setParent = function (mesh) {
  14376. var child = this;
  14377. var parent = mesh;
  14378. if (mesh == null) {
  14379. var rotation = BABYLON.Tmp.Quaternion[0];
  14380. var position = BABYLON.Tmp.Vector3[0];
  14381. var scale = BABYLON.Tmp.Vector3[1];
  14382. child.getWorldMatrix().decompose(scale, rotation, position);
  14383. if (child.rotationQuaternion) {
  14384. child.rotationQuaternion.copyFrom(rotation);
  14385. }
  14386. else {
  14387. rotation.toEulerAnglesToRef(child.rotation);
  14388. }
  14389. child.position.x = position.x;
  14390. child.position.y = position.y;
  14391. child.position.z = position.z;
  14392. }
  14393. else {
  14394. var position = BABYLON.Tmp.Vector3[0];
  14395. var m1 = BABYLON.Tmp.Matrix[0];
  14396. parent.getWorldMatrix().invertToRef(m1);
  14397. BABYLON.Vector3.TransformCoordinatesToRef(child.position, m1, position);
  14398. child.position.copyFrom(position);
  14399. }
  14400. child.parent = parent;
  14401. return this;
  14402. };
  14403. /**
  14404. * Adds the passed mesh as a child to the current mesh.
  14405. * Returns the AbstractMesh.
  14406. */
  14407. AbstractMesh.prototype.addChild = function (mesh) {
  14408. mesh.setParent(this);
  14409. return this;
  14410. };
  14411. /**
  14412. * Removes the passed mesh from the current mesh children list.
  14413. * Returns the AbstractMesh.
  14414. */
  14415. AbstractMesh.prototype.removeChild = function (mesh) {
  14416. mesh.setParent(null);
  14417. return this;
  14418. };
  14419. /**
  14420. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  14421. * Returns the AbstractMesh.
  14422. */
  14423. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  14424. result.x = this._pivotMatrix.m[12];
  14425. result.y = this._pivotMatrix.m[13];
  14426. result.z = this._pivotMatrix.m[14];
  14427. this.getPivotPointToRef(result);
  14428. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  14429. return this;
  14430. };
  14431. // Facet data
  14432. /**
  14433. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  14434. * Returns the AbstractMesh.
  14435. */
  14436. AbstractMesh.prototype._initFacetData = function () {
  14437. if (!this._facetNormals) {
  14438. this._facetNormals = new Array();
  14439. }
  14440. if (!this._facetPositions) {
  14441. this._facetPositions = new Array();
  14442. }
  14443. if (!this._facetPartitioning) {
  14444. this._facetPartitioning = new Array();
  14445. }
  14446. this._facetNb = this.getIndices().length / 3;
  14447. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  14448. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  14449. for (var f = 0; f < this._facetNb; f++) {
  14450. this._facetNormals[f] = BABYLON.Vector3.Zero();
  14451. this._facetPositions[f] = BABYLON.Vector3.Zero();
  14452. }
  14453. this._facetDataEnabled = true;
  14454. return this;
  14455. };
  14456. /**
  14457. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  14458. * This method can be called within the render loop.
  14459. * 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.
  14460. * Returns the AbstractMesh.
  14461. */
  14462. AbstractMesh.prototype.updateFacetData = function () {
  14463. if (!this._facetDataEnabled) {
  14464. this._initFacetData();
  14465. }
  14466. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14467. var indices = this.getIndices();
  14468. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14469. var bInfo = this.getBoundingInfo();
  14470. if (!bInfo) {
  14471. return this;
  14472. }
  14473. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  14474. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  14475. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  14476. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  14477. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  14478. this._subDiv.max = this._partitioningSubdivisions;
  14479. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  14480. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  14481. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  14482. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  14483. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  14484. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  14485. // set the parameters for ComputeNormals()
  14486. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  14487. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  14488. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  14489. this._facetParameters.bInfo = bInfo;
  14490. this._facetParameters.bbSize = this._bbSize;
  14491. this._facetParameters.subDiv = this._subDiv;
  14492. this._facetParameters.ratio = this.partitioningBBoxRatio;
  14493. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  14494. return this;
  14495. };
  14496. /**
  14497. * Returns the facetLocalNormals array.
  14498. * The normals are expressed in the mesh local space.
  14499. */
  14500. AbstractMesh.prototype.getFacetLocalNormals = function () {
  14501. if (!this._facetNormals) {
  14502. this.updateFacetData();
  14503. }
  14504. return this._facetNormals;
  14505. };
  14506. /**
  14507. * Returns the facetLocalPositions array.
  14508. * The facet positions are expressed in the mesh local space.
  14509. */
  14510. AbstractMesh.prototype.getFacetLocalPositions = function () {
  14511. if (!this._facetPositions) {
  14512. this.updateFacetData();
  14513. }
  14514. return this._facetPositions;
  14515. };
  14516. /**
  14517. * Returns the facetLocalPartioning array.
  14518. */
  14519. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  14520. if (!this._facetPartitioning) {
  14521. this.updateFacetData();
  14522. }
  14523. return this._facetPartitioning;
  14524. };
  14525. /**
  14526. * Returns the i-th facet position in the world system.
  14527. * This method allocates a new Vector3 per call.
  14528. */
  14529. AbstractMesh.prototype.getFacetPosition = function (i) {
  14530. var pos = BABYLON.Vector3.Zero();
  14531. this.getFacetPositionToRef(i, pos);
  14532. return pos;
  14533. };
  14534. /**
  14535. * Sets the reference Vector3 with the i-th facet position in the world system.
  14536. * Returns the AbstractMesh.
  14537. */
  14538. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  14539. var localPos = (this.getFacetLocalPositions())[i];
  14540. var world = this.getWorldMatrix();
  14541. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  14542. return this;
  14543. };
  14544. /**
  14545. * Returns the i-th facet normal in the world system.
  14546. * This method allocates a new Vector3 per call.
  14547. */
  14548. AbstractMesh.prototype.getFacetNormal = function (i) {
  14549. var norm = BABYLON.Vector3.Zero();
  14550. this.getFacetNormalToRef(i, norm);
  14551. return norm;
  14552. };
  14553. /**
  14554. * Sets the reference Vector3 with the i-th facet normal in the world system.
  14555. * Returns the AbstractMesh.
  14556. */
  14557. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  14558. var localNorm = (this.getFacetLocalNormals())[i];
  14559. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  14560. return this;
  14561. };
  14562. /**
  14563. * 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).
  14564. */
  14565. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  14566. var bInfo = this.getBoundingInfo();
  14567. if (!bInfo) {
  14568. return null;
  14569. }
  14570. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  14571. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  14572. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  14573. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  14574. return null;
  14575. }
  14576. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  14577. };
  14578. /**
  14579. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  14580. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  14581. * 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.
  14582. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14583. * 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.
  14584. */
  14585. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  14586. if (checkFace === void 0) { checkFace = false; }
  14587. if (facing === void 0) { facing = true; }
  14588. var world = this.getWorldMatrix();
  14589. var invMat = BABYLON.Tmp.Matrix[5];
  14590. world.invertToRef(invMat);
  14591. var invVect = BABYLON.Tmp.Vector3[8];
  14592. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  14593. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  14594. if (projected) {
  14595. // tranform the local computed projected vector to world coordinates
  14596. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  14597. }
  14598. return closest;
  14599. };
  14600. /**
  14601. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  14602. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  14603. * 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.
  14604. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14605. * 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.
  14606. */
  14607. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  14608. if (checkFace === void 0) { checkFace = false; }
  14609. if (facing === void 0) { facing = true; }
  14610. var closest = null;
  14611. var tmpx = 0.0;
  14612. var tmpy = 0.0;
  14613. var tmpz = 0.0;
  14614. var d = 0.0; // tmp dot facet normal * facet position
  14615. var t0 = 0.0;
  14616. var projx = 0.0;
  14617. var projy = 0.0;
  14618. var projz = 0.0;
  14619. // Get all the facets in the same partitioning block than (x, y, z)
  14620. var facetPositions = this.getFacetLocalPositions();
  14621. var facetNormals = this.getFacetLocalNormals();
  14622. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  14623. if (!facetsInBlock) {
  14624. return null;
  14625. }
  14626. // Get the closest facet to (x, y, z)
  14627. var shortest = Number.MAX_VALUE; // init distance vars
  14628. var tmpDistance = shortest;
  14629. var fib; // current facet in the block
  14630. var norm; // current facet normal
  14631. var p0; // current facet barycenter position
  14632. // loop on all the facets in the current partitioning block
  14633. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  14634. fib = facetsInBlock[idx];
  14635. norm = facetNormals[fib];
  14636. p0 = facetPositions[fib];
  14637. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  14638. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  14639. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  14640. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  14641. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  14642. projx = x + norm.x * t0;
  14643. projy = y + norm.y * t0;
  14644. projz = z + norm.z * t0;
  14645. tmpx = projx - x;
  14646. tmpy = projy - y;
  14647. tmpz = projz - z;
  14648. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  14649. if (tmpDistance < shortest) {
  14650. shortest = tmpDistance;
  14651. closest = fib;
  14652. if (projected) {
  14653. projected.x = projx;
  14654. projected.y = projy;
  14655. projected.z = projz;
  14656. }
  14657. }
  14658. }
  14659. }
  14660. return closest;
  14661. };
  14662. /**
  14663. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  14664. */
  14665. AbstractMesh.prototype.getFacetDataParameters = function () {
  14666. return this._facetParameters;
  14667. };
  14668. /**
  14669. * Disables the feature FacetData and frees the related memory.
  14670. * Returns the AbstractMesh.
  14671. */
  14672. AbstractMesh.prototype.disableFacetData = function () {
  14673. if (this._facetDataEnabled) {
  14674. this._facetDataEnabled = false;
  14675. this._facetPositions = new Array();
  14676. ;
  14677. this._facetNormals = new Array();
  14678. ;
  14679. this._facetPartitioning = new Array();
  14680. ;
  14681. this._facetParameters = null;
  14682. }
  14683. return this;
  14684. };
  14685. /**
  14686. * Creates new normals data for the mesh.
  14687. * @param updatable.
  14688. */
  14689. AbstractMesh.prototype.createNormals = function (updatable) {
  14690. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14691. var indices = this.getIndices();
  14692. var normals;
  14693. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14694. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14695. }
  14696. else {
  14697. normals = [];
  14698. }
  14699. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  14700. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  14701. };
  14702. AbstractMesh.prototype.checkOcclusionQuery = function () {
  14703. var engine = this.getEngine();
  14704. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  14705. this._isOccluded = false;
  14706. return;
  14707. }
  14708. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  14709. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  14710. if (isOcclusionQueryAvailable) {
  14711. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  14712. this._isOcclusionQueryInProgress = false;
  14713. this._occlusionInternalRetryCounter = 0;
  14714. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  14715. }
  14716. else {
  14717. this._occlusionInternalRetryCounter++;
  14718. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  14719. this._isOcclusionQueryInProgress = false;
  14720. this._occlusionInternalRetryCounter = 0;
  14721. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  14722. // if strict continue the last state of the object.
  14723. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  14724. }
  14725. else {
  14726. return;
  14727. }
  14728. }
  14729. }
  14730. var scene = this.getScene();
  14731. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  14732. if (!this._occlusionQuery) {
  14733. this._occlusionQuery = engine.createQuery();
  14734. }
  14735. engine.beginQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  14736. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  14737. engine.endQuery(this.occlusionQueryAlgorithmType);
  14738. this._isOcclusionQueryInProgress = true;
  14739. };
  14740. // Statics
  14741. AbstractMesh._BILLBOARDMODE_NONE = 0;
  14742. AbstractMesh._BILLBOARDMODE_X = 1;
  14743. AbstractMesh._BILLBOARDMODE_Y = 2;
  14744. AbstractMesh._BILLBOARDMODE_Z = 4;
  14745. AbstractMesh._BILLBOARDMODE_ALL = 7;
  14746. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  14747. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  14748. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  14749. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  14750. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  14751. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  14752. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  14753. return AbstractMesh;
  14754. }(BABYLON.Node));
  14755. BABYLON.AbstractMesh = AbstractMesh;
  14756. })(BABYLON || (BABYLON = {}));
  14757. //# sourceMappingURL=babylon.abstractMesh.js.map
  14758. var BABYLON;
  14759. (function (BABYLON) {
  14760. var Light = /** @class */ (function (_super) {
  14761. __extends(Light, _super);
  14762. /**
  14763. * Creates a Light object in the scene.
  14764. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14765. */
  14766. function Light(name, scene) {
  14767. var _this = _super.call(this, name, scene) || this;
  14768. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  14769. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  14770. _this.intensity = 1.0;
  14771. _this.range = Number.MAX_VALUE;
  14772. /**
  14773. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  14774. * of light.
  14775. */
  14776. _this._photometricScale = 1.0;
  14777. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  14778. _this._radius = 0.00001;
  14779. _this.renderPriority = 0;
  14780. /**
  14781. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  14782. * the current shadow generator.
  14783. */
  14784. _this.shadowEnabled = true;
  14785. _this._excludeWithLayerMask = 0;
  14786. _this._includeOnlyWithLayerMask = 0;
  14787. _this._lightmapMode = 0;
  14788. _this._excludedMeshesIds = new Array();
  14789. _this._includedOnlyMeshesIds = new Array();
  14790. _this.getScene().addLight(_this);
  14791. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  14792. _this._buildUniformLayout();
  14793. _this.includedOnlyMeshes = new Array();
  14794. _this.excludedMeshes = new Array();
  14795. _this._resyncMeshes();
  14796. return _this;
  14797. }
  14798. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  14799. /**
  14800. * If every light affecting the material is in this lightmapMode,
  14801. * material.lightmapTexture adds or multiplies
  14802. * (depends on material.useLightmapAsShadowmap)
  14803. * after every other light calculations.
  14804. */
  14805. get: function () {
  14806. return Light._LIGHTMAP_DEFAULT;
  14807. },
  14808. enumerable: true,
  14809. configurable: true
  14810. });
  14811. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  14812. /**
  14813. * material.lightmapTexture as only diffuse lighting from this light
  14814. * adds pnly specular lighting from this light
  14815. * adds dynamic shadows
  14816. */
  14817. get: function () {
  14818. return Light._LIGHTMAP_SPECULAR;
  14819. },
  14820. enumerable: true,
  14821. configurable: true
  14822. });
  14823. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  14824. /**
  14825. * material.lightmapTexture as only lighting
  14826. * no light calculation from this light
  14827. * only adds dynamic shadows from this light
  14828. */
  14829. get: function () {
  14830. return Light._LIGHTMAP_SHADOWSONLY;
  14831. },
  14832. enumerable: true,
  14833. configurable: true
  14834. });
  14835. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  14836. /**
  14837. * Each light type uses the default quantity according to its type:
  14838. * point/spot lights use luminous intensity
  14839. * directional lights use illuminance
  14840. */
  14841. get: function () {
  14842. return Light._INTENSITYMODE_AUTOMATIC;
  14843. },
  14844. enumerable: true,
  14845. configurable: true
  14846. });
  14847. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  14848. /**
  14849. * lumen (lm)
  14850. */
  14851. get: function () {
  14852. return Light._INTENSITYMODE_LUMINOUSPOWER;
  14853. },
  14854. enumerable: true,
  14855. configurable: true
  14856. });
  14857. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  14858. /**
  14859. * candela (lm/sr)
  14860. */
  14861. get: function () {
  14862. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  14863. },
  14864. enumerable: true,
  14865. configurable: true
  14866. });
  14867. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  14868. /**
  14869. * lux (lm/m^2)
  14870. */
  14871. get: function () {
  14872. return Light._INTENSITYMODE_ILLUMINANCE;
  14873. },
  14874. enumerable: true,
  14875. configurable: true
  14876. });
  14877. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  14878. /**
  14879. * nit (cd/m^2)
  14880. */
  14881. get: function () {
  14882. return Light._INTENSITYMODE_LUMINANCE;
  14883. },
  14884. enumerable: true,
  14885. configurable: true
  14886. });
  14887. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  14888. /**
  14889. * Light type const id of the point light.
  14890. */
  14891. get: function () {
  14892. return Light._LIGHTTYPEID_POINTLIGHT;
  14893. },
  14894. enumerable: true,
  14895. configurable: true
  14896. });
  14897. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  14898. /**
  14899. * Light type const id of the directional light.
  14900. */
  14901. get: function () {
  14902. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  14903. },
  14904. enumerable: true,
  14905. configurable: true
  14906. });
  14907. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  14908. /**
  14909. * Light type const id of the spot light.
  14910. */
  14911. get: function () {
  14912. return Light._LIGHTTYPEID_SPOTLIGHT;
  14913. },
  14914. enumerable: true,
  14915. configurable: true
  14916. });
  14917. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  14918. /**
  14919. * Light type const id of the hemispheric light.
  14920. */
  14921. get: function () {
  14922. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  14923. },
  14924. enumerable: true,
  14925. configurable: true
  14926. });
  14927. Object.defineProperty(Light.prototype, "intensityMode", {
  14928. /**
  14929. * Gets the photometric scale used to interpret the intensity.
  14930. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14931. */
  14932. get: function () {
  14933. return this._intensityMode;
  14934. },
  14935. /**
  14936. * Sets the photometric scale used to interpret the intensity.
  14937. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14938. */
  14939. set: function (value) {
  14940. this._intensityMode = value;
  14941. this._computePhotometricScale();
  14942. },
  14943. enumerable: true,
  14944. configurable: true
  14945. });
  14946. ;
  14947. ;
  14948. Object.defineProperty(Light.prototype, "radius", {
  14949. /**
  14950. * Gets the light radius used by PBR Materials to simulate soft area lights.
  14951. */
  14952. get: function () {
  14953. return this._radius;
  14954. },
  14955. /**
  14956. * sets the light radius used by PBR Materials to simulate soft area lights.
  14957. */
  14958. set: function (value) {
  14959. this._radius = value;
  14960. this._computePhotometricScale();
  14961. },
  14962. enumerable: true,
  14963. configurable: true
  14964. });
  14965. ;
  14966. ;
  14967. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  14968. get: function () {
  14969. return this._includedOnlyMeshes;
  14970. },
  14971. set: function (value) {
  14972. this._includedOnlyMeshes = value;
  14973. this._hookArrayForIncludedOnly(value);
  14974. },
  14975. enumerable: true,
  14976. configurable: true
  14977. });
  14978. Object.defineProperty(Light.prototype, "excludedMeshes", {
  14979. get: function () {
  14980. return this._excludedMeshes;
  14981. },
  14982. set: function (value) {
  14983. this._excludedMeshes = value;
  14984. this._hookArrayForExcluded(value);
  14985. },
  14986. enumerable: true,
  14987. configurable: true
  14988. });
  14989. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  14990. get: function () {
  14991. return this._excludeWithLayerMask;
  14992. },
  14993. set: function (value) {
  14994. this._excludeWithLayerMask = value;
  14995. this._resyncMeshes();
  14996. },
  14997. enumerable: true,
  14998. configurable: true
  14999. });
  15000. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  15001. get: function () {
  15002. return this._includeOnlyWithLayerMask;
  15003. },
  15004. set: function (value) {
  15005. this._includeOnlyWithLayerMask = value;
  15006. this._resyncMeshes();
  15007. },
  15008. enumerable: true,
  15009. configurable: true
  15010. });
  15011. Object.defineProperty(Light.prototype, "lightmapMode", {
  15012. get: function () {
  15013. return this._lightmapMode;
  15014. },
  15015. set: function (value) {
  15016. if (this._lightmapMode === value) {
  15017. return;
  15018. }
  15019. this._lightmapMode = value;
  15020. this._markMeshesAsLightDirty();
  15021. },
  15022. enumerable: true,
  15023. configurable: true
  15024. });
  15025. Light.prototype._buildUniformLayout = function () {
  15026. // Overridden
  15027. };
  15028. /**
  15029. * Returns the string "Light".
  15030. */
  15031. Light.prototype.getClassName = function () {
  15032. return "Light";
  15033. };
  15034. /**
  15035. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15036. */
  15037. Light.prototype.toString = function (fullDetails) {
  15038. var ret = "Name: " + this.name;
  15039. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  15040. if (this.animations) {
  15041. for (var i = 0; i < this.animations.length; i++) {
  15042. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15043. }
  15044. }
  15045. if (fullDetails) {
  15046. }
  15047. return ret;
  15048. };
  15049. /**
  15050. * Set the enabled state of this node.
  15051. * @param {boolean} value - the new enabled state
  15052. * @see isEnabled
  15053. */
  15054. Light.prototype.setEnabled = function (value) {
  15055. _super.prototype.setEnabled.call(this, value);
  15056. this._resyncMeshes();
  15057. };
  15058. /**
  15059. * Returns the Light associated shadow generator.
  15060. */
  15061. Light.prototype.getShadowGenerator = function () {
  15062. return this._shadowGenerator;
  15063. };
  15064. /**
  15065. * Returns a Vector3, the absolute light position in the World.
  15066. */
  15067. Light.prototype.getAbsolutePosition = function () {
  15068. return BABYLON.Vector3.Zero();
  15069. };
  15070. Light.prototype.transferToEffect = function (effect, lightIndex) {
  15071. };
  15072. Light.prototype._getWorldMatrix = function () {
  15073. return BABYLON.Matrix.Identity();
  15074. };
  15075. /**
  15076. * Boolean : True if the light will affect the passed mesh.
  15077. */
  15078. Light.prototype.canAffectMesh = function (mesh) {
  15079. if (!mesh) {
  15080. return true;
  15081. }
  15082. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  15083. return false;
  15084. }
  15085. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  15086. return false;
  15087. }
  15088. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  15089. return false;
  15090. }
  15091. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  15092. return false;
  15093. }
  15094. return true;
  15095. };
  15096. /**
  15097. * Returns the light World matrix.
  15098. */
  15099. Light.prototype.getWorldMatrix = function () {
  15100. this._currentRenderId = this.getScene().getRenderId();
  15101. var worldMatrix = this._getWorldMatrix();
  15102. if (this.parent && this.parent.getWorldMatrix) {
  15103. if (!this._parentedWorldMatrix) {
  15104. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  15105. }
  15106. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  15107. this._markSyncedWithParent();
  15108. return this._parentedWorldMatrix;
  15109. }
  15110. return worldMatrix;
  15111. };
  15112. /**
  15113. * Sort function to order lights for rendering.
  15114. * @param a First Light object to compare to second.
  15115. * @param b Second Light object to compare first.
  15116. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  15117. */
  15118. Light.compareLightsPriority = function (a, b) {
  15119. //shadow-casting lights have priority over non-shadow-casting lights
  15120. //the renderPrioirty is a secondary sort criterion
  15121. if (a.shadowEnabled !== b.shadowEnabled) {
  15122. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  15123. }
  15124. return b.renderPriority - a.renderPriority;
  15125. };
  15126. /**
  15127. * Disposes the light.
  15128. */
  15129. Light.prototype.dispose = function () {
  15130. if (this._shadowGenerator) {
  15131. this._shadowGenerator.dispose();
  15132. this._shadowGenerator = null;
  15133. }
  15134. // Animations
  15135. this.getScene().stopAnimation(this);
  15136. // Remove from meshes
  15137. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15138. var mesh = _a[_i];
  15139. mesh._removeLightSource(this);
  15140. }
  15141. this._uniformBuffer.dispose();
  15142. // Remove from scene
  15143. this.getScene().removeLight(this);
  15144. _super.prototype.dispose.call(this);
  15145. };
  15146. /**
  15147. * Returns the light type ID (integer).
  15148. */
  15149. Light.prototype.getTypeID = function () {
  15150. return 0;
  15151. };
  15152. /**
  15153. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  15154. */
  15155. Light.prototype.getScaledIntensity = function () {
  15156. return this._photometricScale * this.intensity;
  15157. };
  15158. /**
  15159. * Returns a new Light object, named "name", from the current one.
  15160. */
  15161. Light.prototype.clone = function (name) {
  15162. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  15163. if (!constructor) {
  15164. return null;
  15165. }
  15166. return BABYLON.SerializationHelper.Clone(constructor, this);
  15167. };
  15168. /**
  15169. * Serializes the current light into a Serialization object.
  15170. * Returns the serialized object.
  15171. */
  15172. Light.prototype.serialize = function () {
  15173. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15174. // Type
  15175. serializationObject.type = this.getTypeID();
  15176. // Parent
  15177. if (this.parent) {
  15178. serializationObject.parentId = this.parent.id;
  15179. }
  15180. // Inclusion / exclusions
  15181. if (this.excludedMeshes.length > 0) {
  15182. serializationObject.excludedMeshesIds = [];
  15183. this.excludedMeshes.forEach(function (mesh) {
  15184. serializationObject.excludedMeshesIds.push(mesh.id);
  15185. });
  15186. }
  15187. if (this.includedOnlyMeshes.length > 0) {
  15188. serializationObject.includedOnlyMeshesIds = [];
  15189. this.includedOnlyMeshes.forEach(function (mesh) {
  15190. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  15191. });
  15192. }
  15193. // Animations
  15194. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15195. serializationObject.ranges = this.serializeAnimationRanges();
  15196. return serializationObject;
  15197. };
  15198. /**
  15199. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  15200. * This new light is named "name" and added to the passed scene.
  15201. */
  15202. Light.GetConstructorFromName = function (type, name, scene) {
  15203. switch (type) {
  15204. case 0:
  15205. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  15206. case 1:
  15207. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  15208. case 2:
  15209. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  15210. case 3:
  15211. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  15212. }
  15213. return null;
  15214. };
  15215. /**
  15216. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  15217. */
  15218. Light.Parse = function (parsedLight, scene) {
  15219. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  15220. if (!constructor) {
  15221. return null;
  15222. }
  15223. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  15224. // Inclusion / exclusions
  15225. if (parsedLight.excludedMeshesIds) {
  15226. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  15227. }
  15228. if (parsedLight.includedOnlyMeshesIds) {
  15229. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  15230. }
  15231. // Parent
  15232. if (parsedLight.parentId) {
  15233. light._waitingParentId = parsedLight.parentId;
  15234. }
  15235. // Animations
  15236. if (parsedLight.animations) {
  15237. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  15238. var parsedAnimation = parsedLight.animations[animationIndex];
  15239. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15240. }
  15241. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  15242. }
  15243. if (parsedLight.autoAnimate) {
  15244. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  15245. }
  15246. return light;
  15247. };
  15248. Light.prototype._hookArrayForExcluded = function (array) {
  15249. var _this = this;
  15250. var oldPush = array.push;
  15251. array.push = function () {
  15252. var items = [];
  15253. for (var _i = 0; _i < arguments.length; _i++) {
  15254. items[_i] = arguments[_i];
  15255. }
  15256. var result = oldPush.apply(array, items);
  15257. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  15258. var item = items_1[_a];
  15259. item._resyncLighSource(_this);
  15260. }
  15261. return result;
  15262. };
  15263. var oldSplice = array.splice;
  15264. array.splice = function (index, deleteCount) {
  15265. var deleted = oldSplice.apply(array, [index, deleteCount]);
  15266. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  15267. var item = deleted_1[_i];
  15268. item._resyncLighSource(_this);
  15269. }
  15270. return deleted;
  15271. };
  15272. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  15273. var item = array_1[_i];
  15274. item._resyncLighSource(this);
  15275. }
  15276. };
  15277. Light.prototype._hookArrayForIncludedOnly = function (array) {
  15278. var _this = this;
  15279. var oldPush = array.push;
  15280. array.push = function () {
  15281. var items = [];
  15282. for (var _i = 0; _i < arguments.length; _i++) {
  15283. items[_i] = arguments[_i];
  15284. }
  15285. var result = oldPush.apply(array, items);
  15286. _this._resyncMeshes();
  15287. return result;
  15288. };
  15289. var oldSplice = array.splice;
  15290. array.splice = function (index, deleteCount) {
  15291. var deleted = oldSplice.apply(array, [index, deleteCount]);
  15292. _this._resyncMeshes();
  15293. return deleted;
  15294. };
  15295. this._resyncMeshes();
  15296. };
  15297. Light.prototype._resyncMeshes = function () {
  15298. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15299. var mesh = _a[_i];
  15300. mesh._resyncLighSource(this);
  15301. }
  15302. };
  15303. Light.prototype._markMeshesAsLightDirty = function () {
  15304. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15305. var mesh = _a[_i];
  15306. if (mesh._lightSources.indexOf(this) !== -1) {
  15307. mesh._markSubMeshesAsLightDirty();
  15308. }
  15309. }
  15310. };
  15311. /**
  15312. * Recomputes the cached photometric scale if needed.
  15313. */
  15314. Light.prototype._computePhotometricScale = function () {
  15315. this._photometricScale = this._getPhotometricScale();
  15316. this.getScene().resetCachedMaterial();
  15317. };
  15318. /**
  15319. * Returns the Photometric Scale according to the light type and intensity mode.
  15320. */
  15321. Light.prototype._getPhotometricScale = function () {
  15322. var photometricScale = 0.0;
  15323. var lightTypeID = this.getTypeID();
  15324. //get photometric mode
  15325. var photometricMode = this.intensityMode;
  15326. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  15327. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  15328. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  15329. }
  15330. else {
  15331. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  15332. }
  15333. }
  15334. //compute photometric scale
  15335. switch (lightTypeID) {
  15336. case Light.LIGHTTYPEID_POINTLIGHT:
  15337. case Light.LIGHTTYPEID_SPOTLIGHT:
  15338. switch (photometricMode) {
  15339. case Light.INTENSITYMODE_LUMINOUSPOWER:
  15340. photometricScale = 1.0 / (4.0 * Math.PI);
  15341. break;
  15342. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  15343. photometricScale = 1.0;
  15344. break;
  15345. case Light.INTENSITYMODE_LUMINANCE:
  15346. photometricScale = this.radius * this.radius;
  15347. break;
  15348. }
  15349. break;
  15350. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  15351. switch (photometricMode) {
  15352. case Light.INTENSITYMODE_ILLUMINANCE:
  15353. photometricScale = 1.0;
  15354. break;
  15355. case Light.INTENSITYMODE_LUMINANCE:
  15356. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  15357. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  15358. var apexAngleRadians = this.radius;
  15359. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  15360. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  15361. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  15362. photometricScale = solidAngle;
  15363. break;
  15364. }
  15365. break;
  15366. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  15367. // No fall off in hemisperic light.
  15368. photometricScale = 1.0;
  15369. break;
  15370. }
  15371. return photometricScale;
  15372. };
  15373. Light.prototype._reorderLightsInScene = function () {
  15374. var scene = this.getScene();
  15375. if (this._renderPriority != 0) {
  15376. scene.requireLightSorting = true;
  15377. }
  15378. this.getScene().sortLightsByPriority();
  15379. };
  15380. //lightmapMode Consts
  15381. Light._LIGHTMAP_DEFAULT = 0;
  15382. Light._LIGHTMAP_SPECULAR = 1;
  15383. Light._LIGHTMAP_SHADOWSONLY = 2;
  15384. // Intensity Mode Consts
  15385. Light._INTENSITYMODE_AUTOMATIC = 0;
  15386. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  15387. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  15388. Light._INTENSITYMODE_ILLUMINANCE = 3;
  15389. Light._INTENSITYMODE_LUMINANCE = 4;
  15390. // Light types ids const.
  15391. Light._LIGHTTYPEID_POINTLIGHT = 0;
  15392. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  15393. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  15394. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  15395. __decorate([
  15396. BABYLON.serializeAsColor3()
  15397. ], Light.prototype, "diffuse", void 0);
  15398. __decorate([
  15399. BABYLON.serializeAsColor3()
  15400. ], Light.prototype, "specular", void 0);
  15401. __decorate([
  15402. BABYLON.serialize()
  15403. ], Light.prototype, "intensity", void 0);
  15404. __decorate([
  15405. BABYLON.serialize()
  15406. ], Light.prototype, "range", void 0);
  15407. __decorate([
  15408. BABYLON.serialize()
  15409. ], Light.prototype, "intensityMode", null);
  15410. __decorate([
  15411. BABYLON.serialize()
  15412. ], Light.prototype, "radius", null);
  15413. __decorate([
  15414. BABYLON.serialize()
  15415. ], Light.prototype, "_renderPriority", void 0);
  15416. __decorate([
  15417. BABYLON.expandToProperty("_reorderLightsInScene")
  15418. ], Light.prototype, "renderPriority", void 0);
  15419. __decorate([
  15420. BABYLON.serialize()
  15421. ], Light.prototype, "shadowEnabled", void 0);
  15422. __decorate([
  15423. BABYLON.serialize("excludeWithLayerMask")
  15424. ], Light.prototype, "_excludeWithLayerMask", void 0);
  15425. __decorate([
  15426. BABYLON.serialize("includeOnlyWithLayerMask")
  15427. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  15428. __decorate([
  15429. BABYLON.serialize("lightmapMode")
  15430. ], Light.prototype, "_lightmapMode", void 0);
  15431. return Light;
  15432. }(BABYLON.Node));
  15433. BABYLON.Light = Light;
  15434. })(BABYLON || (BABYLON = {}));
  15435. //# sourceMappingURL=babylon.light.js.map
  15436. var BABYLON;
  15437. (function (BABYLON) {
  15438. var Camera = /** @class */ (function (_super) {
  15439. __extends(Camera, _super);
  15440. function Camera(name, position, scene) {
  15441. var _this = _super.call(this, name, scene) || this;
  15442. _this.upVector = BABYLON.Vector3.Up();
  15443. _this.orthoLeft = null;
  15444. _this.orthoRight = null;
  15445. _this.orthoBottom = null;
  15446. _this.orthoTop = null;
  15447. _this.fov = 0.8;
  15448. _this.minZ = 1;
  15449. _this.maxZ = 10000.0;
  15450. _this.inertia = 0.9;
  15451. _this.mode = Camera.PERSPECTIVE_CAMERA;
  15452. _this.isIntermediate = false;
  15453. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  15454. _this.layerMask = 0x0FFFFFFF;
  15455. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  15456. // Camera rig members
  15457. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  15458. _this._rigCameras = new Array();
  15459. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  15460. _this._skipRendering = false;
  15461. _this.customRenderTargets = new Array();
  15462. // Observables
  15463. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  15464. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  15465. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  15466. _this.onRestoreStateObservable = new BABYLON.Observable();
  15467. // Cache
  15468. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  15469. _this._projectionMatrix = new BABYLON.Matrix();
  15470. _this._doNotComputeProjectionMatrix = false;
  15471. _this._postProcesses = new Array();
  15472. _this._transformMatrix = BABYLON.Matrix.Zero();
  15473. _this._activeMeshes = new BABYLON.SmartArray(256);
  15474. _this._globalPosition = BABYLON.Vector3.Zero();
  15475. _this._refreshFrustumPlanes = true;
  15476. _this.getScene().addCamera(_this);
  15477. if (!_this.getScene().activeCamera) {
  15478. _this.getScene().activeCamera = _this;
  15479. }
  15480. _this.position = position;
  15481. return _this;
  15482. }
  15483. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  15484. get: function () {
  15485. return Camera._PERSPECTIVE_CAMERA;
  15486. },
  15487. enumerable: true,
  15488. configurable: true
  15489. });
  15490. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  15491. get: function () {
  15492. return Camera._ORTHOGRAPHIC_CAMERA;
  15493. },
  15494. enumerable: true,
  15495. configurable: true
  15496. });
  15497. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  15498. get: function () {
  15499. return Camera._FOVMODE_VERTICAL_FIXED;
  15500. },
  15501. enumerable: true,
  15502. configurable: true
  15503. });
  15504. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  15505. get: function () {
  15506. return Camera._FOVMODE_HORIZONTAL_FIXED;
  15507. },
  15508. enumerable: true,
  15509. configurable: true
  15510. });
  15511. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  15512. get: function () {
  15513. return Camera._RIG_MODE_NONE;
  15514. },
  15515. enumerable: true,
  15516. configurable: true
  15517. });
  15518. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  15519. get: function () {
  15520. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  15521. },
  15522. enumerable: true,
  15523. configurable: true
  15524. });
  15525. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  15526. get: function () {
  15527. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  15528. },
  15529. enumerable: true,
  15530. configurable: true
  15531. });
  15532. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  15533. get: function () {
  15534. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15535. },
  15536. enumerable: true,
  15537. configurable: true
  15538. });
  15539. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  15540. get: function () {
  15541. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  15542. },
  15543. enumerable: true,
  15544. configurable: true
  15545. });
  15546. Object.defineProperty(Camera, "RIG_MODE_VR", {
  15547. get: function () {
  15548. return Camera._RIG_MODE_VR;
  15549. },
  15550. enumerable: true,
  15551. configurable: true
  15552. });
  15553. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  15554. get: function () {
  15555. return Camera._RIG_MODE_WEBVR;
  15556. },
  15557. enumerable: true,
  15558. configurable: true
  15559. });
  15560. /**
  15561. * Store current camera state (fov, position, etc..)
  15562. */
  15563. Camera.prototype.storeState = function () {
  15564. this._stateStored = true;
  15565. this._storedFov = this.fov;
  15566. return this;
  15567. };
  15568. /**
  15569. * Restores the camera state values if it has been stored. You must call storeState() first
  15570. */
  15571. Camera.prototype._restoreStateValues = function () {
  15572. if (!this._stateStored) {
  15573. return false;
  15574. }
  15575. this.fov = this._storedFov;
  15576. return true;
  15577. };
  15578. /**
  15579. * Restored camera state. You must call storeState() first
  15580. */
  15581. Camera.prototype.restoreState = function () {
  15582. if (this._restoreStateValues()) {
  15583. this.onRestoreStateObservable.notifyObservers(this);
  15584. return true;
  15585. }
  15586. return false;
  15587. };
  15588. Camera.prototype.getClassName = function () {
  15589. return "Camera";
  15590. };
  15591. /**
  15592. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15593. */
  15594. Camera.prototype.toString = function (fullDetails) {
  15595. var ret = "Name: " + this.name;
  15596. ret += ", type: " + this.getClassName();
  15597. if (this.animations) {
  15598. for (var i = 0; i < this.animations.length; i++) {
  15599. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15600. }
  15601. }
  15602. if (fullDetails) {
  15603. }
  15604. return ret;
  15605. };
  15606. Object.defineProperty(Camera.prototype, "globalPosition", {
  15607. get: function () {
  15608. return this._globalPosition;
  15609. },
  15610. enumerable: true,
  15611. configurable: true
  15612. });
  15613. Camera.prototype.getActiveMeshes = function () {
  15614. return this._activeMeshes;
  15615. };
  15616. Camera.prototype.isActiveMesh = function (mesh) {
  15617. return (this._activeMeshes.indexOf(mesh) !== -1);
  15618. };
  15619. //Cache
  15620. Camera.prototype._initCache = function () {
  15621. _super.prototype._initCache.call(this);
  15622. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15623. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15624. this._cache.mode = undefined;
  15625. this._cache.minZ = undefined;
  15626. this._cache.maxZ = undefined;
  15627. this._cache.fov = undefined;
  15628. this._cache.fovMode = undefined;
  15629. this._cache.aspectRatio = undefined;
  15630. this._cache.orthoLeft = undefined;
  15631. this._cache.orthoRight = undefined;
  15632. this._cache.orthoBottom = undefined;
  15633. this._cache.orthoTop = undefined;
  15634. this._cache.renderWidth = undefined;
  15635. this._cache.renderHeight = undefined;
  15636. };
  15637. Camera.prototype._updateCache = function (ignoreParentClass) {
  15638. if (!ignoreParentClass) {
  15639. _super.prototype._updateCache.call(this);
  15640. }
  15641. this._cache.position.copyFrom(this.position);
  15642. this._cache.upVector.copyFrom(this.upVector);
  15643. };
  15644. // Synchronized
  15645. Camera.prototype._isSynchronized = function () {
  15646. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  15647. };
  15648. Camera.prototype._isSynchronizedViewMatrix = function () {
  15649. if (!_super.prototype._isSynchronized.call(this))
  15650. return false;
  15651. return this._cache.position.equals(this.position)
  15652. && this._cache.upVector.equals(this.upVector)
  15653. && this.isSynchronizedWithParent();
  15654. };
  15655. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  15656. var check = this._cache.mode === this.mode
  15657. && this._cache.minZ === this.minZ
  15658. && this._cache.maxZ === this.maxZ;
  15659. if (!check) {
  15660. return false;
  15661. }
  15662. var engine = this.getEngine();
  15663. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15664. check = this._cache.fov === this.fov
  15665. && this._cache.fovMode === this.fovMode
  15666. && this._cache.aspectRatio === engine.getAspectRatio(this);
  15667. }
  15668. else {
  15669. check = this._cache.orthoLeft === this.orthoLeft
  15670. && this._cache.orthoRight === this.orthoRight
  15671. && this._cache.orthoBottom === this.orthoBottom
  15672. && this._cache.orthoTop === this.orthoTop
  15673. && this._cache.renderWidth === engine.getRenderWidth()
  15674. && this._cache.renderHeight === engine.getRenderHeight();
  15675. }
  15676. return check;
  15677. };
  15678. // Controls
  15679. Camera.prototype.attachControl = function (element, noPreventDefault) {
  15680. };
  15681. Camera.prototype.detachControl = function (element) {
  15682. };
  15683. Camera.prototype.update = function () {
  15684. this._checkInputs();
  15685. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15686. this._updateRigCameras();
  15687. }
  15688. };
  15689. Camera.prototype._checkInputs = function () {
  15690. this.onAfterCheckInputsObservable.notifyObservers(this);
  15691. };
  15692. Object.defineProperty(Camera.prototype, "rigCameras", {
  15693. get: function () {
  15694. return this._rigCameras;
  15695. },
  15696. enumerable: true,
  15697. configurable: true
  15698. });
  15699. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  15700. get: function () {
  15701. return this._rigPostProcess;
  15702. },
  15703. enumerable: true,
  15704. configurable: true
  15705. });
  15706. Camera.prototype._cascadePostProcessesToRigCams = function () {
  15707. // invalidate framebuffer
  15708. if (this._postProcesses.length > 0) {
  15709. this._postProcesses[0].markTextureDirty();
  15710. }
  15711. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  15712. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  15713. var cam = this._rigCameras[i];
  15714. var rigPostProcess = cam._rigPostProcess;
  15715. // for VR rig, there does not have to be a post process
  15716. if (rigPostProcess) {
  15717. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  15718. if (isPass) {
  15719. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  15720. cam.isIntermediate = this._postProcesses.length === 0;
  15721. }
  15722. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  15723. rigPostProcess.markTextureDirty();
  15724. }
  15725. else {
  15726. cam._postProcesses = this._postProcesses.slice(0);
  15727. }
  15728. }
  15729. };
  15730. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  15731. if (insertAt === void 0) { insertAt = null; }
  15732. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  15733. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  15734. return 0;
  15735. }
  15736. if (insertAt == null || insertAt < 0) {
  15737. this._postProcesses.push(postProcess);
  15738. }
  15739. else {
  15740. this._postProcesses.splice(insertAt, 0, postProcess);
  15741. }
  15742. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15743. return this._postProcesses.indexOf(postProcess);
  15744. };
  15745. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  15746. if (atIndices === void 0) { atIndices = null; }
  15747. var result = [];
  15748. var i;
  15749. var index;
  15750. if (!atIndices) {
  15751. var idx = this._postProcesses.indexOf(postProcess);
  15752. if (idx !== -1) {
  15753. this._postProcesses.splice(idx, 1);
  15754. }
  15755. }
  15756. else {
  15757. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  15758. // iterate descending, so can just splice as we go
  15759. for (i = atIndices.length - 1; i >= 0; i--) {
  15760. if (this._postProcesses[atIndices[i]] !== postProcess) {
  15761. result.push(i);
  15762. continue;
  15763. }
  15764. index = atIndices[i];
  15765. this._postProcesses.splice(index, 1);
  15766. }
  15767. }
  15768. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15769. return result;
  15770. };
  15771. Camera.prototype.getWorldMatrix = function () {
  15772. if (!this._worldMatrix) {
  15773. this._worldMatrix = BABYLON.Matrix.Identity();
  15774. }
  15775. var viewMatrix = this.getViewMatrix();
  15776. viewMatrix.invertToRef(this._worldMatrix);
  15777. return this._worldMatrix;
  15778. };
  15779. Camera.prototype._getViewMatrix = function () {
  15780. return BABYLON.Matrix.Identity();
  15781. };
  15782. Camera.prototype.getViewMatrix = function (force) {
  15783. if (!force && this._isSynchronizedViewMatrix()) {
  15784. return this._computedViewMatrix;
  15785. }
  15786. this.updateCache();
  15787. this._computedViewMatrix = this._getViewMatrix();
  15788. this._currentRenderId = this.getScene().getRenderId();
  15789. this._refreshFrustumPlanes = true;
  15790. if (!this.parent || !this.parent.getWorldMatrix) {
  15791. this._globalPosition.copyFrom(this.position);
  15792. }
  15793. else {
  15794. if (!this._worldMatrix) {
  15795. this._worldMatrix = BABYLON.Matrix.Identity();
  15796. }
  15797. this._computedViewMatrix.invertToRef(this._worldMatrix);
  15798. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  15799. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  15800. this._computedViewMatrix.invert();
  15801. this._markSyncedWithParent();
  15802. }
  15803. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  15804. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  15805. }
  15806. this.onViewMatrixChangedObservable.notifyObservers(this);
  15807. return this._computedViewMatrix;
  15808. };
  15809. Camera.prototype.freezeProjectionMatrix = function (projection) {
  15810. this._doNotComputeProjectionMatrix = true;
  15811. if (projection !== undefined) {
  15812. this._projectionMatrix = projection;
  15813. }
  15814. };
  15815. ;
  15816. Camera.prototype.unfreezeProjectionMatrix = function () {
  15817. this._doNotComputeProjectionMatrix = false;
  15818. };
  15819. ;
  15820. Camera.prototype.getProjectionMatrix = function (force) {
  15821. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  15822. return this._projectionMatrix;
  15823. }
  15824. // Cache
  15825. this._cache.mode = this.mode;
  15826. this._cache.minZ = this.minZ;
  15827. this._cache.maxZ = this.maxZ;
  15828. // Matrix
  15829. this._refreshFrustumPlanes = true;
  15830. var engine = this.getEngine();
  15831. var scene = this.getScene();
  15832. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15833. this._cache.fov = this.fov;
  15834. this._cache.fovMode = this.fovMode;
  15835. this._cache.aspectRatio = engine.getAspectRatio(this);
  15836. if (this.minZ <= 0) {
  15837. this.minZ = 0.1;
  15838. }
  15839. if (scene.useRightHandedSystem) {
  15840. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15841. }
  15842. else {
  15843. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15844. }
  15845. }
  15846. else {
  15847. var halfWidth = engine.getRenderWidth() / 2.0;
  15848. var halfHeight = engine.getRenderHeight() / 2.0;
  15849. if (scene.useRightHandedSystem) {
  15850. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15851. }
  15852. else {
  15853. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15854. }
  15855. this._cache.orthoLeft = this.orthoLeft;
  15856. this._cache.orthoRight = this.orthoRight;
  15857. this._cache.orthoBottom = this.orthoBottom;
  15858. this._cache.orthoTop = this.orthoTop;
  15859. this._cache.renderWidth = engine.getRenderWidth();
  15860. this._cache.renderHeight = engine.getRenderHeight();
  15861. }
  15862. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  15863. return this._projectionMatrix;
  15864. };
  15865. Camera.prototype.getTranformationMatrix = function () {
  15866. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15867. return this._transformMatrix;
  15868. };
  15869. Camera.prototype.updateFrustumPlanes = function () {
  15870. if (!this._refreshFrustumPlanes) {
  15871. return;
  15872. }
  15873. this.getTranformationMatrix();
  15874. if (!this._frustumPlanes) {
  15875. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15876. }
  15877. else {
  15878. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15879. }
  15880. this._refreshFrustumPlanes = false;
  15881. };
  15882. Camera.prototype.isInFrustum = function (target) {
  15883. this.updateFrustumPlanes();
  15884. return target.isInFrustum(this._frustumPlanes);
  15885. };
  15886. Camera.prototype.isCompletelyInFrustum = function (target) {
  15887. this.updateFrustumPlanes();
  15888. return target.isCompletelyInFrustum(this._frustumPlanes);
  15889. };
  15890. Camera.prototype.getForwardRay = function (length, transform, origin) {
  15891. if (length === void 0) { length = 100; }
  15892. if (!transform) {
  15893. transform = this.getWorldMatrix();
  15894. }
  15895. if (!origin) {
  15896. origin = this.position;
  15897. }
  15898. var forward = new BABYLON.Vector3(0, 0, 1);
  15899. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  15900. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  15901. return new BABYLON.Ray(origin, direction, length);
  15902. };
  15903. Camera.prototype.dispose = function () {
  15904. // Observables
  15905. this.onViewMatrixChangedObservable.clear();
  15906. this.onProjectionMatrixChangedObservable.clear();
  15907. this.onAfterCheckInputsObservable.clear();
  15908. this.onRestoreStateObservable.clear();
  15909. // Inputs
  15910. if (this.inputs) {
  15911. this.inputs.clear();
  15912. }
  15913. // Animations
  15914. this.getScene().stopAnimation(this);
  15915. // Remove from scene
  15916. this.getScene().removeCamera(this);
  15917. while (this._rigCameras.length > 0) {
  15918. var camera = this._rigCameras.pop();
  15919. if (camera) {
  15920. camera.dispose();
  15921. }
  15922. }
  15923. // Postprocesses
  15924. if (this._rigPostProcess) {
  15925. this._rigPostProcess.dispose(this);
  15926. this._rigPostProcess = null;
  15927. this._postProcesses = [];
  15928. }
  15929. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15930. this._rigPostProcess = null;
  15931. this._postProcesses = [];
  15932. }
  15933. else {
  15934. var i = this._postProcesses.length;
  15935. while (--i >= 0) {
  15936. this._postProcesses[i].dispose(this);
  15937. }
  15938. }
  15939. // Render targets
  15940. var i = this.customRenderTargets.length;
  15941. while (--i >= 0) {
  15942. this.customRenderTargets[i].dispose();
  15943. }
  15944. this.customRenderTargets = [];
  15945. // Active Meshes
  15946. this._activeMeshes.dispose();
  15947. _super.prototype.dispose.call(this);
  15948. };
  15949. Object.defineProperty(Camera.prototype, "leftCamera", {
  15950. // ---- Camera rigs section ----
  15951. get: function () {
  15952. if (this._rigCameras.length < 1) {
  15953. return null;
  15954. }
  15955. return this._rigCameras[0];
  15956. },
  15957. enumerable: true,
  15958. configurable: true
  15959. });
  15960. Object.defineProperty(Camera.prototype, "rightCamera", {
  15961. get: function () {
  15962. if (this._rigCameras.length < 2) {
  15963. return null;
  15964. }
  15965. return this._rigCameras[1];
  15966. },
  15967. enumerable: true,
  15968. configurable: true
  15969. });
  15970. Camera.prototype.getLeftTarget = function () {
  15971. if (this._rigCameras.length < 1) {
  15972. return null;
  15973. }
  15974. return this._rigCameras[0].getTarget();
  15975. };
  15976. Camera.prototype.getRightTarget = function () {
  15977. if (this._rigCameras.length < 2) {
  15978. return null;
  15979. }
  15980. return this._rigCameras[1].getTarget();
  15981. };
  15982. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  15983. if (this.cameraRigMode === mode) {
  15984. return;
  15985. }
  15986. while (this._rigCameras.length > 0) {
  15987. var camera = this._rigCameras.pop();
  15988. if (camera) {
  15989. camera.dispose();
  15990. }
  15991. }
  15992. this.cameraRigMode = mode;
  15993. this._cameraRigParams = {};
  15994. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  15995. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  15996. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  15997. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  15998. // create the rig cameras, unless none
  15999. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16000. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  16001. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  16002. if (leftCamera && rightCamera) {
  16003. this._rigCameras.push(leftCamera);
  16004. this._rigCameras.push(rightCamera);
  16005. }
  16006. }
  16007. switch (this.cameraRigMode) {
  16008. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16009. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16010. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  16011. break;
  16012. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16013. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16014. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16015. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16016. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16017. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  16018. break;
  16019. case Camera.RIG_MODE_VR:
  16020. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  16021. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  16022. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16023. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16024. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  16025. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  16026. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  16027. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  16028. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16029. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16030. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  16031. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  16032. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  16033. if (metrics.compensateDistortion) {
  16034. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  16035. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  16036. }
  16037. break;
  16038. case Camera.RIG_MODE_WEBVR:
  16039. if (rigParams.vrDisplay) {
  16040. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  16041. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  16042. //Left eye
  16043. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16044. this._rigCameras[0].setCameraRigParameter("left", true);
  16045. //leaving this for future reference
  16046. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  16047. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  16048. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  16049. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16050. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16051. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16052. this._rigCameras[0].parent = this;
  16053. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  16054. //Right eye
  16055. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16056. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  16057. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  16058. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  16059. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16060. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16061. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16062. this._rigCameras[1].parent = this;
  16063. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  16064. if (Camera.UseAlternateWebVRRendering) {
  16065. this._rigCameras[1]._skipRendering = true;
  16066. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  16067. }
  16068. }
  16069. break;
  16070. }
  16071. this._cascadePostProcessesToRigCams();
  16072. this.update();
  16073. };
  16074. Camera.prototype._getVRProjectionMatrix = function () {
  16075. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  16076. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  16077. return this._projectionMatrix;
  16078. };
  16079. Camera.prototype._updateCameraRotationMatrix = function () {
  16080. //Here for WebVR
  16081. };
  16082. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  16083. //Here for WebVR
  16084. };
  16085. /**
  16086. * This function MUST be overwritten by the different WebVR cameras available.
  16087. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16088. */
  16089. Camera.prototype._getWebVRProjectionMatrix = function () {
  16090. return BABYLON.Matrix.Identity();
  16091. };
  16092. /**
  16093. * This function MUST be overwritten by the different WebVR cameras available.
  16094. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16095. */
  16096. Camera.prototype._getWebVRViewMatrix = function () {
  16097. return BABYLON.Matrix.Identity();
  16098. };
  16099. Camera.prototype.setCameraRigParameter = function (name, value) {
  16100. if (!this._cameraRigParams) {
  16101. this._cameraRigParams = {};
  16102. }
  16103. this._cameraRigParams[name] = value;
  16104. //provisionnally:
  16105. if (name === "interaxialDistance") {
  16106. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  16107. }
  16108. };
  16109. /**
  16110. * needs to be overridden by children so sub has required properties to be copied
  16111. */
  16112. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  16113. return null;
  16114. };
  16115. /**
  16116. * May need to be overridden by children
  16117. */
  16118. Camera.prototype._updateRigCameras = function () {
  16119. for (var i = 0; i < this._rigCameras.length; i++) {
  16120. this._rigCameras[i].minZ = this.minZ;
  16121. this._rigCameras[i].maxZ = this.maxZ;
  16122. this._rigCameras[i].fov = this.fov;
  16123. }
  16124. // only update viewport when ANAGLYPH
  16125. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  16126. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  16127. }
  16128. };
  16129. Camera.prototype._setupInputs = function () {
  16130. };
  16131. Camera.prototype.serialize = function () {
  16132. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  16133. // Type
  16134. serializationObject.type = this.getClassName();
  16135. // Parent
  16136. if (this.parent) {
  16137. serializationObject.parentId = this.parent.id;
  16138. }
  16139. if (this.inputs) {
  16140. this.inputs.serialize(serializationObject);
  16141. }
  16142. // Animations
  16143. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16144. serializationObject.ranges = this.serializeAnimationRanges();
  16145. return serializationObject;
  16146. };
  16147. Camera.prototype.clone = function (name) {
  16148. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  16149. };
  16150. Camera.prototype.getDirection = function (localAxis) {
  16151. var result = BABYLON.Vector3.Zero();
  16152. this.getDirectionToRef(localAxis, result);
  16153. return result;
  16154. };
  16155. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  16156. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16157. };
  16158. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  16159. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  16160. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  16161. switch (type) {
  16162. case "ArcRotateCamera":
  16163. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  16164. case "DeviceOrientationCamera":
  16165. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  16166. case "FollowCamera":
  16167. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  16168. case "ArcFollowCamera":
  16169. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  16170. case "GamepadCamera":
  16171. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16172. case "TouchCamera":
  16173. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  16174. case "VirtualJoysticksCamera":
  16175. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  16176. case "WebVRFreeCamera":
  16177. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16178. case "WebVRGamepadCamera":
  16179. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16180. case "VRDeviceOrientationFreeCamera":
  16181. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16182. case "VRDeviceOrientationGamepadCamera":
  16183. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16184. case "AnaglyphArcRotateCamera":
  16185. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16186. case "AnaglyphFreeCamera":
  16187. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16188. case "AnaglyphGamepadCamera":
  16189. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16190. case "AnaglyphUniversalCamera":
  16191. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16192. case "StereoscopicArcRotateCamera":
  16193. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16194. case "StereoscopicFreeCamera":
  16195. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16196. case "StereoscopicGamepadCamera":
  16197. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16198. case "StereoscopicUniversalCamera":
  16199. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16200. case "FreeCamera":// Forcing Universal here
  16201. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16202. default:// Universal Camera is the default value
  16203. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16204. }
  16205. };
  16206. Camera.Parse = function (parsedCamera, scene) {
  16207. var type = parsedCamera.type;
  16208. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  16209. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  16210. // Parent
  16211. if (parsedCamera.parentId) {
  16212. camera._waitingParentId = parsedCamera.parentId;
  16213. }
  16214. //If camera has an input manager, let it parse inputs settings
  16215. if (camera.inputs) {
  16216. camera.inputs.parse(parsedCamera);
  16217. camera._setupInputs();
  16218. }
  16219. if (camera.setPosition) {
  16220. camera.position.copyFromFloats(0, 0, 0);
  16221. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  16222. }
  16223. // Target
  16224. if (parsedCamera.target) {
  16225. if (camera.setTarget) {
  16226. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  16227. }
  16228. }
  16229. // Apply 3d rig, when found
  16230. if (parsedCamera.cameraRigMode) {
  16231. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  16232. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  16233. }
  16234. // Animations
  16235. if (parsedCamera.animations) {
  16236. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  16237. var parsedAnimation = parsedCamera.animations[animationIndex];
  16238. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16239. }
  16240. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  16241. }
  16242. if (parsedCamera.autoAnimate) {
  16243. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  16244. }
  16245. return camera;
  16246. };
  16247. // Statics
  16248. Camera._PERSPECTIVE_CAMERA = 0;
  16249. Camera._ORTHOGRAPHIC_CAMERA = 1;
  16250. Camera._FOVMODE_VERTICAL_FIXED = 0;
  16251. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  16252. Camera._RIG_MODE_NONE = 0;
  16253. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  16254. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  16255. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  16256. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  16257. Camera._RIG_MODE_VR = 20;
  16258. Camera._RIG_MODE_WEBVR = 21;
  16259. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  16260. Camera.UseAlternateWebVRRendering = false;
  16261. __decorate([
  16262. BABYLON.serializeAsVector3()
  16263. ], Camera.prototype, "position", void 0);
  16264. __decorate([
  16265. BABYLON.serializeAsVector3()
  16266. ], Camera.prototype, "upVector", void 0);
  16267. __decorate([
  16268. BABYLON.serialize()
  16269. ], Camera.prototype, "orthoLeft", void 0);
  16270. __decorate([
  16271. BABYLON.serialize()
  16272. ], Camera.prototype, "orthoRight", void 0);
  16273. __decorate([
  16274. BABYLON.serialize()
  16275. ], Camera.prototype, "orthoBottom", void 0);
  16276. __decorate([
  16277. BABYLON.serialize()
  16278. ], Camera.prototype, "orthoTop", void 0);
  16279. __decorate([
  16280. BABYLON.serialize()
  16281. ], Camera.prototype, "fov", void 0);
  16282. __decorate([
  16283. BABYLON.serialize()
  16284. ], Camera.prototype, "minZ", void 0);
  16285. __decorate([
  16286. BABYLON.serialize()
  16287. ], Camera.prototype, "maxZ", void 0);
  16288. __decorate([
  16289. BABYLON.serialize()
  16290. ], Camera.prototype, "inertia", void 0);
  16291. __decorate([
  16292. BABYLON.serialize()
  16293. ], Camera.prototype, "mode", void 0);
  16294. __decorate([
  16295. BABYLON.serialize()
  16296. ], Camera.prototype, "layerMask", void 0);
  16297. __decorate([
  16298. BABYLON.serialize()
  16299. ], Camera.prototype, "fovMode", void 0);
  16300. __decorate([
  16301. BABYLON.serialize()
  16302. ], Camera.prototype, "cameraRigMode", void 0);
  16303. __decorate([
  16304. BABYLON.serialize()
  16305. ], Camera.prototype, "interaxialDistance", void 0);
  16306. __decorate([
  16307. BABYLON.serialize()
  16308. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  16309. return Camera;
  16310. }(BABYLON.Node));
  16311. BABYLON.Camera = Camera;
  16312. })(BABYLON || (BABYLON = {}));
  16313. //# sourceMappingURL=babylon.camera.js.map
  16314. var BABYLON;
  16315. (function (BABYLON) {
  16316. var RenderingManager = /** @class */ (function () {
  16317. function RenderingManager(scene) {
  16318. this._renderingGroups = new Array();
  16319. this._autoClearDepthStencil = {};
  16320. this._customOpaqueSortCompareFn = {};
  16321. this._customAlphaTestSortCompareFn = {};
  16322. this._customTransparentSortCompareFn = {};
  16323. this._renderinGroupInfo = null;
  16324. this._scene = scene;
  16325. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  16326. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  16327. }
  16328. }
  16329. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  16330. if (depth === void 0) { depth = true; }
  16331. if (stencil === void 0) { stencil = true; }
  16332. if (this._depthStencilBufferAlreadyCleaned) {
  16333. return;
  16334. }
  16335. this._scene.getEngine().clear(null, false, depth, stencil);
  16336. this._depthStencilBufferAlreadyCleaned = true;
  16337. };
  16338. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  16339. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  16340. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  16341. var info = null;
  16342. if (observable) {
  16343. if (!this._renderinGroupInfo) {
  16344. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  16345. }
  16346. info = this._renderinGroupInfo;
  16347. info.scene = this._scene;
  16348. info.camera = this._scene.activeCamera;
  16349. }
  16350. // Dispatch sprites
  16351. if (renderSprites) {
  16352. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  16353. var manager = this._scene.spriteManagers[index];
  16354. this.dispatchSprites(manager);
  16355. }
  16356. }
  16357. // Render
  16358. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16359. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  16360. var renderingGroup = this._renderingGroups[index];
  16361. if (!renderingGroup && !observable)
  16362. continue;
  16363. this._currentIndex = index;
  16364. var renderingGroupMask = 0;
  16365. // Fire PRECLEAR stage
  16366. if (observable && info) {
  16367. renderingGroupMask = Math.pow(2, index);
  16368. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  16369. info.renderingGroupId = index;
  16370. observable.notifyObservers(info, renderingGroupMask);
  16371. }
  16372. // Clear depth/stencil if needed
  16373. if (RenderingManager.AUTOCLEAR) {
  16374. var autoClear = this._autoClearDepthStencil[index];
  16375. if (autoClear && autoClear.autoClear) {
  16376. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  16377. }
  16378. }
  16379. if (observable && info) {
  16380. // Fire PREOPAQUE stage
  16381. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  16382. observable.notifyObservers(info, renderingGroupMask);
  16383. // Fire PRETRANSPARENT stage
  16384. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  16385. observable.notifyObservers(info, renderingGroupMask);
  16386. }
  16387. if (renderingGroup)
  16388. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  16389. // Fire POSTTRANSPARENT stage
  16390. if (observable && info) {
  16391. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  16392. observable.notifyObservers(info, renderingGroupMask);
  16393. }
  16394. }
  16395. };
  16396. RenderingManager.prototype.reset = function () {
  16397. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16398. var renderingGroup = this._renderingGroups[index];
  16399. if (renderingGroup) {
  16400. renderingGroup.prepare();
  16401. }
  16402. }
  16403. };
  16404. RenderingManager.prototype.dispose = function () {
  16405. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16406. var renderingGroup = this._renderingGroups[index];
  16407. if (renderingGroup) {
  16408. renderingGroup.dispose();
  16409. }
  16410. }
  16411. this._renderingGroups.length = 0;
  16412. };
  16413. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  16414. if (!this._renderingGroups[renderingGroupId]) {
  16415. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  16416. }
  16417. };
  16418. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  16419. var renderingGroupId = spriteManager.renderingGroupId || 0;
  16420. this._prepareRenderingGroup(renderingGroupId);
  16421. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  16422. };
  16423. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  16424. var renderingGroupId = particleSystem.renderingGroupId || 0;
  16425. this._prepareRenderingGroup(renderingGroupId);
  16426. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  16427. };
  16428. RenderingManager.prototype.dispatch = function (subMesh) {
  16429. var mesh = subMesh.getMesh();
  16430. var renderingGroupId = mesh.renderingGroupId || 0;
  16431. this._prepareRenderingGroup(renderingGroupId);
  16432. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  16433. };
  16434. /**
  16435. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  16436. * This allowed control for front to back rendering or reversly depending of the special needs.
  16437. *
  16438. * @param renderingGroupId The rendering group id corresponding to its index
  16439. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  16440. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  16441. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  16442. */
  16443. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16444. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16445. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16446. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16447. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  16448. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  16449. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  16450. if (this._renderingGroups[renderingGroupId]) {
  16451. var group = this._renderingGroups[renderingGroupId];
  16452. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  16453. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  16454. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  16455. }
  16456. };
  16457. /**
  16458. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  16459. *
  16460. * @param renderingGroupId The rendering group id corresponding to its index
  16461. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  16462. * @param depth Automatically clears depth between groups if true and autoClear is true.
  16463. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  16464. */
  16465. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  16466. if (depth === void 0) { depth = true; }
  16467. if (stencil === void 0) { stencil = true; }
  16468. this._autoClearDepthStencil[renderingGroupId] = {
  16469. autoClear: autoClearDepthStencil,
  16470. depth: depth,
  16471. stencil: stencil
  16472. };
  16473. };
  16474. /**
  16475. * The max id used for rendering groups (not included)
  16476. */
  16477. RenderingManager.MAX_RENDERINGGROUPS = 4;
  16478. /**
  16479. * The min id used for rendering groups (included)
  16480. */
  16481. RenderingManager.MIN_RENDERINGGROUPS = 0;
  16482. /**
  16483. * Used to globally prevent autoclearing scenes.
  16484. */
  16485. RenderingManager.AUTOCLEAR = true;
  16486. return RenderingManager;
  16487. }());
  16488. BABYLON.RenderingManager = RenderingManager;
  16489. })(BABYLON || (BABYLON = {}));
  16490. //# sourceMappingURL=babylon.renderingManager.js.map
  16491. var BABYLON;
  16492. (function (BABYLON) {
  16493. var RenderingGroup = /** @class */ (function () {
  16494. /**
  16495. * Creates a new rendering group.
  16496. * @param index The rendering group index
  16497. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  16498. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  16499. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  16500. */
  16501. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16502. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16503. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16504. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16505. this.index = index;
  16506. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  16507. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  16508. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  16509. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  16510. this._particleSystems = new BABYLON.SmartArray(256);
  16511. this._spriteManagers = new BABYLON.SmartArray(256);
  16512. this._edgesRenderers = new BABYLON.SmartArray(16);
  16513. this._scene = scene;
  16514. this.opaqueSortCompareFn = opaqueSortCompareFn;
  16515. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  16516. this.transparentSortCompareFn = transparentSortCompareFn;
  16517. }
  16518. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  16519. /**
  16520. * Set the opaque sort comparison function.
  16521. * If null the sub meshes will be render in the order they were created
  16522. */
  16523. set: function (value) {
  16524. this._opaqueSortCompareFn = value;
  16525. if (value) {
  16526. this._renderOpaque = this.renderOpaqueSorted;
  16527. }
  16528. else {
  16529. this._renderOpaque = RenderingGroup.renderUnsorted;
  16530. }
  16531. },
  16532. enumerable: true,
  16533. configurable: true
  16534. });
  16535. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  16536. /**
  16537. * Set the alpha test sort comparison function.
  16538. * If null the sub meshes will be render in the order they were created
  16539. */
  16540. set: function (value) {
  16541. this._alphaTestSortCompareFn = value;
  16542. if (value) {
  16543. this._renderAlphaTest = this.renderAlphaTestSorted;
  16544. }
  16545. else {
  16546. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  16547. }
  16548. },
  16549. enumerable: true,
  16550. configurable: true
  16551. });
  16552. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  16553. /**
  16554. * Set the transparent sort comparison function.
  16555. * If null the sub meshes will be render in the order they were created
  16556. */
  16557. set: function (value) {
  16558. if (value) {
  16559. this._transparentSortCompareFn = value;
  16560. }
  16561. else {
  16562. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  16563. }
  16564. this._renderTransparent = this.renderTransparentSorted;
  16565. },
  16566. enumerable: true,
  16567. configurable: true
  16568. });
  16569. /**
  16570. * Render all the sub meshes contained in the group.
  16571. * @param customRenderFunction Used to override the default render behaviour of the group.
  16572. * @returns true if rendered some submeshes.
  16573. */
  16574. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  16575. if (customRenderFunction) {
  16576. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  16577. return;
  16578. }
  16579. var engine = this._scene.getEngine();
  16580. // Depth only
  16581. if (this._depthOnlySubMeshes.length !== 0) {
  16582. engine.setAlphaTesting(true);
  16583. engine.setColorWrite(false);
  16584. this._renderAlphaTest(this._depthOnlySubMeshes);
  16585. engine.setAlphaTesting(false);
  16586. engine.setColorWrite(true);
  16587. }
  16588. // Opaque
  16589. if (this._opaqueSubMeshes.length !== 0) {
  16590. this._renderOpaque(this._opaqueSubMeshes);
  16591. }
  16592. // Alpha test
  16593. if (this._alphaTestSubMeshes.length !== 0) {
  16594. engine.setAlphaTesting(true);
  16595. this._renderAlphaTest(this._alphaTestSubMeshes);
  16596. engine.setAlphaTesting(false);
  16597. }
  16598. var stencilState = engine.getStencilBuffer();
  16599. engine.setStencilBuffer(false);
  16600. // Sprites
  16601. if (renderSprites) {
  16602. this._renderSprites();
  16603. }
  16604. // Particles
  16605. if (renderParticles) {
  16606. this._renderParticles(activeMeshes);
  16607. }
  16608. if (this.onBeforeTransparentRendering) {
  16609. this.onBeforeTransparentRendering();
  16610. }
  16611. // Transparent
  16612. if (this._transparentSubMeshes.length !== 0) {
  16613. this._renderTransparent(this._transparentSubMeshes);
  16614. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16615. }
  16616. // Set back stencil to false in case it changes before the edge renderer.
  16617. engine.setStencilBuffer(false);
  16618. // Edges
  16619. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16620. this._edgesRenderers.data[edgesRendererIndex].render();
  16621. }
  16622. // Restore Stencil state.
  16623. engine.setStencilBuffer(stencilState);
  16624. };
  16625. /**
  16626. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  16627. * @param subMeshes The submeshes to render
  16628. */
  16629. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  16630. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  16631. };
  16632. /**
  16633. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  16634. * @param subMeshes The submeshes to render
  16635. */
  16636. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  16637. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  16638. };
  16639. /**
  16640. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  16641. * @param subMeshes The submeshes to render
  16642. */
  16643. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  16644. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  16645. };
  16646. /**
  16647. * Renders the submeshes in a specified order.
  16648. * @param subMeshes The submeshes to sort before render
  16649. * @param sortCompareFn The comparison function use to sort
  16650. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  16651. * @param transparent Specifies to activate blending if true
  16652. */
  16653. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  16654. var subIndex = 0;
  16655. var subMesh;
  16656. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  16657. for (; subIndex < subMeshes.length; subIndex++) {
  16658. subMesh = subMeshes.data[subIndex];
  16659. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  16660. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  16661. }
  16662. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  16663. if (sortCompareFn) {
  16664. sortedArray.sort(sortCompareFn);
  16665. }
  16666. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  16667. subMesh = sortedArray[subIndex];
  16668. if (transparent) {
  16669. var material = subMesh.getMaterial();
  16670. if (material.needDepthPrePass) {
  16671. var engine = material.getScene().getEngine();
  16672. engine.setColorWrite(false);
  16673. engine.setAlphaTesting(true);
  16674. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16675. subMesh.render(false);
  16676. engine.setAlphaTesting(false);
  16677. engine.setColorWrite(true);
  16678. }
  16679. }
  16680. subMesh.render(transparent);
  16681. }
  16682. };
  16683. /**
  16684. * Renders the submeshes in the order they were dispatched (no sort applied).
  16685. * @param subMeshes The submeshes to render
  16686. */
  16687. RenderingGroup.renderUnsorted = function (subMeshes) {
  16688. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  16689. var submesh = subMeshes.data[subIndex];
  16690. submesh.render(false);
  16691. }
  16692. };
  16693. /**
  16694. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16695. * are rendered back to front if in the same alpha index.
  16696. *
  16697. * @param a The first submesh
  16698. * @param b The second submesh
  16699. * @returns The result of the comparison
  16700. */
  16701. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  16702. // Alpha index first
  16703. if (a._alphaIndex > b._alphaIndex) {
  16704. return 1;
  16705. }
  16706. if (a._alphaIndex < b._alphaIndex) {
  16707. return -1;
  16708. }
  16709. // Then distance to camera
  16710. return RenderingGroup.backToFrontSortCompare(a, b);
  16711. };
  16712. /**
  16713. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16714. * are rendered back to front.
  16715. *
  16716. * @param a The first submesh
  16717. * @param b The second submesh
  16718. * @returns The result of the comparison
  16719. */
  16720. RenderingGroup.backToFrontSortCompare = function (a, b) {
  16721. // Then distance to camera
  16722. if (a._distanceToCamera < b._distanceToCamera) {
  16723. return 1;
  16724. }
  16725. if (a._distanceToCamera > b._distanceToCamera) {
  16726. return -1;
  16727. }
  16728. return 0;
  16729. };
  16730. /**
  16731. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16732. * are rendered front to back (prevent overdraw).
  16733. *
  16734. * @param a The first submesh
  16735. * @param b The second submesh
  16736. * @returns The result of the comparison
  16737. */
  16738. RenderingGroup.frontToBackSortCompare = function (a, b) {
  16739. // Then distance to camera
  16740. if (a._distanceToCamera < b._distanceToCamera) {
  16741. return -1;
  16742. }
  16743. if (a._distanceToCamera > b._distanceToCamera) {
  16744. return 1;
  16745. }
  16746. return 0;
  16747. };
  16748. /**
  16749. * Resets the different lists of submeshes to prepare a new frame.
  16750. */
  16751. RenderingGroup.prototype.prepare = function () {
  16752. this._opaqueSubMeshes.reset();
  16753. this._transparentSubMeshes.reset();
  16754. this._alphaTestSubMeshes.reset();
  16755. this._depthOnlySubMeshes.reset();
  16756. this._particleSystems.reset();
  16757. this._spriteManagers.reset();
  16758. this._edgesRenderers.reset();
  16759. };
  16760. RenderingGroup.prototype.dispose = function () {
  16761. this._opaqueSubMeshes.dispose();
  16762. this._transparentSubMeshes.dispose();
  16763. this._alphaTestSubMeshes.dispose();
  16764. this._depthOnlySubMeshes.dispose();
  16765. this._particleSystems.dispose();
  16766. this._spriteManagers.dispose();
  16767. this._edgesRenderers.dispose();
  16768. };
  16769. /**
  16770. * Inserts the submesh in its correct queue depending on its material.
  16771. * @param subMesh The submesh to dispatch
  16772. */
  16773. RenderingGroup.prototype.dispatch = function (subMesh) {
  16774. var material = subMesh.getMaterial();
  16775. var mesh = subMesh.getMesh();
  16776. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  16777. this._transparentSubMeshes.push(subMesh);
  16778. }
  16779. else if (material.needAlphaTesting()) {
  16780. if (material.needDepthPrePass) {
  16781. this._depthOnlySubMeshes.push(subMesh);
  16782. }
  16783. this._alphaTestSubMeshes.push(subMesh);
  16784. }
  16785. else {
  16786. if (material.needDepthPrePass) {
  16787. this._depthOnlySubMeshes.push(subMesh);
  16788. }
  16789. this._opaqueSubMeshes.push(subMesh); // Opaque
  16790. }
  16791. if (mesh._edgesRenderer) {
  16792. this._edgesRenderers.push(mesh._edgesRenderer);
  16793. }
  16794. };
  16795. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  16796. this._spriteManagers.push(spriteManager);
  16797. };
  16798. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  16799. this._particleSystems.push(particleSystem);
  16800. };
  16801. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  16802. if (this._particleSystems.length === 0) {
  16803. return;
  16804. }
  16805. // Particles
  16806. var activeCamera = this._scene.activeCamera;
  16807. this._scene._particlesDuration.beginMonitoring();
  16808. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  16809. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  16810. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  16811. continue;
  16812. }
  16813. var emitter = particleSystem.emitter;
  16814. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  16815. this._scene._activeParticles.addCount(particleSystem.render(), false);
  16816. }
  16817. }
  16818. this._scene._particlesDuration.endMonitoring(false);
  16819. };
  16820. RenderingGroup.prototype._renderSprites = function () {
  16821. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  16822. return;
  16823. }
  16824. // Sprites
  16825. var activeCamera = this._scene.activeCamera;
  16826. this._scene._spritesDuration.beginMonitoring();
  16827. for (var id = 0; id < this._spriteManagers.length; id++) {
  16828. var spriteManager = this._spriteManagers.data[id];
  16829. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  16830. spriteManager.render();
  16831. }
  16832. }
  16833. this._scene._spritesDuration.endMonitoring(false);
  16834. };
  16835. return RenderingGroup;
  16836. }());
  16837. BABYLON.RenderingGroup = RenderingGroup;
  16838. })(BABYLON || (BABYLON = {}));
  16839. //# sourceMappingURL=babylon.renderingGroup.js.map
  16840. var BABYLON;
  16841. (function (BABYLON) {
  16842. var ClickInfo = /** @class */ (function () {
  16843. function ClickInfo() {
  16844. this._singleClick = false;
  16845. this._doubleClick = false;
  16846. this._hasSwiped = false;
  16847. this._ignore = false;
  16848. }
  16849. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  16850. get: function () {
  16851. return this._singleClick;
  16852. },
  16853. set: function (b) {
  16854. this._singleClick = b;
  16855. },
  16856. enumerable: true,
  16857. configurable: true
  16858. });
  16859. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  16860. get: function () {
  16861. return this._doubleClick;
  16862. },
  16863. set: function (b) {
  16864. this._doubleClick = b;
  16865. },
  16866. enumerable: true,
  16867. configurable: true
  16868. });
  16869. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  16870. get: function () {
  16871. return this._hasSwiped;
  16872. },
  16873. set: function (b) {
  16874. this._hasSwiped = b;
  16875. },
  16876. enumerable: true,
  16877. configurable: true
  16878. });
  16879. Object.defineProperty(ClickInfo.prototype, "ignore", {
  16880. get: function () {
  16881. return this._ignore;
  16882. },
  16883. set: function (b) {
  16884. this._ignore = b;
  16885. },
  16886. enumerable: true,
  16887. configurable: true
  16888. });
  16889. return ClickInfo;
  16890. }());
  16891. /**
  16892. * This class is used by the onRenderingGroupObservable
  16893. */
  16894. var RenderingGroupInfo = /** @class */ (function () {
  16895. function RenderingGroupInfo() {
  16896. }
  16897. /**
  16898. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  16899. * This stage will be fired no matter what
  16900. */
  16901. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  16902. /**
  16903. * Called before opaque object are rendered.
  16904. * This stage will be fired only if there's 3D Opaque content to render
  16905. */
  16906. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  16907. /**
  16908. * Called after the opaque objects are rendered and before the transparent ones
  16909. * This stage will be fired only if there's 3D transparent content to render
  16910. */
  16911. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  16912. /**
  16913. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  16914. * This stage will be fired no matter what
  16915. */
  16916. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  16917. return RenderingGroupInfo;
  16918. }());
  16919. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  16920. /**
  16921. * Represents a scene to be rendered by the engine.
  16922. * @see http://doc.babylonjs.com/page.php?p=21911
  16923. */
  16924. var Scene = /** @class */ (function () {
  16925. /**
  16926. * @constructor
  16927. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16928. */
  16929. function Scene(engine) {
  16930. // Members
  16931. this.autoClear = true;
  16932. this.autoClearDepthAndStencil = true;
  16933. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  16934. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16935. this.forceWireframe = false;
  16936. this._forcePointsCloud = false;
  16937. this.forceShowBoundingBoxes = false;
  16938. this.animationsEnabled = true;
  16939. this.constantlyUpdateMeshUnderPointer = false;
  16940. this.hoverCursor = "pointer";
  16941. this.defaultCursor = "";
  16942. /**
  16943. * This is used to call preventDefault() on pointer down
  16944. * in order to block unwanted artifacts like system double clicks
  16945. */
  16946. this.preventDefaultOnPointerDown = true;
  16947. // Metadata
  16948. this.metadata = null;
  16949. /**
  16950. * An event triggered when the scene is disposed.
  16951. * @type {BABYLON.Observable}
  16952. */
  16953. this.onDisposeObservable = new BABYLON.Observable();
  16954. /**
  16955. * An event triggered before rendering the scene
  16956. * @type {BABYLON.Observable}
  16957. */
  16958. this.onBeforeRenderObservable = new BABYLON.Observable();
  16959. /**
  16960. * An event triggered after rendering the scene
  16961. * @type {BABYLON.Observable}
  16962. */
  16963. this.onAfterRenderObservable = new BABYLON.Observable();
  16964. /**
  16965. * An event triggered when the scene is ready
  16966. * @type {BABYLON.Observable}
  16967. */
  16968. this.onReadyObservable = new BABYLON.Observable();
  16969. /**
  16970. * An event triggered before rendering a camera
  16971. * @type {BABYLON.Observable}
  16972. */
  16973. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16974. /**
  16975. * An event triggered after rendering a camera
  16976. * @type {BABYLON.Observable}
  16977. */
  16978. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16979. /**
  16980. * An event triggered when a camera is created
  16981. * @type {BABYLON.Observable}
  16982. */
  16983. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16984. /**
  16985. * An event triggered when a camera is removed
  16986. * @type {BABYLON.Observable}
  16987. */
  16988. this.onCameraRemovedObservable = new BABYLON.Observable();
  16989. /**
  16990. * An event triggered when a light is created
  16991. * @type {BABYLON.Observable}
  16992. */
  16993. this.onNewLightAddedObservable = new BABYLON.Observable();
  16994. /**
  16995. * An event triggered when a light is removed
  16996. * @type {BABYLON.Observable}
  16997. */
  16998. this.onLightRemovedObservable = new BABYLON.Observable();
  16999. /**
  17000. * An event triggered when a geometry is created
  17001. * @type {BABYLON.Observable}
  17002. */
  17003. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  17004. /**
  17005. * An event triggered when a geometry is removed
  17006. * @type {BABYLON.Observable}
  17007. */
  17008. this.onGeometryRemovedObservable = new BABYLON.Observable();
  17009. /**
  17010. * An event triggered when a mesh is created
  17011. * @type {BABYLON.Observable}
  17012. */
  17013. this.onNewMeshAddedObservable = new BABYLON.Observable();
  17014. /**
  17015. * An event triggered when a mesh is removed
  17016. * @type {BABYLON.Observable}
  17017. */
  17018. this.onMeshRemovedObservable = new BABYLON.Observable();
  17019. /**
  17020. * An event triggered before calculating deterministic simulation step
  17021. * @type {BABYLON.Observable}
  17022. */
  17023. this.onBeforeStepObservable = new BABYLON.Observable();
  17024. /**
  17025. * An event triggered after calculating deterministic simulation step
  17026. * @type {BABYLON.Observable}
  17027. */
  17028. this.onAfterStepObservable = new BABYLON.Observable();
  17029. /**
  17030. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  17031. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  17032. * 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)
  17033. */
  17034. this.onRenderingGroupObservable = new BABYLON.Observable();
  17035. // Animations
  17036. this.animations = [];
  17037. /**
  17038. * 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).
  17039. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  17040. */
  17041. this.onPrePointerObservable = new BABYLON.Observable();
  17042. /**
  17043. * Observable event triggered each time an input event is received from the rendering canvas
  17044. */
  17045. this.onPointerObservable = new BABYLON.Observable();
  17046. this._meshPickProceed = false;
  17047. this._previousHasSwiped = false;
  17048. this._currentPickResult = null;
  17049. this._previousPickResult = null;
  17050. this._totalPointersPressed = 0;
  17051. this._doubleClickOccured = false;
  17052. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  17053. this.cameraToUseForPointers = null;
  17054. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  17055. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  17056. this._startingPointerTime = 0;
  17057. this._previousStartingPointerTime = 0;
  17058. // Deterministic lockstep
  17059. this._timeAccumulator = 0;
  17060. this._currentStepId = 0;
  17061. this._currentInternalStep = 0;
  17062. // Keyboard
  17063. /**
  17064. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  17065. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  17066. */
  17067. this.onPreKeyboardObservable = new BABYLON.Observable();
  17068. /**
  17069. * Observable event triggered each time an keyboard event is received from the hosting window
  17070. */
  17071. this.onKeyboardObservable = new BABYLON.Observable();
  17072. // Coordinate system
  17073. /**
  17074. * use right-handed coordinate system on this scene.
  17075. * @type {boolean}
  17076. */
  17077. this._useRightHandedSystem = false;
  17078. // Fog
  17079. this._fogEnabled = true;
  17080. this._fogMode = Scene.FOGMODE_NONE;
  17081. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  17082. this.fogDensity = 0.1;
  17083. this.fogStart = 0;
  17084. this.fogEnd = 1000.0;
  17085. // Lights
  17086. /**
  17087. * is shadow enabled on this scene.
  17088. * @type {boolean}
  17089. */
  17090. this._shadowsEnabled = true;
  17091. /**
  17092. * is light enabled on this scene.
  17093. * @type {boolean}
  17094. */
  17095. this._lightsEnabled = true;
  17096. /**
  17097. * All of the lights added to this scene.
  17098. * @see BABYLON.Light
  17099. * @type {BABYLON.Light[]}
  17100. */
  17101. this.lights = new Array();
  17102. // Cameras
  17103. /** All of the cameras added to this scene. */
  17104. this.cameras = new Array();
  17105. /** All of the active cameras added to this scene. */
  17106. this.activeCameras = new Array();
  17107. // Meshes
  17108. /**
  17109. * All of the (abstract) meshes added to this scene.
  17110. * @see BABYLON.AbstractMesh
  17111. * @type {BABYLON.AbstractMesh[]}
  17112. */
  17113. this.meshes = new Array();
  17114. // Geometries
  17115. this._geometries = new Array();
  17116. this.materials = new Array();
  17117. this.multiMaterials = new Array();
  17118. // Textures
  17119. this._texturesEnabled = true;
  17120. this.textures = new Array();
  17121. // Particles
  17122. this.particlesEnabled = true;
  17123. this.particleSystems = new Array();
  17124. // Sprites
  17125. this.spritesEnabled = true;
  17126. this.spriteManagers = new Array();
  17127. // Layers
  17128. this.layers = new Array();
  17129. this.highlightLayers = new Array();
  17130. // Skeletons
  17131. this._skeletonsEnabled = true;
  17132. this.skeletons = new Array();
  17133. // Morph targets
  17134. this.morphTargetManagers = new Array();
  17135. // Lens flares
  17136. this.lensFlaresEnabled = true;
  17137. this.lensFlareSystems = new Array();
  17138. // Collisions
  17139. this.collisionsEnabled = true;
  17140. /** Defines the gravity applied to this scene */
  17141. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  17142. // Postprocesses
  17143. this.postProcesses = new Array();
  17144. this.postProcessesEnabled = true;
  17145. // Customs render targets
  17146. this.renderTargetsEnabled = true;
  17147. this.dumpNextRenderTargets = false;
  17148. this.customRenderTargets = new Array();
  17149. // Imported meshes
  17150. this.importedMeshesFiles = new Array();
  17151. // Probes
  17152. this.probesEnabled = true;
  17153. this.reflectionProbes = new Array();
  17154. this._actionManagers = new Array();
  17155. this._meshesForIntersections = new BABYLON.SmartArray(256);
  17156. // Procedural textures
  17157. this.proceduralTexturesEnabled = true;
  17158. this._proceduralTextures = new Array();
  17159. this.soundTracks = new Array();
  17160. this._audioEnabled = true;
  17161. this._headphone = false;
  17162. // Performance counters
  17163. this._totalMeshesCounter = new BABYLON.PerfCounter();
  17164. this._totalLightsCounter = new BABYLON.PerfCounter();
  17165. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  17166. this._totalTexturesCounter = new BABYLON.PerfCounter();
  17167. this._totalVertices = new BABYLON.PerfCounter();
  17168. this._activeIndices = new BABYLON.PerfCounter();
  17169. this._activeParticles = new BABYLON.PerfCounter();
  17170. this._interFrameDuration = new BABYLON.PerfCounter();
  17171. this._lastFrameDuration = new BABYLON.PerfCounter();
  17172. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  17173. this._renderTargetsDuration = new BABYLON.PerfCounter();
  17174. this._particlesDuration = new BABYLON.PerfCounter();
  17175. this._renderDuration = new BABYLON.PerfCounter();
  17176. this._spritesDuration = new BABYLON.PerfCounter();
  17177. this._activeBones = new BABYLON.PerfCounter();
  17178. this._animationTime = 0;
  17179. this.animationTimeScale = 1;
  17180. this._renderId = 0;
  17181. this._executeWhenReadyTimeoutId = -1;
  17182. this._intermediateRendering = false;
  17183. this._viewUpdateFlag = -1;
  17184. this._projectionUpdateFlag = -1;
  17185. this._alternateViewUpdateFlag = -1;
  17186. this._alternateProjectionUpdateFlag = -1;
  17187. this._toBeDisposed = new BABYLON.SmartArray(256);
  17188. this._pendingData = new Array();
  17189. this._activeMeshes = new BABYLON.SmartArray(256);
  17190. this._processedMaterials = new BABYLON.SmartArray(256);
  17191. this._renderTargets = new BABYLON.SmartArray(256);
  17192. this._activeParticleSystems = new BABYLON.SmartArray(256);
  17193. this._activeSkeletons = new BABYLON.SmartArray(32);
  17194. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  17195. this._activeAnimatables = new Array();
  17196. this._transformMatrix = BABYLON.Matrix.Zero();
  17197. this._useAlternateCameraConfiguration = false;
  17198. this._alternateRendering = false;
  17199. this.requireLightSorting = false;
  17200. this._activeMeshesFrozen = false;
  17201. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  17202. this._engine.scenes.push(this);
  17203. this._uid = null;
  17204. this._renderingManager = new BABYLON.RenderingManager(this);
  17205. this.postProcessManager = new BABYLON.PostProcessManager(this);
  17206. if (BABYLON.OutlineRenderer) {
  17207. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  17208. }
  17209. if (BABYLON.Tools.IsWindowObjectExist()) {
  17210. this.attachControl();
  17211. }
  17212. //simplification queue
  17213. if (BABYLON.SimplificationQueue) {
  17214. this.simplificationQueue = new BABYLON.SimplificationQueue();
  17215. }
  17216. //collision coordinator initialization. For now legacy per default.
  17217. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  17218. // Uniform Buffer
  17219. this._createUbo();
  17220. // Default Image processing definition.
  17221. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  17222. }
  17223. Object.defineProperty(Scene, "FOGMODE_NONE", {
  17224. /** The fog is deactivated */
  17225. get: function () {
  17226. return Scene._FOGMODE_NONE;
  17227. },
  17228. enumerable: true,
  17229. configurable: true
  17230. });
  17231. Object.defineProperty(Scene, "FOGMODE_EXP", {
  17232. /** The fog density is following an exponential function */
  17233. get: function () {
  17234. return Scene._FOGMODE_EXP;
  17235. },
  17236. enumerable: true,
  17237. configurable: true
  17238. });
  17239. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  17240. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  17241. get: function () {
  17242. return Scene._FOGMODE_EXP2;
  17243. },
  17244. enumerable: true,
  17245. configurable: true
  17246. });
  17247. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  17248. /** The fog density is following a linear function. */
  17249. get: function () {
  17250. return Scene._FOGMODE_LINEAR;
  17251. },
  17252. enumerable: true,
  17253. configurable: true
  17254. });
  17255. Object.defineProperty(Scene.prototype, "environmentTexture", {
  17256. /**
  17257. * Texture used in all pbr material as the reflection texture.
  17258. * As in the majority of the scene they are the same (exception for multi room and so on),
  17259. * this is easier to reference from here than from all the materials.
  17260. */
  17261. get: function () {
  17262. return this._environmentTexture;
  17263. },
  17264. /**
  17265. * Texture used in all pbr material as the reflection texture.
  17266. * As in the majority of the scene they are the same (exception for multi room and so on),
  17267. * this is easier to set here than in all the materials.
  17268. */
  17269. set: function (value) {
  17270. if (this._environmentTexture === value) {
  17271. return;
  17272. }
  17273. this._environmentTexture = value;
  17274. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17275. },
  17276. enumerable: true,
  17277. configurable: true
  17278. });
  17279. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  17280. /**
  17281. * Default image processing configuration used either in the rendering
  17282. * Forward main pass or through the imageProcessingPostProcess if present.
  17283. * As in the majority of the scene they are the same (exception for multi camera),
  17284. * this is easier to reference from here than from all the materials and post process.
  17285. *
  17286. * No setter as we it is a shared configuration, you can set the values instead.
  17287. */
  17288. get: function () {
  17289. return this._imageProcessingConfiguration;
  17290. },
  17291. enumerable: true,
  17292. configurable: true
  17293. });
  17294. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  17295. get: function () {
  17296. return this._forcePointsCloud;
  17297. },
  17298. set: function (value) {
  17299. if (this._forcePointsCloud === value) {
  17300. return;
  17301. }
  17302. this._forcePointsCloud = value;
  17303. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17304. },
  17305. enumerable: true,
  17306. configurable: true
  17307. });
  17308. Object.defineProperty(Scene.prototype, "onDispose", {
  17309. /** A function to be executed when this scene is disposed. */
  17310. set: function (callback) {
  17311. if (this._onDisposeObserver) {
  17312. this.onDisposeObservable.remove(this._onDisposeObserver);
  17313. }
  17314. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17315. },
  17316. enumerable: true,
  17317. configurable: true
  17318. });
  17319. Object.defineProperty(Scene.prototype, "beforeRender", {
  17320. /** A function to be executed before rendering this scene */
  17321. set: function (callback) {
  17322. if (this._onBeforeRenderObserver) {
  17323. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  17324. }
  17325. if (callback) {
  17326. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  17327. }
  17328. },
  17329. enumerable: true,
  17330. configurable: true
  17331. });
  17332. Object.defineProperty(Scene.prototype, "afterRender", {
  17333. /** A function to be executed after rendering this scene */
  17334. set: function (callback) {
  17335. if (this._onAfterRenderObserver) {
  17336. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  17337. }
  17338. if (callback) {
  17339. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  17340. }
  17341. },
  17342. enumerable: true,
  17343. configurable: true
  17344. });
  17345. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  17346. set: function (callback) {
  17347. if (this._onBeforeCameraRenderObserver) {
  17348. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  17349. }
  17350. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  17351. },
  17352. enumerable: true,
  17353. configurable: true
  17354. });
  17355. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  17356. set: function (callback) {
  17357. if (this._onAfterCameraRenderObserver) {
  17358. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  17359. }
  17360. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  17361. },
  17362. enumerable: true,
  17363. configurable: true
  17364. });
  17365. Object.defineProperty(Scene.prototype, "gamepadManager", {
  17366. get: function () {
  17367. if (!this._gamepadManager) {
  17368. this._gamepadManager = new BABYLON.GamepadManager();
  17369. }
  17370. return this._gamepadManager;
  17371. },
  17372. enumerable: true,
  17373. configurable: true
  17374. });
  17375. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  17376. get: function () {
  17377. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  17378. },
  17379. enumerable: true,
  17380. configurable: true
  17381. });
  17382. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  17383. get: function () {
  17384. return this._useRightHandedSystem;
  17385. },
  17386. set: function (value) {
  17387. if (this._useRightHandedSystem === value) {
  17388. return;
  17389. }
  17390. this._useRightHandedSystem = value;
  17391. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17392. },
  17393. enumerable: true,
  17394. configurable: true
  17395. });
  17396. Scene.prototype.setStepId = function (newStepId) {
  17397. this._currentStepId = newStepId;
  17398. };
  17399. ;
  17400. Scene.prototype.getStepId = function () {
  17401. return this._currentStepId;
  17402. };
  17403. ;
  17404. Scene.prototype.getInternalStep = function () {
  17405. return this._currentInternalStep;
  17406. };
  17407. ;
  17408. Object.defineProperty(Scene.prototype, "fogEnabled", {
  17409. get: function () {
  17410. return this._fogEnabled;
  17411. },
  17412. /**
  17413. * is fog enabled on this scene.
  17414. */
  17415. set: function (value) {
  17416. if (this._fogEnabled === value) {
  17417. return;
  17418. }
  17419. this._fogEnabled = value;
  17420. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17421. },
  17422. enumerable: true,
  17423. configurable: true
  17424. });
  17425. Object.defineProperty(Scene.prototype, "fogMode", {
  17426. get: function () {
  17427. return this._fogMode;
  17428. },
  17429. set: function (value) {
  17430. if (this._fogMode === value) {
  17431. return;
  17432. }
  17433. this._fogMode = value;
  17434. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17435. },
  17436. enumerable: true,
  17437. configurable: true
  17438. });
  17439. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  17440. get: function () {
  17441. return this._shadowsEnabled;
  17442. },
  17443. set: function (value) {
  17444. if (this._shadowsEnabled === value) {
  17445. return;
  17446. }
  17447. this._shadowsEnabled = value;
  17448. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  17449. },
  17450. enumerable: true,
  17451. configurable: true
  17452. });
  17453. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  17454. get: function () {
  17455. return this._lightsEnabled;
  17456. },
  17457. set: function (value) {
  17458. if (this._lightsEnabled === value) {
  17459. return;
  17460. }
  17461. this._lightsEnabled = value;
  17462. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  17463. },
  17464. enumerable: true,
  17465. configurable: true
  17466. });
  17467. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  17468. /** The default material used on meshes when no material is affected */
  17469. get: function () {
  17470. if (!this._defaultMaterial) {
  17471. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  17472. }
  17473. return this._defaultMaterial;
  17474. },
  17475. /** The default material used on meshes when no material is affected */
  17476. set: function (value) {
  17477. this._defaultMaterial = value;
  17478. },
  17479. enumerable: true,
  17480. configurable: true
  17481. });
  17482. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  17483. get: function () {
  17484. return this._texturesEnabled;
  17485. },
  17486. set: function (value) {
  17487. if (this._texturesEnabled === value) {
  17488. return;
  17489. }
  17490. this._texturesEnabled = value;
  17491. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17492. },
  17493. enumerable: true,
  17494. configurable: true
  17495. });
  17496. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  17497. get: function () {
  17498. return this._skeletonsEnabled;
  17499. },
  17500. set: function (value) {
  17501. if (this._skeletonsEnabled === value) {
  17502. return;
  17503. }
  17504. this._skeletonsEnabled = value;
  17505. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  17506. },
  17507. enumerable: true,
  17508. configurable: true
  17509. });
  17510. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  17511. get: function () {
  17512. if (!this._postProcessRenderPipelineManager) {
  17513. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  17514. }
  17515. return this._postProcessRenderPipelineManager;
  17516. },
  17517. enumerable: true,
  17518. configurable: true
  17519. });
  17520. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  17521. get: function () {
  17522. if (!this._mainSoundTrack) {
  17523. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  17524. }
  17525. return this._mainSoundTrack;
  17526. },
  17527. enumerable: true,
  17528. configurable: true
  17529. });
  17530. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  17531. get: function () {
  17532. return this._alternateRendering;
  17533. },
  17534. enumerable: true,
  17535. configurable: true
  17536. });
  17537. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  17538. get: function () {
  17539. return this._frustumPlanes;
  17540. },
  17541. enumerable: true,
  17542. configurable: true
  17543. });
  17544. Object.defineProperty(Scene.prototype, "debugLayer", {
  17545. // Properties
  17546. get: function () {
  17547. if (!this._debugLayer) {
  17548. this._debugLayer = new BABYLON.DebugLayer(this);
  17549. }
  17550. return this._debugLayer;
  17551. },
  17552. enumerable: true,
  17553. configurable: true
  17554. });
  17555. Object.defineProperty(Scene.prototype, "workerCollisions", {
  17556. get: function () {
  17557. return this._workerCollisions;
  17558. },
  17559. set: function (enabled) {
  17560. if (!BABYLON.CollisionCoordinatorLegacy) {
  17561. return;
  17562. }
  17563. enabled = (enabled && !!Worker);
  17564. this._workerCollisions = enabled;
  17565. if (this.collisionCoordinator) {
  17566. this.collisionCoordinator.destroy();
  17567. }
  17568. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  17569. this.collisionCoordinator.init(this);
  17570. },
  17571. enumerable: true,
  17572. configurable: true
  17573. });
  17574. Object.defineProperty(Scene.prototype, "selectionOctree", {
  17575. get: function () {
  17576. return this._selectionOctree;
  17577. },
  17578. enumerable: true,
  17579. configurable: true
  17580. });
  17581. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  17582. /**
  17583. * The mesh that is currently under the pointer.
  17584. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  17585. */
  17586. get: function () {
  17587. return this._pointerOverMesh;
  17588. },
  17589. enumerable: true,
  17590. configurable: true
  17591. });
  17592. Object.defineProperty(Scene.prototype, "pointerX", {
  17593. /**
  17594. * Current on-screen X position of the pointer
  17595. * @return {number} X position of the pointer
  17596. */
  17597. get: function () {
  17598. return this._pointerX;
  17599. },
  17600. enumerable: true,
  17601. configurable: true
  17602. });
  17603. Object.defineProperty(Scene.prototype, "pointerY", {
  17604. /**
  17605. * Current on-screen Y position of the pointer
  17606. * @return {number} Y position of the pointer
  17607. */
  17608. get: function () {
  17609. return this._pointerY;
  17610. },
  17611. enumerable: true,
  17612. configurable: true
  17613. });
  17614. Scene.prototype.getCachedMaterial = function () {
  17615. return this._cachedMaterial;
  17616. };
  17617. Scene.prototype.getCachedEffect = function () {
  17618. return this._cachedEffect;
  17619. };
  17620. Scene.prototype.getCachedVisibility = function () {
  17621. return this._cachedVisibility;
  17622. };
  17623. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  17624. if (visibility === void 0) { visibility = 1; }
  17625. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  17626. };
  17627. Scene.prototype.getBoundingBoxRenderer = function () {
  17628. if (!this._boundingBoxRenderer) {
  17629. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  17630. }
  17631. return this._boundingBoxRenderer;
  17632. };
  17633. Scene.prototype.getOutlineRenderer = function () {
  17634. return this._outlineRenderer;
  17635. };
  17636. Scene.prototype.getEngine = function () {
  17637. return this._engine;
  17638. };
  17639. Scene.prototype.getTotalVertices = function () {
  17640. return this._totalVertices.current;
  17641. };
  17642. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  17643. get: function () {
  17644. return this._totalVertices;
  17645. },
  17646. enumerable: true,
  17647. configurable: true
  17648. });
  17649. Scene.prototype.getActiveIndices = function () {
  17650. return this._activeIndices.current;
  17651. };
  17652. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  17653. get: function () {
  17654. return this._activeIndices;
  17655. },
  17656. enumerable: true,
  17657. configurable: true
  17658. });
  17659. Scene.prototype.getActiveParticles = function () {
  17660. return this._activeParticles.current;
  17661. };
  17662. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  17663. get: function () {
  17664. return this._activeParticles;
  17665. },
  17666. enumerable: true,
  17667. configurable: true
  17668. });
  17669. Scene.prototype.getActiveBones = function () {
  17670. return this._activeBones.current;
  17671. };
  17672. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  17673. get: function () {
  17674. return this._activeBones;
  17675. },
  17676. enumerable: true,
  17677. configurable: true
  17678. });
  17679. // Stats
  17680. Scene.prototype.getInterFramePerfCounter = function () {
  17681. return this._interFrameDuration.current;
  17682. };
  17683. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  17684. get: function () {
  17685. return this._interFrameDuration;
  17686. },
  17687. enumerable: true,
  17688. configurable: true
  17689. });
  17690. Scene.prototype.getLastFrameDuration = function () {
  17691. return this._lastFrameDuration.current;
  17692. };
  17693. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  17694. get: function () {
  17695. return this._lastFrameDuration;
  17696. },
  17697. enumerable: true,
  17698. configurable: true
  17699. });
  17700. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  17701. return this._evaluateActiveMeshesDuration.current;
  17702. };
  17703. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  17704. get: function () {
  17705. return this._evaluateActiveMeshesDuration;
  17706. },
  17707. enumerable: true,
  17708. configurable: true
  17709. });
  17710. Scene.prototype.getActiveMeshes = function () {
  17711. return this._activeMeshes;
  17712. };
  17713. Scene.prototype.getRenderTargetsDuration = function () {
  17714. return this._renderTargetsDuration.current;
  17715. };
  17716. Scene.prototype.getRenderDuration = function () {
  17717. return this._renderDuration.current;
  17718. };
  17719. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  17720. get: function () {
  17721. return this._renderDuration;
  17722. },
  17723. enumerable: true,
  17724. configurable: true
  17725. });
  17726. Scene.prototype.getParticlesDuration = function () {
  17727. return this._particlesDuration.current;
  17728. };
  17729. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  17730. get: function () {
  17731. return this._particlesDuration;
  17732. },
  17733. enumerable: true,
  17734. configurable: true
  17735. });
  17736. Scene.prototype.getSpritesDuration = function () {
  17737. return this._spritesDuration.current;
  17738. };
  17739. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  17740. get: function () {
  17741. return this._spritesDuration;
  17742. },
  17743. enumerable: true,
  17744. configurable: true
  17745. });
  17746. Scene.prototype.getAnimationRatio = function () {
  17747. return this._animationRatio;
  17748. };
  17749. Scene.prototype.getRenderId = function () {
  17750. return this._renderId;
  17751. };
  17752. Scene.prototype.incrementRenderId = function () {
  17753. this._renderId++;
  17754. };
  17755. Scene.prototype._updatePointerPosition = function (evt) {
  17756. var canvasRect = this._engine.getRenderingCanvasClientRect();
  17757. if (!canvasRect) {
  17758. return;
  17759. }
  17760. this._pointerX = evt.clientX - canvasRect.left;
  17761. this._pointerY = evt.clientY - canvasRect.top;
  17762. this._unTranslatedPointerX = this._pointerX;
  17763. this._unTranslatedPointerY = this._pointerY;
  17764. };
  17765. Scene.prototype._createUbo = function () {
  17766. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  17767. this._sceneUbo.addUniform("viewProjection", 16);
  17768. this._sceneUbo.addUniform("view", 16);
  17769. };
  17770. Scene.prototype._createAlternateUbo = function () {
  17771. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  17772. this._alternateSceneUbo.addUniform("viewProjection", 16);
  17773. this._alternateSceneUbo.addUniform("view", 16);
  17774. };
  17775. // Pointers handling
  17776. /**
  17777. * Use this method to simulate a pointer move on a mesh
  17778. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  17779. */
  17780. Scene.prototype.simulatePointerMove = function (pickResult) {
  17781. var evt = new PointerEvent("pointermove");
  17782. return this._processPointerMove(pickResult, evt);
  17783. };
  17784. Scene.prototype._processPointerMove = function (pickResult, evt) {
  17785. var canvas = this._engine.getRenderingCanvas();
  17786. if (!canvas) {
  17787. return this;
  17788. }
  17789. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17790. this.setPointerOverSprite(null);
  17791. this.setPointerOverMesh(pickResult.pickedMesh);
  17792. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  17793. if (this._pointerOverMesh.actionManager.hoverCursor) {
  17794. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  17795. }
  17796. else {
  17797. canvas.style.cursor = this.hoverCursor;
  17798. }
  17799. }
  17800. else {
  17801. canvas.style.cursor = this.defaultCursor;
  17802. }
  17803. }
  17804. else {
  17805. this.setPointerOverMesh(null);
  17806. // Sprites
  17807. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  17808. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17809. this.setPointerOverSprite(pickResult.pickedSprite);
  17810. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  17811. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  17812. }
  17813. else {
  17814. canvas.style.cursor = this.hoverCursor;
  17815. }
  17816. }
  17817. else {
  17818. this.setPointerOverSprite(null);
  17819. // Restore pointer
  17820. canvas.style.cursor = this.defaultCursor;
  17821. }
  17822. }
  17823. if (pickResult) {
  17824. if (this.onPointerMove) {
  17825. this.onPointerMove(evt, pickResult);
  17826. }
  17827. if (this.onPointerObservable.hasObservers()) {
  17828. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  17829. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17830. this.onPointerObservable.notifyObservers(pi, type);
  17831. }
  17832. }
  17833. return this;
  17834. };
  17835. /**
  17836. * Use this method to simulate a pointer down on a mesh
  17837. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  17838. */
  17839. Scene.prototype.simulatePointerDown = function (pickResult) {
  17840. var evt = new PointerEvent("pointerdown");
  17841. return this._processPointerDown(pickResult, evt);
  17842. };
  17843. Scene.prototype._processPointerDown = function (pickResult, evt) {
  17844. var _this = this;
  17845. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17846. this._pickedDownMesh = pickResult.pickedMesh;
  17847. var actionManager = pickResult.pickedMesh.actionManager;
  17848. if (actionManager) {
  17849. if (actionManager.hasPickTriggers) {
  17850. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17851. switch (evt.button) {
  17852. case 0:
  17853. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17854. break;
  17855. case 1:
  17856. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17857. break;
  17858. case 2:
  17859. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17860. break;
  17861. }
  17862. }
  17863. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  17864. window.setTimeout(function () {
  17865. 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);
  17866. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  17867. if (_this._totalPointersPressed !== 0 &&
  17868. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  17869. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  17870. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  17871. _this._startingPointerTime = 0;
  17872. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17873. }
  17874. }
  17875. }, Scene.LongPressDelay);
  17876. }
  17877. }
  17878. }
  17879. if (pickResult) {
  17880. if (this.onPointerDown) {
  17881. this.onPointerDown(evt, pickResult);
  17882. }
  17883. if (this.onPointerObservable.hasObservers()) {
  17884. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  17885. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17886. this.onPointerObservable.notifyObservers(pi, type);
  17887. }
  17888. }
  17889. return this;
  17890. };
  17891. /**
  17892. * Use this method to simulate a pointer up on a mesh
  17893. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  17894. */
  17895. Scene.prototype.simulatePointerUp = function (pickResult) {
  17896. var evt = new PointerEvent("pointerup");
  17897. var clickInfo = new ClickInfo();
  17898. clickInfo.singleClick = true;
  17899. return this._processPointerUp(pickResult, evt, clickInfo);
  17900. };
  17901. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  17902. if (pickResult && pickResult && pickResult.pickedMesh) {
  17903. this._pickedUpMesh = pickResult.pickedMesh;
  17904. if (this._pickedDownMesh === this._pickedUpMesh) {
  17905. if (this.onPointerPick) {
  17906. this.onPointerPick(evt, pickResult);
  17907. }
  17908. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  17909. var type = BABYLON.PointerEventTypes.POINTERPICK;
  17910. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17911. this.onPointerObservable.notifyObservers(pi, type);
  17912. }
  17913. }
  17914. if (pickResult.pickedMesh.actionManager) {
  17915. if (clickInfo.ignore) {
  17916. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17917. }
  17918. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  17919. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17920. }
  17921. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17922. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17923. }
  17924. }
  17925. }
  17926. if (this._pickedDownMesh &&
  17927. this._pickedDownMesh.actionManager &&
  17928. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  17929. this._pickedDownMesh !== this._pickedUpMesh) {
  17930. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  17931. }
  17932. if (this.onPointerUp) {
  17933. this.onPointerUp(evt, pickResult);
  17934. }
  17935. if (this.onPointerObservable.hasObservers()) {
  17936. if (!clickInfo.ignore) {
  17937. if (!clickInfo.hasSwiped) {
  17938. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  17939. var type = BABYLON.PointerEventTypes.POINTERTAP;
  17940. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17941. this.onPointerObservable.notifyObservers(pi, type);
  17942. }
  17943. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  17944. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  17945. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17946. this.onPointerObservable.notifyObservers(pi, type);
  17947. }
  17948. }
  17949. }
  17950. else {
  17951. var type = BABYLON.PointerEventTypes.POINTERUP;
  17952. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17953. this.onPointerObservable.notifyObservers(pi, type);
  17954. }
  17955. }
  17956. return this;
  17957. };
  17958. /**
  17959. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  17960. * @param attachUp defines if you want to attach events to pointerup
  17961. * @param attachDown defines if you want to attach events to pointerdown
  17962. * @param attachMove defines if you want to attach events to pointermove
  17963. */
  17964. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  17965. var _this = this;
  17966. if (attachUp === void 0) { attachUp = true; }
  17967. if (attachDown === void 0) { attachDown = true; }
  17968. if (attachMove === void 0) { attachMove = true; }
  17969. this._initActionManager = function (act, clickInfo) {
  17970. if (!_this._meshPickProceed) {
  17971. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17972. _this._currentPickResult = pickResult;
  17973. if (pickResult) {
  17974. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  17975. }
  17976. _this._meshPickProceed = true;
  17977. }
  17978. return act;
  17979. };
  17980. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  17981. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  17982. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  17983. btn !== _this._previousButtonPressed) {
  17984. _this._doubleClickOccured = false;
  17985. clickInfo.singleClick = true;
  17986. clickInfo.ignore = false;
  17987. cb(clickInfo, _this._currentPickResult);
  17988. }
  17989. };
  17990. this._initClickEvent = function (obs1, obs2, evt, cb) {
  17991. var clickInfo = new ClickInfo();
  17992. _this._currentPickResult = null;
  17993. var act = null;
  17994. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  17995. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  17996. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17997. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  17998. act = _this._initActionManager(act, clickInfo);
  17999. if (act)
  18000. checkPicking = act.hasPickTriggers;
  18001. }
  18002. if (checkPicking) {
  18003. var btn = evt.button;
  18004. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  18005. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  18006. if (!clickInfo.hasSwiped) {
  18007. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  18008. if (!checkSingleClickImmediately) {
  18009. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  18010. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18011. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18012. act = _this._initActionManager(act, clickInfo);
  18013. if (act)
  18014. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  18015. }
  18016. }
  18017. if (checkSingleClickImmediately) {
  18018. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  18019. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  18020. btn !== _this._previousButtonPressed) {
  18021. clickInfo.singleClick = true;
  18022. cb(clickInfo, _this._currentPickResult);
  18023. }
  18024. }
  18025. else {
  18026. // wait that no double click has been raised during the double click delay
  18027. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18028. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  18029. }
  18030. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  18031. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18032. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18033. act = _this._initActionManager(act, clickInfo);
  18034. if (act)
  18035. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  18036. }
  18037. if (checkDoubleClick) {
  18038. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  18039. if (btn === _this._previousButtonPressed &&
  18040. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  18041. !_this._doubleClickOccured) {
  18042. // pointer has not moved for 2 clicks, it's a double click
  18043. if (!clickInfo.hasSwiped &&
  18044. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  18045. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  18046. _this._previousStartingPointerTime = 0;
  18047. _this._doubleClickOccured = true;
  18048. clickInfo.doubleClick = true;
  18049. clickInfo.ignore = false;
  18050. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  18051. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  18052. }
  18053. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18054. cb(clickInfo, _this._currentPickResult);
  18055. }
  18056. else {
  18057. _this._doubleClickOccured = false;
  18058. _this._previousStartingPointerTime = _this._startingPointerTime;
  18059. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  18060. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  18061. _this._previousButtonPressed = btn;
  18062. _this._previousHasSwiped = clickInfo.hasSwiped;
  18063. if (Scene.ExclusiveDoubleClickMode) {
  18064. if (_this._previousDelayedSimpleClickTimeout) {
  18065. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  18066. }
  18067. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18068. cb(clickInfo, _this._previousPickResult);
  18069. }
  18070. else {
  18071. cb(clickInfo, _this._currentPickResult);
  18072. }
  18073. }
  18074. }
  18075. else {
  18076. _this._doubleClickOccured = false;
  18077. _this._previousStartingPointerTime = _this._startingPointerTime;
  18078. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  18079. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  18080. _this._previousButtonPressed = btn;
  18081. _this._previousHasSwiped = clickInfo.hasSwiped;
  18082. }
  18083. }
  18084. }
  18085. }
  18086. clickInfo.ignore = true;
  18087. cb(clickInfo, _this._currentPickResult);
  18088. };
  18089. this._spritePredicate = function (sprite) {
  18090. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  18091. };
  18092. this._onPointerMove = function (evt) {
  18093. _this._updatePointerPosition(evt);
  18094. // PreObservable support
  18095. if (_this.onPrePointerObservable.hasObservers()) {
  18096. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  18097. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18098. _this.onPrePointerObservable.notifyObservers(pi, type);
  18099. if (pi.skipOnPointerObservable) {
  18100. return;
  18101. }
  18102. }
  18103. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18104. return;
  18105. }
  18106. if (!_this.pointerMovePredicate) {
  18107. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  18108. }
  18109. // Meshes
  18110. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  18111. _this._processPointerMove(pickResult, evt);
  18112. };
  18113. this._onPointerDown = function (evt) {
  18114. _this._totalPointersPressed++;
  18115. _this._pickedDownMesh = null;
  18116. _this._meshPickProceed = false;
  18117. _this._updatePointerPosition(evt);
  18118. if (_this.preventDefaultOnPointerDown && canvas) {
  18119. evt.preventDefault();
  18120. canvas.focus();
  18121. }
  18122. // PreObservable support
  18123. if (_this.onPrePointerObservable.hasObservers()) {
  18124. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  18125. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18126. _this.onPrePointerObservable.notifyObservers(pi, type);
  18127. if (pi.skipOnPointerObservable) {
  18128. return;
  18129. }
  18130. }
  18131. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18132. return;
  18133. }
  18134. _this._startingPointerPosition.x = _this._pointerX;
  18135. _this._startingPointerPosition.y = _this._pointerY;
  18136. _this._startingPointerTime = new Date().getTime();
  18137. if (!_this.pointerDownPredicate) {
  18138. _this.pointerDownPredicate = function (mesh) {
  18139. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  18140. };
  18141. }
  18142. // Meshes
  18143. _this._pickedDownMesh = null;
  18144. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  18145. _this._processPointerDown(pickResult, evt);
  18146. // Sprites
  18147. _this._pickedDownSprite = null;
  18148. if (_this.spriteManagers.length > 0) {
  18149. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  18150. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  18151. if (pickResult.pickedSprite.actionManager) {
  18152. _this._pickedDownSprite = pickResult.pickedSprite;
  18153. switch (evt.button) {
  18154. case 0:
  18155. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18156. break;
  18157. case 1:
  18158. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18159. break;
  18160. case 2:
  18161. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18162. break;
  18163. }
  18164. if (pickResult.pickedSprite.actionManager) {
  18165. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18166. }
  18167. }
  18168. }
  18169. }
  18170. };
  18171. this._onPointerUp = function (evt) {
  18172. if (_this._totalPointersPressed === 0) {
  18173. return; // So we need to test it the pointer down was pressed before.
  18174. }
  18175. _this._totalPointersPressed--;
  18176. _this._pickedUpMesh = null;
  18177. _this._meshPickProceed = false;
  18178. _this._updatePointerPosition(evt);
  18179. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  18180. // PreObservable support
  18181. if (_this.onPrePointerObservable.hasObservers()) {
  18182. if (!clickInfo.ignore) {
  18183. if (!clickInfo.hasSwiped) {
  18184. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  18185. var type = BABYLON.PointerEventTypes.POINTERTAP;
  18186. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18187. _this.onPrePointerObservable.notifyObservers(pi, type);
  18188. if (pi.skipOnPointerObservable) {
  18189. return;
  18190. }
  18191. }
  18192. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  18193. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  18194. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18195. _this.onPrePointerObservable.notifyObservers(pi, type);
  18196. if (pi.skipOnPointerObservable) {
  18197. return;
  18198. }
  18199. }
  18200. }
  18201. }
  18202. else {
  18203. var type = BABYLON.PointerEventTypes.POINTERUP;
  18204. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18205. _this.onPrePointerObservable.notifyObservers(pi, type);
  18206. if (pi.skipOnPointerObservable) {
  18207. return;
  18208. }
  18209. }
  18210. }
  18211. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18212. return;
  18213. }
  18214. if (!_this.pointerUpPredicate) {
  18215. _this.pointerUpPredicate = function (mesh) {
  18216. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  18217. };
  18218. }
  18219. // Meshes
  18220. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  18221. _this._initActionManager(null, clickInfo);
  18222. }
  18223. if (!pickResult) {
  18224. pickResult = _this._currentPickResult;
  18225. }
  18226. _this._processPointerUp(pickResult, evt, clickInfo);
  18227. // Sprites
  18228. if (_this.spriteManagers.length > 0) {
  18229. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  18230. if (spritePickResult) {
  18231. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  18232. if (spritePickResult.pickedSprite.actionManager) {
  18233. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  18234. if (spritePickResult.pickedSprite.actionManager) {
  18235. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  18236. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  18237. }
  18238. }
  18239. }
  18240. }
  18241. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  18242. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  18243. }
  18244. }
  18245. }
  18246. _this._previousPickResult = _this._currentPickResult;
  18247. });
  18248. };
  18249. this._onKeyDown = function (evt) {
  18250. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  18251. if (_this.onPreKeyboardObservable.hasObservers()) {
  18252. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  18253. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  18254. if (pi.skipOnPointerObservable) {
  18255. return;
  18256. }
  18257. }
  18258. if (_this.onKeyboardObservable.hasObservers()) {
  18259. var pi = new BABYLON.KeyboardInfo(type, evt);
  18260. _this.onKeyboardObservable.notifyObservers(pi, type);
  18261. }
  18262. if (_this.actionManager) {
  18263. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  18264. }
  18265. };
  18266. this._onKeyUp = function (evt) {
  18267. var type = BABYLON.KeyboardEventTypes.KEYUP;
  18268. if (_this.onPreKeyboardObservable.hasObservers()) {
  18269. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  18270. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  18271. if (pi.skipOnPointerObservable) {
  18272. return;
  18273. }
  18274. }
  18275. if (_this.onKeyboardObservable.hasObservers()) {
  18276. var pi = new BABYLON.KeyboardInfo(type, evt);
  18277. _this.onKeyboardObservable.notifyObservers(pi, type);
  18278. }
  18279. if (_this.actionManager) {
  18280. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  18281. }
  18282. };
  18283. var engine = this.getEngine();
  18284. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  18285. if (!canvas) {
  18286. return;
  18287. }
  18288. canvas.addEventListener("keydown", _this._onKeyDown, false);
  18289. canvas.addEventListener("keyup", _this._onKeyUp, false);
  18290. });
  18291. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  18292. if (!canvas) {
  18293. return;
  18294. }
  18295. canvas.removeEventListener("keydown", _this._onKeyDown);
  18296. canvas.removeEventListener("keyup", _this._onKeyUp);
  18297. });
  18298. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  18299. var canvas = this._engine.getRenderingCanvas();
  18300. if (!canvas) {
  18301. return;
  18302. }
  18303. if (attachMove) {
  18304. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  18305. // Wheel
  18306. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  18307. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  18308. }
  18309. if (attachDown) {
  18310. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  18311. }
  18312. if (attachUp) {
  18313. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  18314. }
  18315. canvas.tabIndex = 1;
  18316. };
  18317. Scene.prototype.detachControl = function () {
  18318. var engine = this.getEngine();
  18319. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  18320. var canvas = engine.getRenderingCanvas();
  18321. if (!canvas) {
  18322. return;
  18323. }
  18324. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  18325. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  18326. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  18327. if (this._onCanvasBlurObserver) {
  18328. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  18329. }
  18330. if (this._onCanvasFocusObserver) {
  18331. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  18332. }
  18333. // Wheel
  18334. canvas.removeEventListener('mousewheel', this._onPointerMove);
  18335. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  18336. // Keyboard
  18337. canvas.removeEventListener("keydown", this._onKeyDown);
  18338. canvas.removeEventListener("keyup", this._onKeyUp);
  18339. // Observables
  18340. this.onKeyboardObservable.clear();
  18341. this.onPreKeyboardObservable.clear();
  18342. this.onPointerObservable.clear();
  18343. this.onPrePointerObservable.clear();
  18344. };
  18345. // Ready
  18346. Scene.prototype.isReady = function () {
  18347. if (this._pendingData.length > 0) {
  18348. return false;
  18349. }
  18350. var index;
  18351. // Geometries
  18352. for (index = 0; index < this._geometries.length; index++) {
  18353. var geometry = this._geometries[index];
  18354. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18355. return false;
  18356. }
  18357. }
  18358. // Meshes
  18359. for (index = 0; index < this.meshes.length; index++) {
  18360. var mesh = this.meshes[index];
  18361. if (!mesh.isEnabled()) {
  18362. continue;
  18363. }
  18364. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  18365. continue;
  18366. }
  18367. if (!mesh.isReady()) {
  18368. return false;
  18369. }
  18370. var mat = mesh.material;
  18371. if (mat) {
  18372. if (!mat.isReady(mesh)) {
  18373. return false;
  18374. }
  18375. }
  18376. }
  18377. return true;
  18378. };
  18379. Scene.prototype.resetCachedMaterial = function () {
  18380. this._cachedMaterial = null;
  18381. this._cachedEffect = null;
  18382. this._cachedVisibility = null;
  18383. };
  18384. Scene.prototype.registerBeforeRender = function (func) {
  18385. this.onBeforeRenderObservable.add(func);
  18386. };
  18387. Scene.prototype.unregisterBeforeRender = function (func) {
  18388. this.onBeforeRenderObservable.removeCallback(func);
  18389. };
  18390. Scene.prototype.registerAfterRender = function (func) {
  18391. this.onAfterRenderObservable.add(func);
  18392. };
  18393. Scene.prototype.unregisterAfterRender = function (func) {
  18394. this.onAfterRenderObservable.removeCallback(func);
  18395. };
  18396. Scene.prototype._addPendingData = function (data) {
  18397. this._pendingData.push(data);
  18398. };
  18399. Scene.prototype._removePendingData = function (data) {
  18400. var index = this._pendingData.indexOf(data);
  18401. if (index !== -1) {
  18402. this._pendingData.splice(index, 1);
  18403. }
  18404. };
  18405. Scene.prototype.getWaitingItemsCount = function () {
  18406. return this._pendingData.length;
  18407. };
  18408. /**
  18409. * Registers a function to be executed when the scene is ready.
  18410. * @param {Function} func - the function to be executed.
  18411. */
  18412. Scene.prototype.executeWhenReady = function (func) {
  18413. var _this = this;
  18414. this.onReadyObservable.add(func);
  18415. if (this._executeWhenReadyTimeoutId !== -1) {
  18416. return;
  18417. }
  18418. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18419. _this._checkIsReady();
  18420. }, 150);
  18421. };
  18422. Scene.prototype._checkIsReady = function () {
  18423. var _this = this;
  18424. if (this.isReady()) {
  18425. this.onReadyObservable.notifyObservers(this);
  18426. this.onReadyObservable.clear();
  18427. this._executeWhenReadyTimeoutId = -1;
  18428. return;
  18429. }
  18430. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18431. _this._checkIsReady();
  18432. }, 150);
  18433. };
  18434. // Animations
  18435. /**
  18436. * Will start the animation sequence of a given target
  18437. * @param target - the target
  18438. * @param {number} from - from which frame should animation start
  18439. * @param {number} to - till which frame should animation run.
  18440. * @param {boolean} [loop] - should the animation loop
  18441. * @param {number} [speedRatio] - the speed in which to run the animation
  18442. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  18443. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  18444. * Returns {BABYLON.Animatable} the animatable object created for this animation
  18445. * See BABYLON.Animatable
  18446. */
  18447. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  18448. if (speedRatio === void 0) { speedRatio = 1.0; }
  18449. if (from > to && speedRatio > 0) {
  18450. speedRatio *= -1;
  18451. }
  18452. this.stopAnimation(target);
  18453. if (!animatable) {
  18454. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  18455. }
  18456. // Local animations
  18457. if (target.animations) {
  18458. animatable.appendAnimations(target, target.animations);
  18459. }
  18460. // Children animations
  18461. if (target.getAnimatables) {
  18462. var animatables = target.getAnimatables();
  18463. for (var index = 0; index < animatables.length; index++) {
  18464. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  18465. }
  18466. }
  18467. animatable.reset();
  18468. return animatable;
  18469. };
  18470. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  18471. if (speedRatio === undefined) {
  18472. speedRatio = 1.0;
  18473. }
  18474. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  18475. return animatable;
  18476. };
  18477. Scene.prototype.getAnimatableByTarget = function (target) {
  18478. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18479. if (this._activeAnimatables[index].target === target) {
  18480. return this._activeAnimatables[index];
  18481. }
  18482. }
  18483. return null;
  18484. };
  18485. Object.defineProperty(Scene.prototype, "Animatables", {
  18486. get: function () {
  18487. return this._activeAnimatables;
  18488. },
  18489. enumerable: true,
  18490. configurable: true
  18491. });
  18492. /**
  18493. * Will stop the animation of the given target
  18494. * @param target - the target
  18495. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  18496. * @see beginAnimation
  18497. */
  18498. Scene.prototype.stopAnimation = function (target, animationName) {
  18499. var animatable = this.getAnimatableByTarget(target);
  18500. if (animatable) {
  18501. animatable.stop(animationName);
  18502. }
  18503. };
  18504. Scene.prototype._animate = function () {
  18505. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  18506. return;
  18507. }
  18508. // Getting time
  18509. var now = BABYLON.Tools.Now;
  18510. if (!this._animationTimeLast) {
  18511. if (this._pendingData.length > 0) {
  18512. return;
  18513. }
  18514. this._animationTimeLast = now;
  18515. }
  18516. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  18517. this._animationTime += deltaTime;
  18518. this._animationTimeLast = now;
  18519. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18520. this._activeAnimatables[index]._animate(this._animationTime);
  18521. }
  18522. };
  18523. // Matrix
  18524. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  18525. this._useAlternateCameraConfiguration = active;
  18526. };
  18527. Scene.prototype.getViewMatrix = function () {
  18528. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  18529. };
  18530. Scene.prototype.getProjectionMatrix = function () {
  18531. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  18532. };
  18533. Scene.prototype.getTransformMatrix = function () {
  18534. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  18535. };
  18536. Scene.prototype.setTransformMatrix = function (view, projection) {
  18537. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  18538. return;
  18539. }
  18540. this._viewUpdateFlag = view.updateFlag;
  18541. this._projectionUpdateFlag = projection.updateFlag;
  18542. this._viewMatrix = view;
  18543. this._projectionMatrix = projection;
  18544. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18545. // Update frustum
  18546. if (!this._frustumPlanes) {
  18547. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18548. }
  18549. else {
  18550. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18551. }
  18552. if (this.activeCamera && this.activeCamera._alternateCamera) {
  18553. var otherCamera = this.activeCamera._alternateCamera;
  18554. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  18555. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  18556. }
  18557. if (this._sceneUbo.useUbo) {
  18558. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  18559. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  18560. this._sceneUbo.update();
  18561. }
  18562. };
  18563. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  18564. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  18565. return;
  18566. }
  18567. this._alternateViewUpdateFlag = view.updateFlag;
  18568. this._alternateProjectionUpdateFlag = projection.updateFlag;
  18569. this._alternateViewMatrix = view;
  18570. this._alternateProjectionMatrix = projection;
  18571. if (!this._alternateTransformMatrix) {
  18572. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  18573. }
  18574. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  18575. if (!this._alternateSceneUbo) {
  18576. this._createAlternateUbo();
  18577. }
  18578. if (this._alternateSceneUbo.useUbo) {
  18579. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  18580. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  18581. this._alternateSceneUbo.update();
  18582. }
  18583. };
  18584. Scene.prototype.getSceneUniformBuffer = function () {
  18585. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  18586. };
  18587. // Methods
  18588. Scene.prototype.getUniqueId = function () {
  18589. var result = Scene._uniqueIdCounter;
  18590. Scene._uniqueIdCounter++;
  18591. return result;
  18592. };
  18593. Scene.prototype.addMesh = function (newMesh) {
  18594. this.meshes.push(newMesh);
  18595. //notify the collision coordinator
  18596. if (this.collisionCoordinator) {
  18597. this.collisionCoordinator.onMeshAdded(newMesh);
  18598. }
  18599. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  18600. };
  18601. Scene.prototype.removeMesh = function (toRemove) {
  18602. var index = this.meshes.indexOf(toRemove);
  18603. if (index !== -1) {
  18604. // Remove from the scene if mesh found
  18605. this.meshes.splice(index, 1);
  18606. }
  18607. //notify the collision coordinator
  18608. if (this.collisionCoordinator) {
  18609. this.collisionCoordinator.onMeshRemoved(toRemove);
  18610. }
  18611. this.onMeshRemovedObservable.notifyObservers(toRemove);
  18612. return index;
  18613. };
  18614. Scene.prototype.removeSkeleton = function (toRemove) {
  18615. var index = this.skeletons.indexOf(toRemove);
  18616. if (index !== -1) {
  18617. // Remove from the scene if found
  18618. this.skeletons.splice(index, 1);
  18619. }
  18620. return index;
  18621. };
  18622. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  18623. var index = this.morphTargetManagers.indexOf(toRemove);
  18624. if (index !== -1) {
  18625. // Remove from the scene if found
  18626. this.morphTargetManagers.splice(index, 1);
  18627. }
  18628. return index;
  18629. };
  18630. Scene.prototype.removeLight = function (toRemove) {
  18631. var index = this.lights.indexOf(toRemove);
  18632. if (index !== -1) {
  18633. // Remove from the scene if mesh found
  18634. this.lights.splice(index, 1);
  18635. this.sortLightsByPriority();
  18636. }
  18637. this.onLightRemovedObservable.notifyObservers(toRemove);
  18638. return index;
  18639. };
  18640. Scene.prototype.removeCamera = function (toRemove) {
  18641. var index = this.cameras.indexOf(toRemove);
  18642. if (index !== -1) {
  18643. // Remove from the scene if mesh found
  18644. this.cameras.splice(index, 1);
  18645. }
  18646. // Remove from activeCameras
  18647. var index2 = this.activeCameras.indexOf(toRemove);
  18648. if (index2 !== -1) {
  18649. // Remove from the scene if mesh found
  18650. this.activeCameras.splice(index2, 1);
  18651. }
  18652. // Reset the activeCamera
  18653. if (this.activeCamera === toRemove) {
  18654. if (this.cameras.length > 0) {
  18655. this.activeCamera = this.cameras[0];
  18656. }
  18657. else {
  18658. this.activeCamera = null;
  18659. }
  18660. }
  18661. this.onCameraRemovedObservable.notifyObservers(toRemove);
  18662. return index;
  18663. };
  18664. Scene.prototype.addLight = function (newLight) {
  18665. this.lights.push(newLight);
  18666. this.sortLightsByPriority();
  18667. this.onNewLightAddedObservable.notifyObservers(newLight);
  18668. };
  18669. Scene.prototype.sortLightsByPriority = function () {
  18670. if (this.requireLightSorting) {
  18671. this.lights.sort(BABYLON.Light.compareLightsPriority);
  18672. }
  18673. };
  18674. Scene.prototype.addCamera = function (newCamera) {
  18675. this.cameras.push(newCamera);
  18676. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  18677. };
  18678. /**
  18679. * Switch active camera
  18680. * @param {Camera} newCamera - new active camera
  18681. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  18682. */
  18683. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  18684. if (attachControl === void 0) { attachControl = true; }
  18685. var canvas = this._engine.getRenderingCanvas();
  18686. if (!canvas) {
  18687. return;
  18688. }
  18689. if (this.activeCamera) {
  18690. this.activeCamera.detachControl(canvas);
  18691. }
  18692. this.activeCamera = newCamera;
  18693. if (attachControl) {
  18694. newCamera.attachControl(canvas);
  18695. }
  18696. };
  18697. /**
  18698. * sets the active camera of the scene using its ID
  18699. * @param {string} id - the camera's ID
  18700. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  18701. * @see activeCamera
  18702. */
  18703. Scene.prototype.setActiveCameraByID = function (id) {
  18704. var camera = this.getCameraByID(id);
  18705. if (camera) {
  18706. this.activeCamera = camera;
  18707. return camera;
  18708. }
  18709. return null;
  18710. };
  18711. /**
  18712. * sets the active camera of the scene using its name
  18713. * @param {string} name - the camera's name
  18714. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  18715. * @see activeCamera
  18716. */
  18717. Scene.prototype.setActiveCameraByName = function (name) {
  18718. var camera = this.getCameraByName(name);
  18719. if (camera) {
  18720. this.activeCamera = camera;
  18721. return camera;
  18722. }
  18723. return null;
  18724. };
  18725. /**
  18726. * get a material using its id
  18727. * @param {string} the material's ID
  18728. * @return {BABYLON.Material|null} the material or null if none found.
  18729. */
  18730. Scene.prototype.getMaterialByID = function (id) {
  18731. for (var index = 0; index < this.materials.length; index++) {
  18732. if (this.materials[index].id === id) {
  18733. return this.materials[index];
  18734. }
  18735. }
  18736. return null;
  18737. };
  18738. /**
  18739. * get a material using its name
  18740. * @param {string} the material's name
  18741. * @return {BABYLON.Material|null} the material or null if none found.
  18742. */
  18743. Scene.prototype.getMaterialByName = function (name) {
  18744. for (var index = 0; index < this.materials.length; index++) {
  18745. if (this.materials[index].name === name) {
  18746. return this.materials[index];
  18747. }
  18748. }
  18749. return null;
  18750. };
  18751. Scene.prototype.getLensFlareSystemByName = function (name) {
  18752. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18753. if (this.lensFlareSystems[index].name === name) {
  18754. return this.lensFlareSystems[index];
  18755. }
  18756. }
  18757. return null;
  18758. };
  18759. Scene.prototype.getLensFlareSystemByID = function (id) {
  18760. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18761. if (this.lensFlareSystems[index].id === id) {
  18762. return this.lensFlareSystems[index];
  18763. }
  18764. }
  18765. return null;
  18766. };
  18767. Scene.prototype.getCameraByID = function (id) {
  18768. for (var index = 0; index < this.cameras.length; index++) {
  18769. if (this.cameras[index].id === id) {
  18770. return this.cameras[index];
  18771. }
  18772. }
  18773. return null;
  18774. };
  18775. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  18776. for (var index = 0; index < this.cameras.length; index++) {
  18777. if (this.cameras[index].uniqueId === uniqueId) {
  18778. return this.cameras[index];
  18779. }
  18780. }
  18781. return null;
  18782. };
  18783. /**
  18784. * get a camera using its name
  18785. * @param {string} the camera's name
  18786. * @return {BABYLON.Camera|null} the camera or null if none found.
  18787. */
  18788. Scene.prototype.getCameraByName = function (name) {
  18789. for (var index = 0; index < this.cameras.length; index++) {
  18790. if (this.cameras[index].name === name) {
  18791. return this.cameras[index];
  18792. }
  18793. }
  18794. return null;
  18795. };
  18796. /**
  18797. * get a bone using its id
  18798. * @param {string} the bone's id
  18799. * @return {BABYLON.Bone|null} the bone or null if not found
  18800. */
  18801. Scene.prototype.getBoneByID = function (id) {
  18802. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18803. var skeleton = this.skeletons[skeletonIndex];
  18804. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18805. if (skeleton.bones[boneIndex].id === id) {
  18806. return skeleton.bones[boneIndex];
  18807. }
  18808. }
  18809. }
  18810. return null;
  18811. };
  18812. /**
  18813. * get a bone using its id
  18814. * @param {string} the bone's name
  18815. * @return {BABYLON.Bone|null} the bone or null if not found
  18816. */
  18817. Scene.prototype.getBoneByName = function (name) {
  18818. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18819. var skeleton = this.skeletons[skeletonIndex];
  18820. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18821. if (skeleton.bones[boneIndex].name === name) {
  18822. return skeleton.bones[boneIndex];
  18823. }
  18824. }
  18825. }
  18826. return null;
  18827. };
  18828. /**
  18829. * get a light node using its name
  18830. * @param {string} the light's name
  18831. * @return {BABYLON.Light|null} the light or null if none found.
  18832. */
  18833. Scene.prototype.getLightByName = function (name) {
  18834. for (var index = 0; index < this.lights.length; index++) {
  18835. if (this.lights[index].name === name) {
  18836. return this.lights[index];
  18837. }
  18838. }
  18839. return null;
  18840. };
  18841. /**
  18842. * get a light node using its ID
  18843. * @param {string} the light's id
  18844. * @return {BABYLON.Light|null} the light or null if none found.
  18845. */
  18846. Scene.prototype.getLightByID = function (id) {
  18847. for (var index = 0; index < this.lights.length; index++) {
  18848. if (this.lights[index].id === id) {
  18849. return this.lights[index];
  18850. }
  18851. }
  18852. return null;
  18853. };
  18854. /**
  18855. * get a light node using its scene-generated unique ID
  18856. * @param {number} the light's unique id
  18857. * @return {BABYLON.Light|null} the light or null if none found.
  18858. */
  18859. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  18860. for (var index = 0; index < this.lights.length; index++) {
  18861. if (this.lights[index].uniqueId === uniqueId) {
  18862. return this.lights[index];
  18863. }
  18864. }
  18865. return null;
  18866. };
  18867. /**
  18868. * get a particle system by id
  18869. * @param id {number} the particle system id
  18870. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  18871. */
  18872. Scene.prototype.getParticleSystemByID = function (id) {
  18873. for (var index = 0; index < this.particleSystems.length; index++) {
  18874. if (this.particleSystems[index].id === id) {
  18875. return this.particleSystems[index];
  18876. }
  18877. }
  18878. return null;
  18879. };
  18880. /**
  18881. * get a geometry using its ID
  18882. * @param {string} the geometry's id
  18883. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  18884. */
  18885. Scene.prototype.getGeometryByID = function (id) {
  18886. for (var index = 0; index < this._geometries.length; index++) {
  18887. if (this._geometries[index].id === id) {
  18888. return this._geometries[index];
  18889. }
  18890. }
  18891. return null;
  18892. };
  18893. /**
  18894. * add a new geometry to this scene.
  18895. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  18896. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  18897. * @return {boolean} was the geometry added or not
  18898. */
  18899. Scene.prototype.pushGeometry = function (geometry, force) {
  18900. if (!force && this.getGeometryByID(geometry.id)) {
  18901. return false;
  18902. }
  18903. this._geometries.push(geometry);
  18904. //notify the collision coordinator
  18905. if (this.collisionCoordinator) {
  18906. this.collisionCoordinator.onGeometryAdded(geometry);
  18907. }
  18908. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  18909. return true;
  18910. };
  18911. /**
  18912. * Removes an existing geometry
  18913. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  18914. * @return {boolean} was the geometry removed or not
  18915. */
  18916. Scene.prototype.removeGeometry = function (geometry) {
  18917. var index = this._geometries.indexOf(geometry);
  18918. if (index > -1) {
  18919. this._geometries.splice(index, 1);
  18920. //notify the collision coordinator
  18921. if (this.collisionCoordinator) {
  18922. this.collisionCoordinator.onGeometryDeleted(geometry);
  18923. }
  18924. this.onGeometryRemovedObservable.notifyObservers(geometry);
  18925. return true;
  18926. }
  18927. return false;
  18928. };
  18929. Scene.prototype.getGeometries = function () {
  18930. return this._geometries;
  18931. };
  18932. /**
  18933. * Get the first added mesh found of a given ID
  18934. * @param {string} id - the id to search for
  18935. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18936. */
  18937. Scene.prototype.getMeshByID = function (id) {
  18938. for (var index = 0; index < this.meshes.length; index++) {
  18939. if (this.meshes[index].id === id) {
  18940. return this.meshes[index];
  18941. }
  18942. }
  18943. return null;
  18944. };
  18945. Scene.prototype.getMeshesByID = function (id) {
  18946. return this.meshes.filter(function (m) {
  18947. return m.id === id;
  18948. });
  18949. };
  18950. /**
  18951. * Get a mesh with its auto-generated unique id
  18952. * @param {number} uniqueId - the unique id to search for
  18953. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18954. */
  18955. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  18956. for (var index = 0; index < this.meshes.length; index++) {
  18957. if (this.meshes[index].uniqueId === uniqueId) {
  18958. return this.meshes[index];
  18959. }
  18960. }
  18961. return null;
  18962. };
  18963. /**
  18964. * Get a the last added mesh found of a given ID
  18965. * @param {string} id - the id to search for
  18966. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18967. */
  18968. Scene.prototype.getLastMeshByID = function (id) {
  18969. for (var index = this.meshes.length - 1; index >= 0; index--) {
  18970. if (this.meshes[index].id === id) {
  18971. return this.meshes[index];
  18972. }
  18973. }
  18974. return null;
  18975. };
  18976. /**
  18977. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  18978. * @param {string} id - the id to search for
  18979. * @return {BABYLON.Node|null} the node found or null if not found at all.
  18980. */
  18981. Scene.prototype.getLastEntryByID = function (id) {
  18982. var index;
  18983. for (index = this.meshes.length - 1; index >= 0; index--) {
  18984. if (this.meshes[index].id === id) {
  18985. return this.meshes[index];
  18986. }
  18987. }
  18988. for (index = this.cameras.length - 1; index >= 0; index--) {
  18989. if (this.cameras[index].id === id) {
  18990. return this.cameras[index];
  18991. }
  18992. }
  18993. for (index = this.lights.length - 1; index >= 0; index--) {
  18994. if (this.lights[index].id === id) {
  18995. return this.lights[index];
  18996. }
  18997. }
  18998. return null;
  18999. };
  19000. Scene.prototype.getNodeByID = function (id) {
  19001. var mesh = this.getMeshByID(id);
  19002. if (mesh) {
  19003. return mesh;
  19004. }
  19005. var light = this.getLightByID(id);
  19006. if (light) {
  19007. return light;
  19008. }
  19009. var camera = this.getCameraByID(id);
  19010. if (camera) {
  19011. return camera;
  19012. }
  19013. var bone = this.getBoneByID(id);
  19014. return bone;
  19015. };
  19016. Scene.prototype.getNodeByName = function (name) {
  19017. var mesh = this.getMeshByName(name);
  19018. if (mesh) {
  19019. return mesh;
  19020. }
  19021. var light = this.getLightByName(name);
  19022. if (light) {
  19023. return light;
  19024. }
  19025. var camera = this.getCameraByName(name);
  19026. if (camera) {
  19027. return camera;
  19028. }
  19029. var bone = this.getBoneByName(name);
  19030. return bone;
  19031. };
  19032. Scene.prototype.getMeshByName = function (name) {
  19033. for (var index = 0; index < this.meshes.length; index++) {
  19034. if (this.meshes[index].name === name) {
  19035. return this.meshes[index];
  19036. }
  19037. }
  19038. return null;
  19039. };
  19040. Scene.prototype.getSoundByName = function (name) {
  19041. var index;
  19042. if (BABYLON.AudioEngine) {
  19043. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  19044. if (this.mainSoundTrack.soundCollection[index].name === name) {
  19045. return this.mainSoundTrack.soundCollection[index];
  19046. }
  19047. }
  19048. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  19049. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  19050. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  19051. return this.soundTracks[sdIndex].soundCollection[index];
  19052. }
  19053. }
  19054. }
  19055. }
  19056. return null;
  19057. };
  19058. Scene.prototype.getLastSkeletonByID = function (id) {
  19059. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  19060. if (this.skeletons[index].id === id) {
  19061. return this.skeletons[index];
  19062. }
  19063. }
  19064. return null;
  19065. };
  19066. Scene.prototype.getSkeletonById = function (id) {
  19067. for (var index = 0; index < this.skeletons.length; index++) {
  19068. if (this.skeletons[index].id === id) {
  19069. return this.skeletons[index];
  19070. }
  19071. }
  19072. return null;
  19073. };
  19074. Scene.prototype.getSkeletonByName = function (name) {
  19075. for (var index = 0; index < this.skeletons.length; index++) {
  19076. if (this.skeletons[index].name === name) {
  19077. return this.skeletons[index];
  19078. }
  19079. }
  19080. return null;
  19081. };
  19082. Scene.prototype.getMorphTargetManagerById = function (id) {
  19083. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  19084. if (this.morphTargetManagers[index].uniqueId === id) {
  19085. return this.morphTargetManagers[index];
  19086. }
  19087. }
  19088. return null;
  19089. };
  19090. Scene.prototype.isActiveMesh = function (mesh) {
  19091. return (this._activeMeshes.indexOf(mesh) !== -1);
  19092. };
  19093. /**
  19094. * Return a the first highlight layer of the scene with a given name.
  19095. * @param name The name of the highlight layer to look for.
  19096. * @return The highlight layer if found otherwise null.
  19097. */
  19098. Scene.prototype.getHighlightLayerByName = function (name) {
  19099. for (var index = 0; index < this.highlightLayers.length; index++) {
  19100. if (this.highlightLayers[index].name === name) {
  19101. return this.highlightLayers[index];
  19102. }
  19103. }
  19104. return null;
  19105. };
  19106. Object.defineProperty(Scene.prototype, "uid", {
  19107. /**
  19108. * Return a unique id as a string which can serve as an identifier for the scene
  19109. */
  19110. get: function () {
  19111. if (!this._uid) {
  19112. this._uid = BABYLON.Tools.RandomId();
  19113. }
  19114. return this._uid;
  19115. },
  19116. enumerable: true,
  19117. configurable: true
  19118. });
  19119. /**
  19120. * Add an externaly attached data from its key.
  19121. * This method call will fail and return false, if such key already exists.
  19122. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  19123. * @param key the unique key that identifies the data
  19124. * @param data the data object to associate to the key for this Engine instance
  19125. * @return true if no such key were already present and the data was added successfully, false otherwise
  19126. */
  19127. Scene.prototype.addExternalData = function (key, data) {
  19128. if (!this._externalData) {
  19129. this._externalData = new BABYLON.StringDictionary();
  19130. }
  19131. return this._externalData.add(key, data);
  19132. };
  19133. /**
  19134. * Get an externaly attached data from its key
  19135. * @param key the unique key that identifies the data
  19136. * @return the associated data, if present (can be null), or undefined if not present
  19137. */
  19138. Scene.prototype.getExternalData = function (key) {
  19139. if (!this._externalData) {
  19140. return null;
  19141. }
  19142. return this._externalData.get(key);
  19143. };
  19144. /**
  19145. * Get an externaly attached data from its key, create it using a factory if it's not already present
  19146. * @param key the unique key that identifies the data
  19147. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  19148. * @return the associated data, can be null if the factory returned null.
  19149. */
  19150. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  19151. if (!this._externalData) {
  19152. this._externalData = new BABYLON.StringDictionary();
  19153. }
  19154. return this._externalData.getOrAddWithFactory(key, factory);
  19155. };
  19156. /**
  19157. * Remove an externaly attached data from the Engine instance
  19158. * @param key the unique key that identifies the data
  19159. * @return true if the data was successfully removed, false if it doesn't exist
  19160. */
  19161. Scene.prototype.removeExternalData = function (key) {
  19162. return this._externalData.remove(key);
  19163. };
  19164. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  19165. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  19166. var material = subMesh.getMaterial();
  19167. if (mesh.showSubMeshesBoundingBox) {
  19168. var boundingInfo = subMesh.getBoundingInfo();
  19169. if (boundingInfo) {
  19170. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  19171. }
  19172. }
  19173. if (material) {
  19174. // Render targets
  19175. if (material.getRenderTargetTextures) {
  19176. if (this._processedMaterials.indexOf(material) === -1) {
  19177. this._processedMaterials.push(material);
  19178. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  19179. }
  19180. }
  19181. // Dispatch
  19182. this._activeIndices.addCount(subMesh.indexCount, false);
  19183. this._renderingManager.dispatch(subMesh);
  19184. }
  19185. }
  19186. };
  19187. Scene.prototype._isInIntermediateRendering = function () {
  19188. return this._intermediateRendering;
  19189. };
  19190. /**
  19191. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  19192. */
  19193. Scene.prototype.freezeActiveMeshes = function () {
  19194. this._evaluateActiveMeshes();
  19195. this._activeMeshesFrozen = true;
  19196. return this;
  19197. };
  19198. /**
  19199. * Use this function to restart evaluating active meshes on every frame
  19200. */
  19201. Scene.prototype.unfreezeActiveMeshes = function () {
  19202. this._activeMeshesFrozen = false;
  19203. return this;
  19204. };
  19205. Scene.prototype._evaluateActiveMeshes = function () {
  19206. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  19207. return;
  19208. }
  19209. if (!this.activeCamera) {
  19210. return;
  19211. }
  19212. this.activeCamera._activeMeshes.reset();
  19213. this._activeMeshes.reset();
  19214. this._renderingManager.reset();
  19215. this._processedMaterials.reset();
  19216. this._activeParticleSystems.reset();
  19217. this._activeSkeletons.reset();
  19218. this._softwareSkinnedMeshes.reset();
  19219. if (this._boundingBoxRenderer) {
  19220. this._boundingBoxRenderer.reset();
  19221. }
  19222. // Meshes
  19223. var meshes;
  19224. var len;
  19225. if (this._selectionOctree) {
  19226. var selection = this._selectionOctree.select(this._frustumPlanes);
  19227. meshes = selection.data;
  19228. len = selection.length;
  19229. }
  19230. else {
  19231. len = this.meshes.length;
  19232. meshes = this.meshes;
  19233. }
  19234. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  19235. var mesh = meshes[meshIndex];
  19236. if (mesh.isBlocked) {
  19237. continue;
  19238. }
  19239. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  19240. if (!mesh.isReady() || !mesh.isEnabled()) {
  19241. continue;
  19242. }
  19243. mesh.computeWorldMatrix();
  19244. // Intersections
  19245. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  19246. this._meshesForIntersections.pushNoDuplicate(mesh);
  19247. }
  19248. // Switch to current LOD
  19249. var meshLOD = mesh.getLOD(this.activeCamera);
  19250. if (!meshLOD) {
  19251. continue;
  19252. }
  19253. mesh._preActivate();
  19254. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  19255. this._activeMeshes.push(mesh);
  19256. this.activeCamera._activeMeshes.push(mesh);
  19257. mesh._activate(this._renderId);
  19258. if (meshLOD !== mesh) {
  19259. meshLOD._activate(this._renderId);
  19260. }
  19261. this._activeMesh(mesh, meshLOD);
  19262. }
  19263. }
  19264. // Particle systems
  19265. this._particlesDuration.beginMonitoring();
  19266. if (this.particlesEnabled) {
  19267. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  19268. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  19269. var particleSystem = this.particleSystems[particleIndex];
  19270. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  19271. continue;
  19272. }
  19273. var emitter = particleSystem.emitter;
  19274. if (!emitter.position || emitter.isEnabled()) {
  19275. this._activeParticleSystems.push(particleSystem);
  19276. particleSystem.animate();
  19277. this._renderingManager.dispatchParticles(particleSystem);
  19278. }
  19279. }
  19280. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  19281. }
  19282. this._particlesDuration.endMonitoring(false);
  19283. };
  19284. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  19285. if (mesh.skeleton && this.skeletonsEnabled) {
  19286. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  19287. mesh.skeleton.prepare();
  19288. }
  19289. if (!mesh.computeBonesUsingShaders) {
  19290. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  19291. }
  19292. }
  19293. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  19294. var boundingInfo = sourceMesh.getBoundingInfo();
  19295. if (boundingInfo) {
  19296. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  19297. }
  19298. }
  19299. if (mesh && mesh.subMeshes) {
  19300. // Submeshes Octrees
  19301. var len;
  19302. var subMeshes;
  19303. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  19304. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  19305. len = intersections.length;
  19306. subMeshes = intersections.data;
  19307. }
  19308. else {
  19309. subMeshes = mesh.subMeshes;
  19310. len = subMeshes.length;
  19311. }
  19312. for (var subIndex = 0; subIndex < len; subIndex++) {
  19313. var subMesh = subMeshes[subIndex];
  19314. this._evaluateSubMesh(subMesh, mesh);
  19315. }
  19316. }
  19317. };
  19318. Scene.prototype.updateTransformMatrix = function (force) {
  19319. if (!this.activeCamera) {
  19320. return;
  19321. }
  19322. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  19323. };
  19324. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  19325. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  19326. };
  19327. Scene.prototype._renderForCamera = function (camera) {
  19328. if (camera && camera._skipRendering) {
  19329. return;
  19330. }
  19331. var engine = this._engine;
  19332. this.activeCamera = camera;
  19333. if (!this.activeCamera)
  19334. throw new Error("Active camera not set");
  19335. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19336. // Viewport
  19337. engine.setViewport(this.activeCamera.viewport);
  19338. // Camera
  19339. this.resetCachedMaterial();
  19340. this._renderId++;
  19341. this.activeCamera.update();
  19342. this.updateTransformMatrix();
  19343. if (camera._alternateCamera) {
  19344. this.updateAlternateTransformMatrix(camera._alternateCamera);
  19345. this._alternateRendering = true;
  19346. }
  19347. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  19348. // Meshes
  19349. this._evaluateActiveMeshesDuration.beginMonitoring();
  19350. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  19351. this._evaluateActiveMeshes();
  19352. this._evaluateActiveMeshesDuration.endMonitoring(false);
  19353. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  19354. // Software skinning
  19355. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  19356. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  19357. mesh.applySkeleton(mesh.skeleton);
  19358. }
  19359. // Render targets
  19360. this._renderTargetsDuration.beginMonitoring();
  19361. var needsRestoreFrameBuffer = false;
  19362. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  19363. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  19364. }
  19365. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  19366. this._intermediateRendering = true;
  19367. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  19368. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  19369. var renderTarget = this._renderTargets.data[renderIndex];
  19370. if (renderTarget._shouldRender()) {
  19371. this._renderId++;
  19372. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  19373. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  19374. }
  19375. }
  19376. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  19377. this._intermediateRendering = false;
  19378. this._renderId++;
  19379. needsRestoreFrameBuffer = true; // Restore back buffer
  19380. }
  19381. // Render HighlightLayer Texture
  19382. var stencilState = this._engine.getStencilBuffer();
  19383. var renderhighlights = false;
  19384. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  19385. this._intermediateRendering = true;
  19386. for (var i = 0; i < this.highlightLayers.length; i++) {
  19387. var highlightLayer = this.highlightLayers[i];
  19388. if (highlightLayer.shouldRender() &&
  19389. (!highlightLayer.camera ||
  19390. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  19391. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  19392. renderhighlights = true;
  19393. var renderTarget = highlightLayer._mainTexture;
  19394. if (renderTarget._shouldRender()) {
  19395. this._renderId++;
  19396. renderTarget.render(false, false);
  19397. needsRestoreFrameBuffer = true;
  19398. }
  19399. }
  19400. }
  19401. this._intermediateRendering = false;
  19402. this._renderId++;
  19403. }
  19404. if (needsRestoreFrameBuffer) {
  19405. engine.restoreDefaultFramebuffer(); // Restore back buffer
  19406. }
  19407. this._renderTargetsDuration.endMonitoring(false);
  19408. // Prepare Frame
  19409. this.postProcessManager._prepareFrame();
  19410. this._renderDuration.beginMonitoring();
  19411. // Backgrounds
  19412. var layerIndex;
  19413. var layer;
  19414. if (this.layers.length) {
  19415. engine.setDepthBuffer(false);
  19416. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  19417. layer = this.layers[layerIndex];
  19418. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  19419. layer.render();
  19420. }
  19421. }
  19422. engine.setDepthBuffer(true);
  19423. }
  19424. // Render
  19425. BABYLON.Tools.StartPerformanceCounter("Main render");
  19426. // Activate HighlightLayer stencil
  19427. if (renderhighlights) {
  19428. this._engine.setStencilBuffer(true);
  19429. }
  19430. this._renderingManager.render(null, null, true, true);
  19431. // Restore HighlightLayer stencil
  19432. if (renderhighlights) {
  19433. this._engine.setStencilBuffer(stencilState);
  19434. }
  19435. BABYLON.Tools.EndPerformanceCounter("Main render");
  19436. // Bounding boxes
  19437. if (this._boundingBoxRenderer) {
  19438. this._boundingBoxRenderer.render();
  19439. }
  19440. // Lens flares
  19441. if (this.lensFlaresEnabled) {
  19442. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  19443. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  19444. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  19445. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  19446. lensFlareSystem.render();
  19447. }
  19448. }
  19449. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  19450. }
  19451. // Foregrounds
  19452. if (this.layers.length) {
  19453. engine.setDepthBuffer(false);
  19454. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  19455. layer = this.layers[layerIndex];
  19456. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  19457. layer.render();
  19458. }
  19459. }
  19460. engine.setDepthBuffer(true);
  19461. }
  19462. // Highlight Layer
  19463. if (renderhighlights) {
  19464. engine.setDepthBuffer(false);
  19465. for (var i = 0; i < this.highlightLayers.length; i++) {
  19466. if (this.highlightLayers[i].shouldRender()) {
  19467. this.highlightLayers[i].render();
  19468. }
  19469. }
  19470. engine.setDepthBuffer(true);
  19471. }
  19472. this._renderDuration.endMonitoring(false);
  19473. // Finalize frame
  19474. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  19475. // Reset some special arrays
  19476. this._renderTargets.reset();
  19477. this._alternateRendering = false;
  19478. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  19479. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19480. };
  19481. Scene.prototype._processSubCameras = function (camera) {
  19482. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  19483. this._renderForCamera(camera);
  19484. return;
  19485. }
  19486. // Update camera
  19487. if (this.activeCamera) {
  19488. this.activeCamera.update();
  19489. }
  19490. // rig cameras
  19491. for (var index = 0; index < camera._rigCameras.length; index++) {
  19492. this._renderForCamera(camera._rigCameras[index]);
  19493. }
  19494. this.activeCamera = camera;
  19495. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  19496. };
  19497. Scene.prototype._checkIntersections = function () {
  19498. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  19499. var sourceMesh = this._meshesForIntersections.data[index];
  19500. if (!sourceMesh.actionManager) {
  19501. continue;
  19502. }
  19503. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  19504. var action = sourceMesh.actionManager.actions[actionIndex];
  19505. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19506. var parameters = action.getTriggerParameter();
  19507. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  19508. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  19509. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  19510. if (areIntersecting && currentIntersectionInProgress === -1) {
  19511. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  19512. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  19513. sourceMesh._intersectionsInProgress.push(otherMesh);
  19514. }
  19515. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19516. sourceMesh._intersectionsInProgress.push(otherMesh);
  19517. }
  19518. }
  19519. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  19520. //They intersected, and now they don't.
  19521. //is this trigger an exit trigger? execute an event.
  19522. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19523. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  19524. }
  19525. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  19526. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19527. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  19528. }
  19529. }
  19530. }
  19531. }
  19532. }
  19533. };
  19534. Scene.prototype.render = function () {
  19535. if (this.isDisposed) {
  19536. return;
  19537. }
  19538. this._interFrameDuration.endMonitoring();
  19539. this._lastFrameDuration.beginMonitoring();
  19540. this._particlesDuration.fetchNewFrame();
  19541. this._spritesDuration.fetchNewFrame();
  19542. this._activeParticles.fetchNewFrame();
  19543. this._renderDuration.fetchNewFrame();
  19544. this._renderTargetsDuration.fetchNewFrame();
  19545. this._evaluateActiveMeshesDuration.fetchNewFrame();
  19546. this._totalVertices.fetchNewFrame();
  19547. this._activeIndices.fetchNewFrame();
  19548. this._activeBones.fetchNewFrame();
  19549. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  19550. this._meshesForIntersections.reset();
  19551. this.resetCachedMaterial();
  19552. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  19553. // Actions
  19554. if (this.actionManager) {
  19555. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  19556. }
  19557. //Simplification Queue
  19558. if (this.simplificationQueue && !this.simplificationQueue.running) {
  19559. this.simplificationQueue.executeNext();
  19560. }
  19561. if (this._engine.isDeterministicLockStep()) {
  19562. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  19563. var defaultTimeStep = (60.0 / 1000.0);
  19564. if (this._physicsEngine) {
  19565. defaultTimeStep = this._physicsEngine.getTimeStep();
  19566. }
  19567. var maxSubSteps = this._engine.getLockstepMaxSteps();
  19568. this._timeAccumulator += deltaTime;
  19569. // compute the amount of fixed steps we should have taken since the last step
  19570. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  19571. internalSteps = Math.min(internalSteps, maxSubSteps);
  19572. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  19573. this.onBeforeStepObservable.notifyObservers(this);
  19574. // Animations
  19575. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  19576. this._animate();
  19577. // Physics
  19578. if (this._physicsEngine) {
  19579. BABYLON.Tools.StartPerformanceCounter("Physics");
  19580. this._physicsEngine._step(defaultTimeStep);
  19581. BABYLON.Tools.EndPerformanceCounter("Physics");
  19582. }
  19583. this._timeAccumulator -= defaultTimeStep;
  19584. this.onAfterStepObservable.notifyObservers(this);
  19585. this._currentStepId++;
  19586. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  19587. this._evaluateActiveMeshes();
  19588. }
  19589. }
  19590. }
  19591. else {
  19592. // Animations
  19593. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  19594. this._animationRatio = deltaTime * (60.0 / 1000.0);
  19595. this._animate();
  19596. // Physics
  19597. if (this._physicsEngine) {
  19598. BABYLON.Tools.StartPerformanceCounter("Physics");
  19599. this._physicsEngine._step(deltaTime / 1000.0);
  19600. BABYLON.Tools.EndPerformanceCounter("Physics");
  19601. }
  19602. }
  19603. // Before render
  19604. this.onBeforeRenderObservable.notifyObservers(this);
  19605. // Customs render targets
  19606. this._renderTargetsDuration.beginMonitoring();
  19607. var engine = this.getEngine();
  19608. var currentActiveCamera = this.activeCamera;
  19609. if (this.renderTargetsEnabled) {
  19610. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  19611. this._intermediateRendering = true;
  19612. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  19613. var renderTarget = this.customRenderTargets[customIndex];
  19614. if (renderTarget._shouldRender()) {
  19615. this._renderId++;
  19616. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  19617. if (!this.activeCamera)
  19618. throw new Error("Active camera not set");
  19619. // Viewport
  19620. engine.setViewport(this.activeCamera.viewport);
  19621. // Camera
  19622. this.updateTransformMatrix();
  19623. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  19624. }
  19625. }
  19626. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  19627. this._intermediateRendering = false;
  19628. this._renderId++;
  19629. }
  19630. // Restore back buffer
  19631. if (this.customRenderTargets.length > 0) {
  19632. engine.restoreDefaultFramebuffer();
  19633. }
  19634. this._renderTargetsDuration.endMonitoring();
  19635. this.activeCamera = currentActiveCamera;
  19636. // Procedural textures
  19637. if (this.proceduralTexturesEnabled) {
  19638. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  19639. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  19640. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  19641. if (proceduralTexture._shouldRender()) {
  19642. proceduralTexture.render();
  19643. }
  19644. }
  19645. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  19646. }
  19647. // Clear
  19648. if (this.autoClearDepthAndStencil || this.autoClear) {
  19649. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  19650. }
  19651. // Shadows
  19652. if (this.shadowsEnabled) {
  19653. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  19654. var light = this.lights[lightIndex];
  19655. var shadowGenerator = light.getShadowGenerator();
  19656. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  19657. var shadowMap = (shadowGenerator.getShadowMap());
  19658. if (this.textures.indexOf(shadowMap) !== -1) {
  19659. this._renderTargets.push(shadowMap);
  19660. }
  19661. }
  19662. }
  19663. }
  19664. // Depth renderer
  19665. if (this._depthRenderer) {
  19666. this._renderTargets.push(this._depthRenderer.getDepthMap());
  19667. }
  19668. // Geometry renderer
  19669. if (this._geometryBufferRenderer) {
  19670. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  19671. }
  19672. // RenderPipeline
  19673. if (this._postProcessRenderPipelineManager) {
  19674. this._postProcessRenderPipelineManager.update();
  19675. }
  19676. // Multi-cameras?
  19677. if (this.activeCameras.length > 0) {
  19678. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  19679. if (cameraIndex > 0) {
  19680. this._engine.clear(null, false, true, true);
  19681. }
  19682. this._processSubCameras(this.activeCameras[cameraIndex]);
  19683. }
  19684. }
  19685. else {
  19686. if (!this.activeCamera) {
  19687. throw new Error("No camera defined");
  19688. }
  19689. this._processSubCameras(this.activeCamera);
  19690. }
  19691. // Intersection checks
  19692. this._checkIntersections();
  19693. // Update the audio listener attached to the camera
  19694. if (BABYLON.AudioEngine) {
  19695. this._updateAudioParameters();
  19696. }
  19697. // After render
  19698. if (this.afterRender) {
  19699. this.afterRender();
  19700. }
  19701. this.onAfterRenderObservable.notifyObservers(this);
  19702. // Cleaning
  19703. for (var index = 0; index < this._toBeDisposed.length; index++) {
  19704. var data = this._toBeDisposed.data[index];
  19705. if (data) {
  19706. data.dispose();
  19707. }
  19708. this._toBeDisposed[index] = null;
  19709. }
  19710. this._toBeDisposed.reset();
  19711. if (this.dumpNextRenderTargets) {
  19712. this.dumpNextRenderTargets = false;
  19713. }
  19714. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  19715. this._interFrameDuration.beginMonitoring();
  19716. this._lastFrameDuration.endMonitoring();
  19717. this._totalMeshesCounter.addCount(this.meshes.length, true);
  19718. this._totalLightsCounter.addCount(this.lights.length, true);
  19719. this._totalMaterialsCounter.addCount(this.materials.length, true);
  19720. this._totalTexturesCounter.addCount(this.textures.length, true);
  19721. this._activeBones.addCount(0, true);
  19722. this._activeIndices.addCount(0, true);
  19723. this._activeParticles.addCount(0, true);
  19724. };
  19725. Scene.prototype._updateAudioParameters = function () {
  19726. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  19727. return;
  19728. }
  19729. var listeningCamera;
  19730. var audioEngine = BABYLON.Engine.audioEngine;
  19731. if (this.activeCameras.length > 0) {
  19732. listeningCamera = this.activeCameras[0];
  19733. }
  19734. else {
  19735. listeningCamera = this.activeCamera;
  19736. }
  19737. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  19738. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  19739. // for VR cameras
  19740. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  19741. listeningCamera = listeningCamera.rigCameras[0];
  19742. }
  19743. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  19744. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  19745. cameraDirection.normalize();
  19746. // To avoid some errors on GearVR
  19747. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  19748. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  19749. }
  19750. var i;
  19751. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19752. var sound = this.mainSoundTrack.soundCollection[i];
  19753. if (sound.useCustomAttenuation) {
  19754. sound.updateDistanceFromListener();
  19755. }
  19756. }
  19757. for (i = 0; i < this.soundTracks.length; i++) {
  19758. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19759. sound = this.soundTracks[i].soundCollection[j];
  19760. if (sound.useCustomAttenuation) {
  19761. sound.updateDistanceFromListener();
  19762. }
  19763. }
  19764. }
  19765. }
  19766. };
  19767. Object.defineProperty(Scene.prototype, "audioEnabled", {
  19768. // Audio
  19769. get: function () {
  19770. return this._audioEnabled;
  19771. },
  19772. set: function (value) {
  19773. this._audioEnabled = value;
  19774. if (BABYLON.AudioEngine) {
  19775. if (this._audioEnabled) {
  19776. this._enableAudio();
  19777. }
  19778. else {
  19779. this._disableAudio();
  19780. }
  19781. }
  19782. },
  19783. enumerable: true,
  19784. configurable: true
  19785. });
  19786. Scene.prototype._disableAudio = function () {
  19787. var i;
  19788. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19789. this.mainSoundTrack.soundCollection[i].pause();
  19790. }
  19791. for (i = 0; i < this.soundTracks.length; i++) {
  19792. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19793. this.soundTracks[i].soundCollection[j].pause();
  19794. }
  19795. }
  19796. };
  19797. Scene.prototype._enableAudio = function () {
  19798. var i;
  19799. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19800. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  19801. this.mainSoundTrack.soundCollection[i].play();
  19802. }
  19803. }
  19804. for (i = 0; i < this.soundTracks.length; i++) {
  19805. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19806. if (this.soundTracks[i].soundCollection[j].isPaused) {
  19807. this.soundTracks[i].soundCollection[j].play();
  19808. }
  19809. }
  19810. }
  19811. };
  19812. Object.defineProperty(Scene.prototype, "headphone", {
  19813. get: function () {
  19814. return this._headphone;
  19815. },
  19816. set: function (value) {
  19817. this._headphone = value;
  19818. if (BABYLON.AudioEngine) {
  19819. if (this._headphone) {
  19820. this._switchAudioModeForHeadphones();
  19821. }
  19822. else {
  19823. this._switchAudioModeForNormalSpeakers();
  19824. }
  19825. }
  19826. },
  19827. enumerable: true,
  19828. configurable: true
  19829. });
  19830. Scene.prototype._switchAudioModeForHeadphones = function () {
  19831. this.mainSoundTrack.switchPanningModelToHRTF();
  19832. for (var i = 0; i < this.soundTracks.length; i++) {
  19833. this.soundTracks[i].switchPanningModelToHRTF();
  19834. }
  19835. };
  19836. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  19837. this.mainSoundTrack.switchPanningModelToEqualPower();
  19838. for (var i = 0; i < this.soundTracks.length; i++) {
  19839. this.soundTracks[i].switchPanningModelToEqualPower();
  19840. }
  19841. };
  19842. Scene.prototype.enableDepthRenderer = function () {
  19843. if (this._depthRenderer) {
  19844. return this._depthRenderer;
  19845. }
  19846. this._depthRenderer = new BABYLON.DepthRenderer(this);
  19847. return this._depthRenderer;
  19848. };
  19849. Scene.prototype.disableDepthRenderer = function () {
  19850. if (!this._depthRenderer) {
  19851. return;
  19852. }
  19853. this._depthRenderer.dispose();
  19854. this._depthRenderer = null;
  19855. };
  19856. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  19857. if (ratio === void 0) { ratio = 1; }
  19858. if (this._geometryBufferRenderer) {
  19859. return this._geometryBufferRenderer;
  19860. }
  19861. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  19862. if (!this._geometryBufferRenderer.isSupported) {
  19863. this._geometryBufferRenderer = null;
  19864. }
  19865. return this._geometryBufferRenderer;
  19866. };
  19867. Scene.prototype.disableGeometryBufferRenderer = function () {
  19868. if (!this._geometryBufferRenderer) {
  19869. return;
  19870. }
  19871. this._geometryBufferRenderer.dispose();
  19872. this._geometryBufferRenderer = null;
  19873. };
  19874. Scene.prototype.freezeMaterials = function () {
  19875. for (var i = 0; i < this.materials.length; i++) {
  19876. this.materials[i].freeze();
  19877. }
  19878. };
  19879. Scene.prototype.unfreezeMaterials = function () {
  19880. for (var i = 0; i < this.materials.length; i++) {
  19881. this.materials[i].unfreeze();
  19882. }
  19883. };
  19884. Scene.prototype.dispose = function () {
  19885. this.beforeRender = null;
  19886. this.afterRender = null;
  19887. this.skeletons = [];
  19888. this.morphTargetManagers = [];
  19889. this.importedMeshesFiles = new Array();
  19890. this.resetCachedMaterial();
  19891. if (this._depthRenderer) {
  19892. this._depthRenderer.dispose();
  19893. }
  19894. if (this._gamepadManager) {
  19895. this._gamepadManager.dispose();
  19896. this._gamepadManager = null;
  19897. }
  19898. // Smart arrays
  19899. if (this.activeCamera) {
  19900. this.activeCamera._activeMeshes.dispose();
  19901. this.activeCamera = null;
  19902. }
  19903. this._activeMeshes.dispose();
  19904. this._renderingManager.dispose();
  19905. this._processedMaterials.dispose();
  19906. this._activeParticleSystems.dispose();
  19907. this._activeSkeletons.dispose();
  19908. this._softwareSkinnedMeshes.dispose();
  19909. this._renderTargets.dispose();
  19910. if (this._boundingBoxRenderer) {
  19911. this._boundingBoxRenderer.dispose();
  19912. }
  19913. this._meshesForIntersections.dispose();
  19914. this._toBeDisposed.dispose();
  19915. // Debug layer
  19916. if (this._debugLayer) {
  19917. this._debugLayer.hide();
  19918. }
  19919. // Events
  19920. this.onDisposeObservable.notifyObservers(this);
  19921. this.onDisposeObservable.clear();
  19922. this.onBeforeRenderObservable.clear();
  19923. this.onAfterRenderObservable.clear();
  19924. this.detachControl();
  19925. // Release sounds & sounds tracks
  19926. if (BABYLON.AudioEngine) {
  19927. this.disposeSounds();
  19928. }
  19929. // VR Helper
  19930. if (this.VRHelper) {
  19931. this.VRHelper.dispose();
  19932. }
  19933. // Detach cameras
  19934. var canvas = this._engine.getRenderingCanvas();
  19935. if (canvas) {
  19936. var index;
  19937. for (index = 0; index < this.cameras.length; index++) {
  19938. this.cameras[index].detachControl(canvas);
  19939. }
  19940. }
  19941. // Release lights
  19942. while (this.lights.length) {
  19943. this.lights[0].dispose();
  19944. }
  19945. // Release meshes
  19946. while (this.meshes.length) {
  19947. this.meshes[0].dispose(true);
  19948. }
  19949. // Release cameras
  19950. while (this.cameras.length) {
  19951. this.cameras[0].dispose();
  19952. }
  19953. // Release materials
  19954. if (this.defaultMaterial) {
  19955. this.defaultMaterial.dispose();
  19956. }
  19957. while (this.multiMaterials.length) {
  19958. this.multiMaterials[0].dispose();
  19959. }
  19960. while (this.materials.length) {
  19961. this.materials[0].dispose();
  19962. }
  19963. // Release particles
  19964. while (this.particleSystems.length) {
  19965. this.particleSystems[0].dispose();
  19966. }
  19967. // Release sprites
  19968. while (this.spriteManagers.length) {
  19969. this.spriteManagers[0].dispose();
  19970. }
  19971. // Release postProcesses
  19972. while (this.postProcesses.length) {
  19973. this.postProcesses[0].dispose();
  19974. }
  19975. // Release layers
  19976. while (this.layers.length) {
  19977. this.layers[0].dispose();
  19978. }
  19979. while (this.highlightLayers.length) {
  19980. this.highlightLayers[0].dispose();
  19981. }
  19982. // Release textures
  19983. while (this.textures.length) {
  19984. this.textures[0].dispose();
  19985. }
  19986. // Release UBO
  19987. this._sceneUbo.dispose();
  19988. if (this._alternateSceneUbo) {
  19989. this._alternateSceneUbo.dispose();
  19990. }
  19991. // Post-processes
  19992. this.postProcessManager.dispose();
  19993. if (this._postProcessRenderPipelineManager) {
  19994. this._postProcessRenderPipelineManager.dispose();
  19995. }
  19996. // Physics
  19997. if (this._physicsEngine) {
  19998. this.disablePhysicsEngine();
  19999. }
  20000. // Remove from engine
  20001. index = this._engine.scenes.indexOf(this);
  20002. if (index > -1) {
  20003. this._engine.scenes.splice(index, 1);
  20004. }
  20005. this._engine.wipeCaches();
  20006. };
  20007. Object.defineProperty(Scene.prototype, "isDisposed", {
  20008. get: function () {
  20009. return !this._engine;
  20010. },
  20011. enumerable: true,
  20012. configurable: true
  20013. });
  20014. // Release sounds & sounds tracks
  20015. Scene.prototype.disposeSounds = function () {
  20016. if (!this._mainSoundTrack) {
  20017. return;
  20018. }
  20019. this.mainSoundTrack.dispose();
  20020. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  20021. this.soundTracks[scIndex].dispose();
  20022. }
  20023. };
  20024. // Octrees
  20025. Scene.prototype.getWorldExtends = function () {
  20026. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20027. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20028. for (var index = 0; index < this.meshes.length; index++) {
  20029. var mesh = this.meshes[index];
  20030. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  20031. continue;
  20032. }
  20033. mesh.computeWorldMatrix(true);
  20034. var boundingInfo = mesh.getBoundingInfo();
  20035. if (boundingInfo) {
  20036. var minBox = boundingInfo.boundingBox.minimumWorld;
  20037. var maxBox = boundingInfo.boundingBox.maximumWorld;
  20038. BABYLON.Tools.CheckExtends(minBox, min, max);
  20039. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20040. }
  20041. }
  20042. return {
  20043. min: min,
  20044. max: max
  20045. };
  20046. };
  20047. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  20048. if (maxCapacity === void 0) { maxCapacity = 64; }
  20049. if (maxDepth === void 0) { maxDepth = 2; }
  20050. if (!this._selectionOctree) {
  20051. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  20052. }
  20053. var worldExtends = this.getWorldExtends();
  20054. // Update octree
  20055. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  20056. return this._selectionOctree;
  20057. };
  20058. // Picking
  20059. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  20060. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  20061. var engine = this._engine;
  20062. if (!camera) {
  20063. if (!this.activeCamera)
  20064. throw new Error("Active camera not set");
  20065. camera = this.activeCamera;
  20066. }
  20067. var cameraViewport = camera.viewport;
  20068. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  20069. // Moving coordinates to local viewport world
  20070. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  20071. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  20072. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  20073. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  20074. };
  20075. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  20076. if (!BABYLON.PickingInfo) {
  20077. return null;
  20078. }
  20079. var engine = this._engine;
  20080. if (!camera) {
  20081. if (!this.activeCamera)
  20082. throw new Error("Active camera not set");
  20083. camera = this.activeCamera;
  20084. }
  20085. var cameraViewport = camera.viewport;
  20086. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  20087. var identity = BABYLON.Matrix.Identity();
  20088. // Moving coordinates to local viewport world
  20089. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  20090. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  20091. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  20092. };
  20093. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  20094. if (!BABYLON.PickingInfo) {
  20095. return null;
  20096. }
  20097. var pickingInfo = null;
  20098. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  20099. var mesh = this.meshes[meshIndex];
  20100. if (predicate) {
  20101. if (!predicate(mesh)) {
  20102. continue;
  20103. }
  20104. }
  20105. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  20106. continue;
  20107. }
  20108. var world = mesh.getWorldMatrix();
  20109. var ray = rayFunction(world);
  20110. var result = mesh.intersects(ray, fastCheck);
  20111. if (!result || !result.hit)
  20112. continue;
  20113. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  20114. continue;
  20115. pickingInfo = result;
  20116. if (fastCheck) {
  20117. break;
  20118. }
  20119. }
  20120. return pickingInfo || new BABYLON.PickingInfo();
  20121. };
  20122. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  20123. if (!BABYLON.PickingInfo) {
  20124. return null;
  20125. }
  20126. var pickingInfos = new Array();
  20127. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  20128. var mesh = this.meshes[meshIndex];
  20129. if (predicate) {
  20130. if (!predicate(mesh)) {
  20131. continue;
  20132. }
  20133. }
  20134. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  20135. continue;
  20136. }
  20137. var world = mesh.getWorldMatrix();
  20138. var ray = rayFunction(world);
  20139. var result = mesh.intersects(ray, false);
  20140. if (!result || !result.hit)
  20141. continue;
  20142. pickingInfos.push(result);
  20143. }
  20144. return pickingInfos;
  20145. };
  20146. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  20147. if (!BABYLON.PickingInfo) {
  20148. return null;
  20149. }
  20150. var pickingInfo = null;
  20151. if (!camera) {
  20152. if (!this.activeCamera) {
  20153. return null;
  20154. }
  20155. camera = this.activeCamera;
  20156. }
  20157. if (this.spriteManagers.length > 0) {
  20158. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  20159. var spriteManager = this.spriteManagers[spriteIndex];
  20160. if (!spriteManager.isPickable) {
  20161. continue;
  20162. }
  20163. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  20164. if (!result || !result.hit)
  20165. continue;
  20166. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  20167. continue;
  20168. pickingInfo = result;
  20169. if (fastCheck) {
  20170. break;
  20171. }
  20172. }
  20173. }
  20174. return pickingInfo || new BABYLON.PickingInfo();
  20175. };
  20176. /** Launch a ray to try to pick a mesh in the scene
  20177. * @param x position on screen
  20178. * @param y position on screen
  20179. * @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
  20180. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20181. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20182. */
  20183. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  20184. var _this = this;
  20185. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate, fastCheck);
  20186. };
  20187. /** Launch a ray to try to pick a sprite in the scene
  20188. * @param x position on screen
  20189. * @param y position on screen
  20190. * @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
  20191. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20192. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20193. */
  20194. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  20195. var ray = this.createPickingRayInCameraSpace(x, y, camera);
  20196. if (!ray) {
  20197. return null;
  20198. }
  20199. return this._internalPickSprites(ray, predicate, fastCheck, camera);
  20200. };
  20201. /** Use the given ray to pick a mesh in the scene
  20202. * @param ray The ray to use to pick meshes
  20203. * @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
  20204. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20205. */
  20206. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  20207. var _this = this;
  20208. return this._internalPick(function (world) {
  20209. if (!_this._pickWithRayInverseMatrix) {
  20210. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  20211. }
  20212. world.invertToRef(_this._pickWithRayInverseMatrix);
  20213. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  20214. }, predicate, fastCheck);
  20215. };
  20216. /**
  20217. * Launch a ray to try to pick a mesh in the scene
  20218. * @param x X position on screen
  20219. * @param y Y position on screen
  20220. * @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
  20221. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20222. */
  20223. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  20224. var _this = this;
  20225. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  20226. };
  20227. /**
  20228. * Launch a ray to try to pick a mesh in the scene
  20229. * @param ray Ray to use
  20230. * @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
  20231. */
  20232. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  20233. var _this = this;
  20234. return this._internalMultiPick(function (world) {
  20235. if (!_this._pickWithRayInverseMatrix) {
  20236. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  20237. }
  20238. world.invertToRef(_this._pickWithRayInverseMatrix);
  20239. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  20240. }, predicate);
  20241. };
  20242. Scene.prototype.setPointerOverMesh = function (mesh) {
  20243. if (this._pointerOverMesh === mesh) {
  20244. return;
  20245. }
  20246. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  20247. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  20248. }
  20249. this._pointerOverMesh = mesh;
  20250. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  20251. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  20252. }
  20253. };
  20254. Scene.prototype.getPointerOverMesh = function () {
  20255. return this._pointerOverMesh;
  20256. };
  20257. Scene.prototype.setPointerOverSprite = function (sprite) {
  20258. if (this._pointerOverSprite === sprite) {
  20259. return;
  20260. }
  20261. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  20262. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  20263. }
  20264. this._pointerOverSprite = sprite;
  20265. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  20266. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  20267. }
  20268. };
  20269. Scene.prototype.getPointerOverSprite = function () {
  20270. return this._pointerOverSprite;
  20271. };
  20272. // Physics
  20273. Scene.prototype.getPhysicsEngine = function () {
  20274. return this._physicsEngine;
  20275. };
  20276. /**
  20277. * Enables physics to the current scene
  20278. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  20279. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  20280. * @return {boolean} was the physics engine initialized
  20281. */
  20282. Scene.prototype.enablePhysics = function (gravity, plugin) {
  20283. if (gravity === void 0) { gravity = null; }
  20284. if (this._physicsEngine) {
  20285. return true;
  20286. }
  20287. try {
  20288. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  20289. return true;
  20290. }
  20291. catch (e) {
  20292. BABYLON.Tools.Error(e.message);
  20293. return false;
  20294. }
  20295. };
  20296. Scene.prototype.disablePhysicsEngine = function () {
  20297. if (!this._physicsEngine) {
  20298. return;
  20299. }
  20300. this._physicsEngine.dispose();
  20301. this._physicsEngine = null;
  20302. };
  20303. Scene.prototype.isPhysicsEnabled = function () {
  20304. return this._physicsEngine !== undefined;
  20305. };
  20306. Scene.prototype.deleteCompoundImpostor = function (compound) {
  20307. var mesh = compound.parts[0].mesh;
  20308. if (mesh.physicsImpostor) {
  20309. mesh.physicsImpostor.dispose();
  20310. mesh.physicsImpostor = null;
  20311. }
  20312. };
  20313. // Misc.
  20314. Scene.prototype._rebuildGeometries = function () {
  20315. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  20316. var geometry = _a[_i];
  20317. geometry._rebuild();
  20318. }
  20319. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  20320. var mesh = _c[_b];
  20321. mesh._rebuild();
  20322. }
  20323. if (this.postProcessManager) {
  20324. this.postProcessManager._rebuild();
  20325. }
  20326. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  20327. var layer = _e[_d];
  20328. layer._rebuild();
  20329. }
  20330. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  20331. var highlightLayer = _g[_f];
  20332. highlightLayer._rebuild();
  20333. }
  20334. if (this._boundingBoxRenderer) {
  20335. this._boundingBoxRenderer._rebuild();
  20336. }
  20337. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  20338. var system = _j[_h];
  20339. system.rebuild();
  20340. }
  20341. if (this._postProcessRenderPipelineManager) {
  20342. this._postProcessRenderPipelineManager._rebuild();
  20343. }
  20344. };
  20345. Scene.prototype._rebuildTextures = function () {
  20346. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  20347. var texture = _a[_i];
  20348. texture._rebuild();
  20349. }
  20350. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20351. };
  20352. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  20353. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  20354. if (replace === void 0) { replace = false; }
  20355. if (attachCameraControls === void 0) { attachCameraControls = false; }
  20356. // Dispose existing camera or light in replace mode.
  20357. if (replace) {
  20358. if (this.activeCamera) {
  20359. this.activeCamera.dispose();
  20360. this.activeCamera = null;
  20361. }
  20362. if (this.lights) {
  20363. for (var i = 0; i < this.lights.length; i++) {
  20364. this.lights[i].dispose();
  20365. }
  20366. }
  20367. }
  20368. // Light
  20369. if (this.lights.length === 0) {
  20370. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  20371. }
  20372. // Camera
  20373. if (!this.activeCamera) {
  20374. var worldExtends = this.getWorldExtends();
  20375. var worldSize = worldExtends.max.subtract(worldExtends.min);
  20376. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  20377. var camera;
  20378. var radius = worldSize.length() * 1.5;
  20379. if (createArcRotateCamera) {
  20380. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  20381. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  20382. arcRotateCamera.wheelPrecision = 100 / radius;
  20383. camera = arcRotateCamera;
  20384. }
  20385. else {
  20386. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  20387. freeCamera.setTarget(worldCenter);
  20388. camera = freeCamera;
  20389. }
  20390. camera.minZ = radius * 0.01;
  20391. camera.maxZ = radius * 100;
  20392. camera.speed = radius * 0.2;
  20393. this.activeCamera = camera;
  20394. var canvas = this.getEngine().getRenderingCanvas();
  20395. if (attachCameraControls && canvas) {
  20396. camera.attachControl(canvas);
  20397. }
  20398. }
  20399. };
  20400. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  20401. if (pbr === void 0) { pbr = false; }
  20402. if (scale === void 0) { scale = 1000; }
  20403. if (blur === void 0) { blur = 0; }
  20404. if (environmentTexture) {
  20405. this.environmentTexture = environmentTexture;
  20406. }
  20407. if (!this.environmentTexture) {
  20408. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  20409. return null;
  20410. }
  20411. // Skybox
  20412. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  20413. if (pbr) {
  20414. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  20415. hdrSkyboxMaterial.backFaceCulling = false;
  20416. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  20417. if (hdrSkyboxMaterial.reflectionTexture) {
  20418. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  20419. }
  20420. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  20421. hdrSkyboxMaterial.disableLighting = true;
  20422. hdrSkyboxMaterial.twoSidedLighting = true;
  20423. hdrSkybox.infiniteDistance = true;
  20424. hdrSkybox.material = hdrSkyboxMaterial;
  20425. }
  20426. else {
  20427. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  20428. skyboxMaterial.backFaceCulling = false;
  20429. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  20430. if (skyboxMaterial.reflectionTexture) {
  20431. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  20432. }
  20433. skyboxMaterial.disableLighting = true;
  20434. hdrSkybox.infiniteDistance = true;
  20435. hdrSkybox.material = skyboxMaterial;
  20436. }
  20437. return hdrSkybox;
  20438. };
  20439. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  20440. if (webVROptions === void 0) { webVROptions = {}; }
  20441. this.VRHelper = new BABYLON.VRExperienceHelper(this, webVROptions);
  20442. };
  20443. // Tags
  20444. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  20445. if (tagsQuery === undefined) {
  20446. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  20447. return list;
  20448. }
  20449. var listByTags = [];
  20450. forEach = forEach || (function (item) { return; });
  20451. for (var i in list) {
  20452. var item = list[i];
  20453. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  20454. listByTags.push(item);
  20455. forEach(item);
  20456. }
  20457. }
  20458. return listByTags;
  20459. };
  20460. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  20461. return this._getByTags(this.meshes, tagsQuery, forEach);
  20462. };
  20463. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  20464. return this._getByTags(this.cameras, tagsQuery, forEach);
  20465. };
  20466. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  20467. return this._getByTags(this.lights, tagsQuery, forEach);
  20468. };
  20469. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  20470. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  20471. };
  20472. /**
  20473. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20474. * This allowed control for front to back rendering or reversly depending of the special needs.
  20475. *
  20476. * @param renderingGroupId The rendering group id corresponding to its index
  20477. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20478. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20479. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20480. */
  20481. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20482. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20483. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20484. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20485. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  20486. };
  20487. /**
  20488. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20489. *
  20490. * @param renderingGroupId The rendering group id corresponding to its index
  20491. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20492. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20493. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20494. */
  20495. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20496. if (depth === void 0) { depth = true; }
  20497. if (stencil === void 0) { stencil = true; }
  20498. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  20499. };
  20500. /**
  20501. * Will flag all materials as dirty to trigger new shader compilation
  20502. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  20503. */
  20504. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  20505. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  20506. var material = _a[_i];
  20507. if (predicate && !predicate(material)) {
  20508. continue;
  20509. }
  20510. material.markAsDirty(flag);
  20511. }
  20512. };
  20513. // Statics
  20514. Scene._FOGMODE_NONE = 0;
  20515. Scene._FOGMODE_EXP = 1;
  20516. Scene._FOGMODE_EXP2 = 2;
  20517. Scene._FOGMODE_LINEAR = 3;
  20518. Scene._uniqueIdCounter = 0;
  20519. Scene.MinDeltaTime = 1.0;
  20520. Scene.MaxDeltaTime = 1000.0;
  20521. /** The distance in pixel that you have to move to prevent some events */
  20522. Scene.DragMovementThreshold = 10; // in pixels
  20523. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  20524. Scene.LongPressDelay = 500; // in milliseconds
  20525. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  20526. Scene.DoubleClickDelay = 300; // in milliseconds
  20527. /** If you need to check double click without raising a single click at first click, enable this flag */
  20528. Scene.ExclusiveDoubleClickMode = false;
  20529. return Scene;
  20530. }());
  20531. BABYLON.Scene = Scene;
  20532. })(BABYLON || (BABYLON = {}));
  20533. //# sourceMappingURL=babylon.scene.js.map
  20534. var BABYLON;
  20535. (function (BABYLON) {
  20536. var Buffer = /** @class */ (function () {
  20537. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  20538. if (instanced === void 0) { instanced = false; }
  20539. if (engine instanceof BABYLON.Mesh) {
  20540. this._engine = engine.getScene().getEngine();
  20541. }
  20542. else {
  20543. this._engine = engine;
  20544. }
  20545. this._updatable = updatable;
  20546. this._data = data;
  20547. this._strideSize = stride;
  20548. if (!postponeInternalCreation) {
  20549. this.create();
  20550. }
  20551. this._instanced = instanced;
  20552. this._instanceDivisor = instanced ? 1 : 0;
  20553. }
  20554. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  20555. // a lot of these parameters are ignored as they are overriden by the buffer
  20556. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  20557. };
  20558. // Properties
  20559. Buffer.prototype.isUpdatable = function () {
  20560. return this._updatable;
  20561. };
  20562. Buffer.prototype.getData = function () {
  20563. return this._data;
  20564. };
  20565. Buffer.prototype.getBuffer = function () {
  20566. return this._buffer;
  20567. };
  20568. Buffer.prototype.getStrideSize = function () {
  20569. return this._strideSize;
  20570. };
  20571. Buffer.prototype.getIsInstanced = function () {
  20572. return this._instanced;
  20573. };
  20574. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  20575. get: function () {
  20576. return this._instanceDivisor;
  20577. },
  20578. set: function (value) {
  20579. this._instanceDivisor = value;
  20580. if (value == 0) {
  20581. this._instanced = false;
  20582. }
  20583. else {
  20584. this._instanced = true;
  20585. }
  20586. },
  20587. enumerable: true,
  20588. configurable: true
  20589. });
  20590. // Methods
  20591. Buffer.prototype.create = function (data) {
  20592. if (data === void 0) { data = null; }
  20593. if (!data && this._buffer) {
  20594. return; // nothing to do
  20595. }
  20596. data = data || this._data;
  20597. if (!data) {
  20598. return;
  20599. }
  20600. if (!this._buffer) {
  20601. if (this._updatable) {
  20602. this._buffer = this._engine.createDynamicVertexBuffer(data);
  20603. this._data = data;
  20604. }
  20605. else {
  20606. this._buffer = this._engine.createVertexBuffer(data);
  20607. }
  20608. }
  20609. else if (this._updatable) {
  20610. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  20611. this._data = data;
  20612. }
  20613. };
  20614. Buffer.prototype._rebuild = function () {
  20615. this._buffer = null;
  20616. this.create(this._data);
  20617. };
  20618. Buffer.prototype.update = function (data) {
  20619. this.create(data);
  20620. };
  20621. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  20622. if (!this._buffer) {
  20623. return;
  20624. }
  20625. if (this._updatable) {
  20626. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  20627. this._data = null;
  20628. }
  20629. };
  20630. Buffer.prototype.dispose = function () {
  20631. if (!this._buffer) {
  20632. return;
  20633. }
  20634. if (this._engine._releaseBuffer(this._buffer)) {
  20635. this._buffer = null;
  20636. }
  20637. };
  20638. return Buffer;
  20639. }());
  20640. BABYLON.Buffer = Buffer;
  20641. })(BABYLON || (BABYLON = {}));
  20642. //# sourceMappingURL=babylon.buffer.js.map
  20643. var BABYLON;
  20644. (function (BABYLON) {
  20645. var VertexBuffer = /** @class */ (function () {
  20646. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  20647. if (!stride) {
  20648. // Deduce stride from kind
  20649. switch (kind) {
  20650. case VertexBuffer.PositionKind:
  20651. stride = 3;
  20652. break;
  20653. case VertexBuffer.NormalKind:
  20654. stride = 3;
  20655. break;
  20656. case VertexBuffer.UVKind:
  20657. case VertexBuffer.UV2Kind:
  20658. case VertexBuffer.UV3Kind:
  20659. case VertexBuffer.UV4Kind:
  20660. case VertexBuffer.UV5Kind:
  20661. case VertexBuffer.UV6Kind:
  20662. stride = 2;
  20663. break;
  20664. case VertexBuffer.TangentKind:
  20665. case VertexBuffer.ColorKind:
  20666. stride = 4;
  20667. break;
  20668. case VertexBuffer.MatricesIndicesKind:
  20669. case VertexBuffer.MatricesIndicesExtraKind:
  20670. stride = 4;
  20671. break;
  20672. case VertexBuffer.MatricesWeightsKind:
  20673. case VertexBuffer.MatricesWeightsExtraKind:
  20674. stride = 4;
  20675. break;
  20676. }
  20677. }
  20678. if (data instanceof BABYLON.Buffer) {
  20679. if (!stride) {
  20680. stride = data.getStrideSize();
  20681. }
  20682. this._buffer = data;
  20683. this._ownsBuffer = false;
  20684. }
  20685. else {
  20686. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  20687. this._ownsBuffer = true;
  20688. }
  20689. this._stride = stride;
  20690. this._offset = offset ? offset : 0;
  20691. this._size = size ? size : stride;
  20692. this._kind = kind;
  20693. }
  20694. VertexBuffer.prototype._rebuild = function () {
  20695. if (!this._buffer) {
  20696. return;
  20697. }
  20698. this._buffer._rebuild();
  20699. };
  20700. /**
  20701. * Returns the kind of the VertexBuffer (string).
  20702. */
  20703. VertexBuffer.prototype.getKind = function () {
  20704. return this._kind;
  20705. };
  20706. // Properties
  20707. /**
  20708. * Boolean : is the VertexBuffer updatable ?
  20709. */
  20710. VertexBuffer.prototype.isUpdatable = function () {
  20711. return this._buffer.isUpdatable();
  20712. };
  20713. /**
  20714. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  20715. */
  20716. VertexBuffer.prototype.getData = function () {
  20717. return this._buffer.getData();
  20718. };
  20719. /**
  20720. * Returns the WebGLBuffer associated to the VertexBuffer.
  20721. */
  20722. VertexBuffer.prototype.getBuffer = function () {
  20723. return this._buffer.getBuffer();
  20724. };
  20725. /**
  20726. * Returns the stride of the VertexBuffer (integer).
  20727. */
  20728. VertexBuffer.prototype.getStrideSize = function () {
  20729. return this._stride;
  20730. };
  20731. /**
  20732. * Returns the offset (integer).
  20733. */
  20734. VertexBuffer.prototype.getOffset = function () {
  20735. return this._offset;
  20736. };
  20737. /**
  20738. * Returns the VertexBuffer total size (integer).
  20739. */
  20740. VertexBuffer.prototype.getSize = function () {
  20741. return this._size;
  20742. };
  20743. /**
  20744. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  20745. */
  20746. VertexBuffer.prototype.getIsInstanced = function () {
  20747. return this._buffer.getIsInstanced();
  20748. };
  20749. /**
  20750. * Returns the instancing divisor, zero for non-instanced (integer).
  20751. */
  20752. VertexBuffer.prototype.getInstanceDivisor = function () {
  20753. return this._buffer.instanceDivisor;
  20754. };
  20755. // Methods
  20756. /**
  20757. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  20758. * Returns the created WebGLBuffer.
  20759. */
  20760. VertexBuffer.prototype.create = function (data) {
  20761. return this._buffer.create(data);
  20762. };
  20763. /**
  20764. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  20765. * Returns the updated WebGLBuffer.
  20766. */
  20767. VertexBuffer.prototype.update = function (data) {
  20768. return this._buffer.update(data);
  20769. };
  20770. /**
  20771. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  20772. * Returns the directly updated WebGLBuffer.
  20773. */
  20774. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  20775. return this._buffer.updateDirectly(data, offset);
  20776. };
  20777. /**
  20778. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  20779. */
  20780. VertexBuffer.prototype.dispose = function () {
  20781. if (this._ownsBuffer) {
  20782. this._buffer.dispose();
  20783. }
  20784. };
  20785. Object.defineProperty(VertexBuffer, "PositionKind", {
  20786. get: function () {
  20787. return VertexBuffer._PositionKind;
  20788. },
  20789. enumerable: true,
  20790. configurable: true
  20791. });
  20792. Object.defineProperty(VertexBuffer, "NormalKind", {
  20793. get: function () {
  20794. return VertexBuffer._NormalKind;
  20795. },
  20796. enumerable: true,
  20797. configurable: true
  20798. });
  20799. Object.defineProperty(VertexBuffer, "TangentKind", {
  20800. get: function () {
  20801. return VertexBuffer._TangentKind;
  20802. },
  20803. enumerable: true,
  20804. configurable: true
  20805. });
  20806. Object.defineProperty(VertexBuffer, "UVKind", {
  20807. get: function () {
  20808. return VertexBuffer._UVKind;
  20809. },
  20810. enumerable: true,
  20811. configurable: true
  20812. });
  20813. Object.defineProperty(VertexBuffer, "UV2Kind", {
  20814. get: function () {
  20815. return VertexBuffer._UV2Kind;
  20816. },
  20817. enumerable: true,
  20818. configurable: true
  20819. });
  20820. Object.defineProperty(VertexBuffer, "UV3Kind", {
  20821. get: function () {
  20822. return VertexBuffer._UV3Kind;
  20823. },
  20824. enumerable: true,
  20825. configurable: true
  20826. });
  20827. Object.defineProperty(VertexBuffer, "UV4Kind", {
  20828. get: function () {
  20829. return VertexBuffer._UV4Kind;
  20830. },
  20831. enumerable: true,
  20832. configurable: true
  20833. });
  20834. Object.defineProperty(VertexBuffer, "UV5Kind", {
  20835. get: function () {
  20836. return VertexBuffer._UV5Kind;
  20837. },
  20838. enumerable: true,
  20839. configurable: true
  20840. });
  20841. Object.defineProperty(VertexBuffer, "UV6Kind", {
  20842. get: function () {
  20843. return VertexBuffer._UV6Kind;
  20844. },
  20845. enumerable: true,
  20846. configurable: true
  20847. });
  20848. Object.defineProperty(VertexBuffer, "ColorKind", {
  20849. get: function () {
  20850. return VertexBuffer._ColorKind;
  20851. },
  20852. enumerable: true,
  20853. configurable: true
  20854. });
  20855. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  20856. get: function () {
  20857. return VertexBuffer._MatricesIndicesKind;
  20858. },
  20859. enumerable: true,
  20860. configurable: true
  20861. });
  20862. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  20863. get: function () {
  20864. return VertexBuffer._MatricesWeightsKind;
  20865. },
  20866. enumerable: true,
  20867. configurable: true
  20868. });
  20869. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  20870. get: function () {
  20871. return VertexBuffer._MatricesIndicesExtraKind;
  20872. },
  20873. enumerable: true,
  20874. configurable: true
  20875. });
  20876. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  20877. get: function () {
  20878. return VertexBuffer._MatricesWeightsExtraKind;
  20879. },
  20880. enumerable: true,
  20881. configurable: true
  20882. });
  20883. // Enums
  20884. VertexBuffer._PositionKind = "position";
  20885. VertexBuffer._NormalKind = "normal";
  20886. VertexBuffer._TangentKind = "tangent";
  20887. VertexBuffer._UVKind = "uv";
  20888. VertexBuffer._UV2Kind = "uv2";
  20889. VertexBuffer._UV3Kind = "uv3";
  20890. VertexBuffer._UV4Kind = "uv4";
  20891. VertexBuffer._UV5Kind = "uv5";
  20892. VertexBuffer._UV6Kind = "uv6";
  20893. VertexBuffer._ColorKind = "color";
  20894. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  20895. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  20896. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  20897. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  20898. return VertexBuffer;
  20899. }());
  20900. BABYLON.VertexBuffer = VertexBuffer;
  20901. })(BABYLON || (BABYLON = {}));
  20902. //# sourceMappingURL=babylon.vertexBuffer.js.map
  20903. var BABYLON;
  20904. (function (BABYLON) {
  20905. var InternalTexture = /** @class */ (function () {
  20906. function InternalTexture(engine, dataSource) {
  20907. this.onLoadedObservable = new BABYLON.Observable();
  20908. // Private
  20909. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  20910. this._references = 1;
  20911. this._engine = engine;
  20912. this._dataSource = dataSource;
  20913. this._webGLTexture = engine._createTexture();
  20914. }
  20915. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  20916. get: function () {
  20917. return this._dataSource;
  20918. },
  20919. enumerable: true,
  20920. configurable: true
  20921. });
  20922. InternalTexture.prototype.incrementReferences = function () {
  20923. this._references++;
  20924. };
  20925. InternalTexture.prototype.updateSize = function (width, height) {
  20926. this.width = width;
  20927. this.height = height;
  20928. this._size = width * height;
  20929. this.baseWidth = width;
  20930. this.baseHeight = height;
  20931. };
  20932. InternalTexture.prototype._rebuild = function () {
  20933. var _this = this;
  20934. var proxy;
  20935. this.isReady = false;
  20936. this._cachedCoordinatesMode = null;
  20937. this._cachedWrapU = null;
  20938. this._cachedWrapV = null;
  20939. this._cachedAnisotropicFilteringLevel = null;
  20940. switch (this._dataSource) {
  20941. case InternalTexture.DATASOURCE_TEMP:
  20942. return;
  20943. case InternalTexture.DATASOURCE_URL:
  20944. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  20945. _this.isReady = true;
  20946. }, null, this._buffer, undefined, this.format);
  20947. proxy._swapAndDie(this);
  20948. return;
  20949. case InternalTexture.DATASOURCE_RAW:
  20950. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  20951. proxy._swapAndDie(this);
  20952. this.isReady = true;
  20953. return;
  20954. case InternalTexture.DATASOURCE_DYNAMIC:
  20955. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  20956. proxy._swapAndDie(this);
  20957. // The engine will make sure to update content so no need to flag it as isReady = true
  20958. return;
  20959. case InternalTexture.DATASOURCE_RENDERTARGET:
  20960. var options = new BABYLON.RenderTargetCreationOptions();
  20961. options.generateDepthBuffer = this._generateDepthBuffer;
  20962. options.generateMipMaps = this.generateMipMaps;
  20963. options.generateStencilBuffer = this._generateStencilBuffer;
  20964. options.samplingMode = this.samplingMode;
  20965. options.type = this.type;
  20966. if (this.isCube) {
  20967. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  20968. }
  20969. else {
  20970. var size = {
  20971. width: this.width,
  20972. height: this.height
  20973. };
  20974. proxy = this._engine.createRenderTargetTexture(size, options);
  20975. }
  20976. proxy._swapAndDie(this);
  20977. this.isReady = true;
  20978. return;
  20979. case InternalTexture.DATASOURCE_CUBE:
  20980. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  20981. _this.isReady = true;
  20982. }, null, this.format, this._extension);
  20983. proxy._swapAndDie(this);
  20984. return;
  20985. case InternalTexture.DATASOURCE_CUBERAW:
  20986. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  20987. proxy._swapAndDie(this);
  20988. this.isReady = true;
  20989. return;
  20990. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  20991. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  20992. if (proxy) {
  20993. proxy._swapAndDie(_this);
  20994. }
  20995. _this.isReady = true;
  20996. }, null, this.format, this._extension);
  20997. return;
  20998. }
  20999. };
  21000. InternalTexture.prototype._swapAndDie = function (target) {
  21001. target._webGLTexture = this._webGLTexture;
  21002. if (this._framebuffer) {
  21003. target._framebuffer = this._framebuffer;
  21004. }
  21005. if (this._depthStencilBuffer) {
  21006. target._depthStencilBuffer = this._depthStencilBuffer;
  21007. }
  21008. if (this._lodTextureHigh) {
  21009. if (target._lodTextureHigh) {
  21010. target._lodTextureHigh.dispose();
  21011. }
  21012. target._lodTextureHigh = this._lodTextureHigh;
  21013. }
  21014. if (this._lodTextureMid) {
  21015. if (target._lodTextureMid) {
  21016. target._lodTextureMid.dispose();
  21017. }
  21018. target._lodTextureMid = this._lodTextureMid;
  21019. }
  21020. if (this._lodTextureLow) {
  21021. if (target._lodTextureLow) {
  21022. target._lodTextureLow.dispose();
  21023. }
  21024. target._lodTextureLow = this._lodTextureLow;
  21025. }
  21026. var cache = this._engine.getLoadedTexturesCache();
  21027. var index = cache.indexOf(this);
  21028. if (index !== -1) {
  21029. cache.splice(index, 1);
  21030. }
  21031. };
  21032. InternalTexture.prototype.dispose = function () {
  21033. if (!this._webGLTexture) {
  21034. return;
  21035. }
  21036. this._references--;
  21037. if (this._references === 0) {
  21038. this._engine._releaseTexture(this);
  21039. this._webGLTexture = null;
  21040. }
  21041. };
  21042. InternalTexture.DATASOURCE_UNKNOWN = 0;
  21043. InternalTexture.DATASOURCE_URL = 1;
  21044. InternalTexture.DATASOURCE_TEMP = 2;
  21045. InternalTexture.DATASOURCE_RAW = 3;
  21046. InternalTexture.DATASOURCE_DYNAMIC = 4;
  21047. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  21048. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  21049. InternalTexture.DATASOURCE_CUBE = 7;
  21050. InternalTexture.DATASOURCE_CUBERAW = 8;
  21051. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  21052. return InternalTexture;
  21053. }());
  21054. BABYLON.InternalTexture = InternalTexture;
  21055. })(BABYLON || (BABYLON = {}));
  21056. //# sourceMappingURL=babylon.internalTexture.js.map
  21057. var BABYLON;
  21058. (function (BABYLON) {
  21059. var BaseTexture = /** @class */ (function () {
  21060. function BaseTexture(scene) {
  21061. this._hasAlpha = false;
  21062. this.getAlphaFromRGB = false;
  21063. this.level = 1;
  21064. this.coordinatesIndex = 0;
  21065. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  21066. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  21067. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  21068. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  21069. this.isCube = false;
  21070. this.gammaSpace = true;
  21071. this.invertZ = false;
  21072. this.lodLevelInAlpha = false;
  21073. this.lodGenerationOffset = 0.0;
  21074. this.lodGenerationScale = 0.8;
  21075. this.isRenderTarget = false;
  21076. this.animations = new Array();
  21077. /**
  21078. * An event triggered when the texture is disposed.
  21079. * @type {BABYLON.Observable}
  21080. */
  21081. this.onDisposeObservable = new BABYLON.Observable();
  21082. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21083. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  21084. if (this._scene) {
  21085. this._scene.textures.push(this);
  21086. }
  21087. this._uid = null;
  21088. }
  21089. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  21090. get: function () {
  21091. return this._hasAlpha;
  21092. },
  21093. set: function (value) {
  21094. if (this._hasAlpha === value) {
  21095. return;
  21096. }
  21097. this._hasAlpha = value;
  21098. if (this._scene) {
  21099. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21100. }
  21101. },
  21102. enumerable: true,
  21103. configurable: true
  21104. });
  21105. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  21106. get: function () {
  21107. return this._coordinatesMode;
  21108. },
  21109. set: function (value) {
  21110. if (this._coordinatesMode === value) {
  21111. return;
  21112. }
  21113. this._coordinatesMode = value;
  21114. if (this._scene) {
  21115. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21116. }
  21117. },
  21118. enumerable: true,
  21119. configurable: true
  21120. });
  21121. Object.defineProperty(BaseTexture.prototype, "uid", {
  21122. get: function () {
  21123. if (!this._uid) {
  21124. this._uid = BABYLON.Tools.RandomId();
  21125. }
  21126. return this._uid;
  21127. },
  21128. enumerable: true,
  21129. configurable: true
  21130. });
  21131. BaseTexture.prototype.toString = function () {
  21132. return this.name;
  21133. };
  21134. BaseTexture.prototype.getClassName = function () {
  21135. return "BaseTexture";
  21136. };
  21137. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  21138. set: function (callback) {
  21139. if (this._onDisposeObserver) {
  21140. this.onDisposeObservable.remove(this._onDisposeObserver);
  21141. }
  21142. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21143. },
  21144. enumerable: true,
  21145. configurable: true
  21146. });
  21147. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  21148. get: function () {
  21149. return true;
  21150. },
  21151. enumerable: true,
  21152. configurable: true
  21153. });
  21154. BaseTexture.prototype.getScene = function () {
  21155. return this._scene;
  21156. };
  21157. BaseTexture.prototype.getTextureMatrix = function () {
  21158. return BABYLON.Matrix.IdentityReadOnly;
  21159. };
  21160. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  21161. return BABYLON.Matrix.IdentityReadOnly;
  21162. };
  21163. BaseTexture.prototype.getInternalTexture = function () {
  21164. return this._texture;
  21165. };
  21166. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  21167. return !this.isBlocking || this.isReady();
  21168. };
  21169. BaseTexture.prototype.isReady = function () {
  21170. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21171. this.delayLoad();
  21172. return false;
  21173. }
  21174. if (this._texture) {
  21175. return this._texture.isReady;
  21176. }
  21177. return false;
  21178. };
  21179. BaseTexture.prototype.getSize = function () {
  21180. if (this._texture && this._texture.width) {
  21181. return new BABYLON.Size(this._texture.width, this._texture.height);
  21182. }
  21183. if (this._texture && this._texture._size) {
  21184. return new BABYLON.Size(this._texture._size, this._texture._size);
  21185. }
  21186. return BABYLON.Size.Zero();
  21187. };
  21188. BaseTexture.prototype.getBaseSize = function () {
  21189. if (!this.isReady() || !this._texture)
  21190. return BABYLON.Size.Zero();
  21191. if (this._texture._size) {
  21192. return new BABYLON.Size(this._texture._size, this._texture._size);
  21193. }
  21194. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  21195. };
  21196. BaseTexture.prototype.scale = function (ratio) {
  21197. };
  21198. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  21199. get: function () {
  21200. return false;
  21201. },
  21202. enumerable: true,
  21203. configurable: true
  21204. });
  21205. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  21206. if (!this._scene) {
  21207. return null;
  21208. }
  21209. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  21210. for (var index = 0; index < texturesCache.length; index++) {
  21211. var texturesCacheEntry = texturesCache[index];
  21212. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  21213. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  21214. texturesCacheEntry.incrementReferences();
  21215. return texturesCacheEntry;
  21216. }
  21217. }
  21218. }
  21219. return null;
  21220. };
  21221. BaseTexture.prototype._rebuild = function () {
  21222. };
  21223. BaseTexture.prototype.delayLoad = function () {
  21224. };
  21225. BaseTexture.prototype.clone = function () {
  21226. return null;
  21227. };
  21228. Object.defineProperty(BaseTexture.prototype, "textureType", {
  21229. get: function () {
  21230. if (!this._texture) {
  21231. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  21232. }
  21233. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  21234. },
  21235. enumerable: true,
  21236. configurable: true
  21237. });
  21238. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  21239. get: function () {
  21240. if (!this._texture) {
  21241. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  21242. }
  21243. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  21244. },
  21245. enumerable: true,
  21246. configurable: true
  21247. });
  21248. BaseTexture.prototype.readPixels = function (faceIndex) {
  21249. if (faceIndex === void 0) { faceIndex = 0; }
  21250. if (!this._texture) {
  21251. return null;
  21252. }
  21253. var size = this.getSize();
  21254. var scene = this.getScene();
  21255. if (!scene) {
  21256. return null;
  21257. }
  21258. var engine = scene.getEngine();
  21259. if (this._texture.isCube) {
  21260. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  21261. }
  21262. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  21263. };
  21264. BaseTexture.prototype.releaseInternalTexture = function () {
  21265. if (this._texture) {
  21266. this._texture.dispose();
  21267. this._texture = null;
  21268. }
  21269. };
  21270. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  21271. get: function () {
  21272. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  21273. return null;
  21274. }
  21275. if (!this._texture._sphericalPolynomial) {
  21276. this._texture._sphericalPolynomial =
  21277. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  21278. }
  21279. return this._texture._sphericalPolynomial;
  21280. },
  21281. set: function (value) {
  21282. if (this._texture) {
  21283. this._texture._sphericalPolynomial = value;
  21284. }
  21285. },
  21286. enumerable: true,
  21287. configurable: true
  21288. });
  21289. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  21290. get: function () {
  21291. if (this._texture) {
  21292. return this._texture._lodTextureHigh;
  21293. }
  21294. return null;
  21295. },
  21296. enumerable: true,
  21297. configurable: true
  21298. });
  21299. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  21300. get: function () {
  21301. if (this._texture) {
  21302. return this._texture._lodTextureMid;
  21303. }
  21304. return null;
  21305. },
  21306. enumerable: true,
  21307. configurable: true
  21308. });
  21309. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  21310. get: function () {
  21311. if (this._texture) {
  21312. return this._texture._lodTextureLow;
  21313. }
  21314. return null;
  21315. },
  21316. enumerable: true,
  21317. configurable: true
  21318. });
  21319. BaseTexture.prototype.dispose = function () {
  21320. if (!this._scene) {
  21321. return;
  21322. }
  21323. // Animations
  21324. this._scene.stopAnimation(this);
  21325. // Remove from scene
  21326. this._scene._removePendingData(this);
  21327. var index = this._scene.textures.indexOf(this);
  21328. if (index >= 0) {
  21329. this._scene.textures.splice(index, 1);
  21330. }
  21331. if (this._texture === undefined) {
  21332. return;
  21333. }
  21334. // Release
  21335. this.releaseInternalTexture();
  21336. // Callback
  21337. this.onDisposeObservable.notifyObservers(this);
  21338. this.onDisposeObservable.clear();
  21339. };
  21340. BaseTexture.prototype.serialize = function () {
  21341. if (!this.name) {
  21342. return null;
  21343. }
  21344. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21345. // Animations
  21346. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21347. return serializationObject;
  21348. };
  21349. BaseTexture.WhenAllReady = function (textures, callback) {
  21350. var numRemaining = textures.length;
  21351. if (numRemaining === 0) {
  21352. callback();
  21353. return;
  21354. }
  21355. var _loop_1 = function () {
  21356. texture = textures[i];
  21357. if (texture.isReady()) {
  21358. if (--numRemaining === 0) {
  21359. callback();
  21360. }
  21361. }
  21362. else {
  21363. onLoadObservable = texture.onLoadObservable;
  21364. var onLoadCallback_1 = function () {
  21365. onLoadObservable.removeCallback(onLoadCallback_1);
  21366. if (--numRemaining === 0) {
  21367. callback();
  21368. }
  21369. };
  21370. onLoadObservable.add(onLoadCallback_1);
  21371. }
  21372. };
  21373. var texture, onLoadObservable;
  21374. for (var i = 0; i < textures.length; i++) {
  21375. _loop_1();
  21376. }
  21377. };
  21378. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  21379. __decorate([
  21380. BABYLON.serialize()
  21381. ], BaseTexture.prototype, "name", void 0);
  21382. __decorate([
  21383. BABYLON.serialize("hasAlpha")
  21384. ], BaseTexture.prototype, "_hasAlpha", void 0);
  21385. __decorate([
  21386. BABYLON.serialize()
  21387. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  21388. __decorate([
  21389. BABYLON.serialize()
  21390. ], BaseTexture.prototype, "level", void 0);
  21391. __decorate([
  21392. BABYLON.serialize()
  21393. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  21394. __decorate([
  21395. BABYLON.serialize("coordinatesMode")
  21396. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  21397. __decorate([
  21398. BABYLON.serialize()
  21399. ], BaseTexture.prototype, "wrapU", void 0);
  21400. __decorate([
  21401. BABYLON.serialize()
  21402. ], BaseTexture.prototype, "wrapV", void 0);
  21403. __decorate([
  21404. BABYLON.serialize()
  21405. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  21406. __decorate([
  21407. BABYLON.serialize()
  21408. ], BaseTexture.prototype, "isCube", void 0);
  21409. __decorate([
  21410. BABYLON.serialize()
  21411. ], BaseTexture.prototype, "gammaSpace", void 0);
  21412. __decorate([
  21413. BABYLON.serialize()
  21414. ], BaseTexture.prototype, "invertZ", void 0);
  21415. __decorate([
  21416. BABYLON.serialize()
  21417. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  21418. __decorate([
  21419. BABYLON.serialize()
  21420. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  21421. __decorate([
  21422. BABYLON.serialize()
  21423. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  21424. __decorate([
  21425. BABYLON.serialize()
  21426. ], BaseTexture.prototype, "isRenderTarget", void 0);
  21427. return BaseTexture;
  21428. }());
  21429. BABYLON.BaseTexture = BaseTexture;
  21430. })(BABYLON || (BABYLON = {}));
  21431. //# sourceMappingURL=babylon.baseTexture.js.map
  21432. var BABYLON;
  21433. (function (BABYLON) {
  21434. var Texture = /** @class */ (function (_super) {
  21435. __extends(Texture, _super);
  21436. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  21437. if (noMipmap === void 0) { noMipmap = false; }
  21438. if (invertY === void 0) { invertY = true; }
  21439. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21440. if (onLoad === void 0) { onLoad = null; }
  21441. if (onError === void 0) { onError = null; }
  21442. if (buffer === void 0) { buffer = null; }
  21443. if (deleteBuffer === void 0) { deleteBuffer = false; }
  21444. var _this = _super.call(this, scene) || this;
  21445. _this.uOffset = 0;
  21446. _this.vOffset = 0;
  21447. _this.uScale = 1.0;
  21448. _this.vScale = 1.0;
  21449. _this.uAng = 0;
  21450. _this.vAng = 0;
  21451. _this.wAng = 0;
  21452. _this._isBlocking = true;
  21453. _this.name = url || "";
  21454. _this.url = url;
  21455. _this._noMipmap = noMipmap;
  21456. _this._invertY = invertY;
  21457. _this._samplingMode = samplingMode;
  21458. _this._buffer = buffer;
  21459. _this._deleteBuffer = deleteBuffer;
  21460. if (format) {
  21461. _this._format = format;
  21462. }
  21463. scene = _this.getScene();
  21464. if (!scene) {
  21465. return _this;
  21466. }
  21467. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  21468. var load = function () {
  21469. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  21470. _this.onLoadObservable.notifyObservers(_this);
  21471. }
  21472. if (onLoad) {
  21473. onLoad();
  21474. }
  21475. if (!_this.isBlocking && scene) {
  21476. scene.resetCachedMaterial();
  21477. }
  21478. };
  21479. if (!_this.url) {
  21480. _this._delayedOnLoad = load;
  21481. _this._delayedOnError = onError;
  21482. return _this;
  21483. }
  21484. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  21485. if (!_this._texture) {
  21486. if (!scene.useDelayedTextureLoading) {
  21487. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  21488. if (deleteBuffer) {
  21489. delete _this._buffer;
  21490. }
  21491. }
  21492. else {
  21493. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21494. _this._delayedOnLoad = load;
  21495. _this._delayedOnError = onError;
  21496. }
  21497. }
  21498. else {
  21499. if (_this._texture.isReady) {
  21500. BABYLON.Tools.SetImmediate(function () { return load(); });
  21501. }
  21502. else {
  21503. _this._texture.onLoadedObservable.add(load);
  21504. }
  21505. }
  21506. return _this;
  21507. }
  21508. Object.defineProperty(Texture.prototype, "noMipmap", {
  21509. get: function () {
  21510. return this._noMipmap;
  21511. },
  21512. enumerable: true,
  21513. configurable: true
  21514. });
  21515. Object.defineProperty(Texture.prototype, "isBlocking", {
  21516. get: function () {
  21517. return this._isBlocking;
  21518. },
  21519. set: function (value) {
  21520. this._isBlocking = value;
  21521. },
  21522. enumerable: true,
  21523. configurable: true
  21524. });
  21525. Object.defineProperty(Texture.prototype, "samplingMode", {
  21526. get: function () {
  21527. return this._samplingMode;
  21528. },
  21529. enumerable: true,
  21530. configurable: true
  21531. });
  21532. Texture.prototype.updateURL = function (url) {
  21533. this.url = url;
  21534. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21535. this.delayLoad();
  21536. };
  21537. Texture.prototype.delayLoad = function () {
  21538. var _this = this;
  21539. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21540. return;
  21541. }
  21542. var scene = this.getScene();
  21543. if (!scene) {
  21544. return;
  21545. }
  21546. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21547. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  21548. if (!this._texture) {
  21549. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  21550. if (this._deleteBuffer) {
  21551. delete this._buffer;
  21552. }
  21553. }
  21554. else {
  21555. if (this._texture.isReady) {
  21556. BABYLON.Tools.SetImmediate(function () {
  21557. if (!_this._delayedOnLoad) {
  21558. return;
  21559. }
  21560. _this._delayedOnLoad();
  21561. });
  21562. }
  21563. else {
  21564. if (this._delayedOnLoad) {
  21565. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  21566. }
  21567. }
  21568. }
  21569. };
  21570. Texture.prototype.updateSamplingMode = function (samplingMode) {
  21571. if (!this._texture) {
  21572. return;
  21573. }
  21574. var scene = this.getScene();
  21575. if (!scene) {
  21576. return;
  21577. }
  21578. this._samplingMode = samplingMode;
  21579. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  21580. };
  21581. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  21582. x *= this.uScale;
  21583. y *= this.vScale;
  21584. x -= 0.5 * this.uScale;
  21585. y -= 0.5 * this.vScale;
  21586. z -= 0.5;
  21587. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  21588. t.x += 0.5 * this.uScale + this.uOffset;
  21589. t.y += 0.5 * this.vScale + this.vOffset;
  21590. t.z += 0.5;
  21591. };
  21592. Texture.prototype.getTextureMatrix = function () {
  21593. var _this = this;
  21594. if (this.uOffset === this._cachedUOffset &&
  21595. this.vOffset === this._cachedVOffset &&
  21596. this.uScale === this._cachedUScale &&
  21597. this.vScale === this._cachedVScale &&
  21598. this.uAng === this._cachedUAng &&
  21599. this.vAng === this._cachedVAng &&
  21600. this.wAng === this._cachedWAng) {
  21601. return this._cachedTextureMatrix;
  21602. }
  21603. this._cachedUOffset = this.uOffset;
  21604. this._cachedVOffset = this.vOffset;
  21605. this._cachedUScale = this.uScale;
  21606. this._cachedVScale = this.vScale;
  21607. this._cachedUAng = this.uAng;
  21608. this._cachedVAng = this.vAng;
  21609. this._cachedWAng = this.wAng;
  21610. if (!this._cachedTextureMatrix) {
  21611. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21612. this._rowGenerationMatrix = new BABYLON.Matrix();
  21613. this._t0 = BABYLON.Vector3.Zero();
  21614. this._t1 = BABYLON.Vector3.Zero();
  21615. this._t2 = BABYLON.Vector3.Zero();
  21616. }
  21617. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  21618. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  21619. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  21620. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  21621. this._t1.subtractInPlace(this._t0);
  21622. this._t2.subtractInPlace(this._t0);
  21623. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21624. this._cachedTextureMatrix.m[0] = this._t1.x;
  21625. this._cachedTextureMatrix.m[1] = this._t1.y;
  21626. this._cachedTextureMatrix.m[2] = this._t1.z;
  21627. this._cachedTextureMatrix.m[4] = this._t2.x;
  21628. this._cachedTextureMatrix.m[5] = this._t2.y;
  21629. this._cachedTextureMatrix.m[6] = this._t2.z;
  21630. this._cachedTextureMatrix.m[8] = this._t0.x;
  21631. this._cachedTextureMatrix.m[9] = this._t0.y;
  21632. this._cachedTextureMatrix.m[10] = this._t0.z;
  21633. var scene = this.getScene();
  21634. if (!scene) {
  21635. return this._cachedTextureMatrix;
  21636. }
  21637. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  21638. return mat.hasTexture(_this);
  21639. });
  21640. return this._cachedTextureMatrix;
  21641. };
  21642. Texture.prototype.getReflectionTextureMatrix = function () {
  21643. var _this = this;
  21644. var scene = this.getScene();
  21645. if (!scene) {
  21646. return this._cachedTextureMatrix;
  21647. }
  21648. if (this.uOffset === this._cachedUOffset &&
  21649. this.vOffset === this._cachedVOffset &&
  21650. this.uScale === this._cachedUScale &&
  21651. this.vScale === this._cachedVScale &&
  21652. this.coordinatesMode === this._cachedCoordinatesMode) {
  21653. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  21654. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  21655. return this._cachedTextureMatrix;
  21656. }
  21657. }
  21658. else {
  21659. return this._cachedTextureMatrix;
  21660. }
  21661. }
  21662. if (!this._cachedTextureMatrix) {
  21663. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21664. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  21665. }
  21666. this._cachedUOffset = this.uOffset;
  21667. this._cachedVOffset = this.vOffset;
  21668. this._cachedUScale = this.uScale;
  21669. this._cachedVScale = this.vScale;
  21670. this._cachedCoordinatesMode = this.coordinatesMode;
  21671. switch (this.coordinatesMode) {
  21672. case Texture.PLANAR_MODE:
  21673. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21674. this._cachedTextureMatrix[0] = this.uScale;
  21675. this._cachedTextureMatrix[5] = this.vScale;
  21676. this._cachedTextureMatrix[12] = this.uOffset;
  21677. this._cachedTextureMatrix[13] = this.vOffset;
  21678. break;
  21679. case Texture.PROJECTION_MODE:
  21680. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  21681. this._projectionModeMatrix.m[0] = 0.5;
  21682. this._projectionModeMatrix.m[5] = -0.5;
  21683. this._projectionModeMatrix.m[10] = 0.0;
  21684. this._projectionModeMatrix.m[12] = 0.5;
  21685. this._projectionModeMatrix.m[13] = 0.5;
  21686. this._projectionModeMatrix.m[14] = 1.0;
  21687. this._projectionModeMatrix.m[15] = 1.0;
  21688. var projectionMatrix = scene.getProjectionMatrix();
  21689. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  21690. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  21691. break;
  21692. default:
  21693. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21694. break;
  21695. }
  21696. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  21697. return (mat.getActiveTextures().indexOf(_this) !== -1);
  21698. });
  21699. return this._cachedTextureMatrix;
  21700. };
  21701. Texture.prototype.clone = function () {
  21702. var _this = this;
  21703. return BABYLON.SerializationHelper.Clone(function () {
  21704. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  21705. }, this);
  21706. };
  21707. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  21708. get: function () {
  21709. if (!this._onLoadObservable) {
  21710. this._onLoadObservable = new BABYLON.Observable();
  21711. }
  21712. return this._onLoadObservable;
  21713. },
  21714. enumerable: true,
  21715. configurable: true
  21716. });
  21717. Texture.prototype.serialize = function () {
  21718. var serializationObject = _super.prototype.serialize.call(this);
  21719. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  21720. serializationObject.base64String = this._buffer;
  21721. serializationObject.name = serializationObject.name.replace("data:", "");
  21722. }
  21723. return serializationObject;
  21724. };
  21725. Texture.prototype.getClassName = function () {
  21726. return "Texture";
  21727. };
  21728. Texture.prototype.dispose = function () {
  21729. _super.prototype.dispose.call(this);
  21730. if (this.onLoadObservable) {
  21731. this.onLoadObservable.clear();
  21732. this._onLoadObservable = null;
  21733. }
  21734. this._delayedOnLoad = null;
  21735. this._delayedOnError = null;
  21736. };
  21737. // Statics
  21738. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  21739. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21740. if (onLoad === void 0) { onLoad = null; }
  21741. if (onError === void 0) { onError = null; }
  21742. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  21743. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  21744. };
  21745. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  21746. if (parsedTexture.customType) {
  21747. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  21748. // Update Sampling Mode
  21749. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  21750. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  21751. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  21752. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  21753. }
  21754. }
  21755. return parsedCustomTexture;
  21756. }
  21757. if (parsedTexture.isCube) {
  21758. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  21759. }
  21760. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  21761. return null;
  21762. }
  21763. var texture = BABYLON.SerializationHelper.Parse(function () {
  21764. if (parsedTexture.mirrorPlane) {
  21765. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21766. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  21767. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  21768. return mirrorTexture;
  21769. }
  21770. else if (parsedTexture.isRenderTarget) {
  21771. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21772. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  21773. return renderTargetTexture;
  21774. }
  21775. else {
  21776. var texture;
  21777. if (parsedTexture.base64String) {
  21778. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  21779. }
  21780. else {
  21781. texture = new Texture(rootUrl + parsedTexture.name, scene);
  21782. }
  21783. return texture;
  21784. }
  21785. }, parsedTexture, scene);
  21786. // Update Sampling Mode
  21787. if (parsedTexture.samplingMode) {
  21788. var sampling = parsedTexture.samplingMode;
  21789. if (texture._samplingMode !== sampling) {
  21790. texture.updateSamplingMode(sampling);
  21791. }
  21792. }
  21793. // Animations
  21794. if (parsedTexture.animations) {
  21795. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  21796. var parsedAnimation = parsedTexture.animations[animationIndex];
  21797. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21798. }
  21799. }
  21800. return texture;
  21801. };
  21802. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  21803. if (deleteBuffer === void 0) { deleteBuffer = false; }
  21804. if (noMipmap === void 0) { noMipmap = false; }
  21805. if (invertY === void 0) { invertY = true; }
  21806. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21807. if (onLoad === void 0) { onLoad = null; }
  21808. if (onError === void 0) { onError = null; }
  21809. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  21810. if (name.substr(0, 5) !== "data:") {
  21811. name = "data:" + name;
  21812. }
  21813. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  21814. };
  21815. // Constants
  21816. Texture.NEAREST_SAMPLINGMODE = 1;
  21817. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  21818. Texture.BILINEAR_SAMPLINGMODE = 2;
  21819. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  21820. Texture.TRILINEAR_SAMPLINGMODE = 3;
  21821. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  21822. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  21823. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  21824. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  21825. Texture.NEAREST_LINEAR = 7;
  21826. Texture.NEAREST_NEAREST = 8;
  21827. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  21828. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  21829. Texture.LINEAR_LINEAR = 11;
  21830. Texture.LINEAR_NEAREST = 12;
  21831. Texture.EXPLICIT_MODE = 0;
  21832. Texture.SPHERICAL_MODE = 1;
  21833. Texture.PLANAR_MODE = 2;
  21834. Texture.CUBIC_MODE = 3;
  21835. Texture.PROJECTION_MODE = 4;
  21836. Texture.SKYBOX_MODE = 5;
  21837. Texture.INVCUBIC_MODE = 6;
  21838. Texture.EQUIRECTANGULAR_MODE = 7;
  21839. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  21840. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  21841. Texture.CLAMP_ADDRESSMODE = 0;
  21842. Texture.WRAP_ADDRESSMODE = 1;
  21843. Texture.MIRROR_ADDRESSMODE = 2;
  21844. __decorate([
  21845. BABYLON.serialize()
  21846. ], Texture.prototype, "url", void 0);
  21847. __decorate([
  21848. BABYLON.serialize()
  21849. ], Texture.prototype, "uOffset", void 0);
  21850. __decorate([
  21851. BABYLON.serialize()
  21852. ], Texture.prototype, "vOffset", void 0);
  21853. __decorate([
  21854. BABYLON.serialize()
  21855. ], Texture.prototype, "uScale", void 0);
  21856. __decorate([
  21857. BABYLON.serialize()
  21858. ], Texture.prototype, "vScale", void 0);
  21859. __decorate([
  21860. BABYLON.serialize()
  21861. ], Texture.prototype, "uAng", void 0);
  21862. __decorate([
  21863. BABYLON.serialize()
  21864. ], Texture.prototype, "vAng", void 0);
  21865. __decorate([
  21866. BABYLON.serialize()
  21867. ], Texture.prototype, "wAng", void 0);
  21868. __decorate([
  21869. BABYLON.serialize()
  21870. ], Texture.prototype, "isBlocking", null);
  21871. return Texture;
  21872. }(BABYLON.BaseTexture));
  21873. BABYLON.Texture = Texture;
  21874. })(BABYLON || (BABYLON = {}));
  21875. //# sourceMappingURL=babylon.texture.js.map
  21876. var BABYLON;
  21877. (function (BABYLON) {
  21878. var _InstancesBatch = /** @class */ (function () {
  21879. function _InstancesBatch() {
  21880. this.mustReturn = false;
  21881. this.visibleInstances = new Array();
  21882. this.renderSelf = new Array();
  21883. }
  21884. return _InstancesBatch;
  21885. }());
  21886. BABYLON._InstancesBatch = _InstancesBatch;
  21887. var Mesh = /** @class */ (function (_super) {
  21888. __extends(Mesh, _super);
  21889. /**
  21890. * @constructor
  21891. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  21892. * @param {Scene} scene The scene to add this mesh to.
  21893. * @param {Node} parent The parent of this mesh, if it has one
  21894. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  21895. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  21896. * When false, achieved by calling a clone(), also passing False.
  21897. * This will make creation of children, recursive.
  21898. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  21899. */
  21900. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  21901. if (parent === void 0) { parent = null; }
  21902. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  21903. var _this = _super.call(this, name, scene) || this;
  21904. // Events
  21905. /**
  21906. * An event triggered before rendering the mesh
  21907. * @type {BABYLON.Observable}
  21908. */
  21909. _this.onBeforeRenderObservable = new BABYLON.Observable();
  21910. /**
  21911. * An event triggered after rendering the mesh
  21912. * @type {BABYLON.Observable}
  21913. */
  21914. _this.onAfterRenderObservable = new BABYLON.Observable();
  21915. /**
  21916. * An event triggered before drawing the mesh
  21917. * @type {BABYLON.Observable}
  21918. */
  21919. _this.onBeforeDrawObservable = new BABYLON.Observable();
  21920. // Members
  21921. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21922. _this.instances = new Array();
  21923. _this._LODLevels = new Array();
  21924. _this._visibleInstances = {};
  21925. _this._renderIdForInstances = new Array();
  21926. _this._batchCache = new _InstancesBatch();
  21927. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  21928. // Use by builder only to know what orientation were the mesh build in.
  21929. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  21930. _this.overrideMaterialSideOrientation = null;
  21931. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  21932. // Will be used to save a source mesh reference, If any
  21933. _this._source = null;
  21934. if (source) {
  21935. // Source mesh
  21936. _this._source = source;
  21937. // Geometry
  21938. if (source._geometry) {
  21939. source._geometry.applyToMesh(_this);
  21940. }
  21941. // Deep copy
  21942. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  21943. // Parent
  21944. _this.parent = source.parent;
  21945. // Pivot
  21946. _this.setPivotMatrix(source.getPivotMatrix());
  21947. _this.id = name + "." + source.id;
  21948. // Material
  21949. _this.material = source.material;
  21950. var index;
  21951. if (!doNotCloneChildren) {
  21952. // Children
  21953. for (index = 0; index < scene.meshes.length; index++) {
  21954. var mesh = scene.meshes[index];
  21955. if (mesh.parent === source) {
  21956. // doNotCloneChildren is always going to be False
  21957. mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  21958. }
  21959. }
  21960. }
  21961. // Physics clone
  21962. var physicsEngine = _this.getScene().getPhysicsEngine();
  21963. if (clonePhysicsImpostor && physicsEngine) {
  21964. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  21965. if (impostor) {
  21966. _this.physicsImpostor = impostor.clone(_this);
  21967. }
  21968. }
  21969. // Particles
  21970. for (index = 0; index < scene.particleSystems.length; index++) {
  21971. var system = scene.particleSystems[index];
  21972. if (system.emitter === source) {
  21973. system.clone(system.name, _this);
  21974. }
  21975. }
  21976. _this.computeWorldMatrix(true);
  21977. }
  21978. // Parent
  21979. if (parent !== null) {
  21980. _this.parent = parent;
  21981. }
  21982. return _this;
  21983. }
  21984. Object.defineProperty(Mesh, "FRONTSIDE", {
  21985. /**
  21986. * Mesh side orientation : usually the external or front surface
  21987. */
  21988. get: function () {
  21989. return Mesh._FRONTSIDE;
  21990. },
  21991. enumerable: true,
  21992. configurable: true
  21993. });
  21994. Object.defineProperty(Mesh, "BACKSIDE", {
  21995. /**
  21996. * Mesh side orientation : usually the internal or back surface
  21997. */
  21998. get: function () {
  21999. return Mesh._BACKSIDE;
  22000. },
  22001. enumerable: true,
  22002. configurable: true
  22003. });
  22004. Object.defineProperty(Mesh, "DOUBLESIDE", {
  22005. /**
  22006. * Mesh side orientation : both internal and external or front and back surfaces
  22007. */
  22008. get: function () {
  22009. return Mesh._DOUBLESIDE;
  22010. },
  22011. enumerable: true,
  22012. configurable: true
  22013. });
  22014. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  22015. /**
  22016. * Mesh side orientation : by default, `FRONTSIDE`
  22017. */
  22018. get: function () {
  22019. return Mesh._DEFAULTSIDE;
  22020. },
  22021. enumerable: true,
  22022. configurable: true
  22023. });
  22024. Object.defineProperty(Mesh, "NO_CAP", {
  22025. /**
  22026. * Mesh cap setting : no cap
  22027. */
  22028. get: function () {
  22029. return Mesh._NO_CAP;
  22030. },
  22031. enumerable: true,
  22032. configurable: true
  22033. });
  22034. Object.defineProperty(Mesh, "CAP_START", {
  22035. /**
  22036. * Mesh cap setting : one cap at the beginning of the mesh
  22037. */
  22038. get: function () {
  22039. return Mesh._CAP_START;
  22040. },
  22041. enumerable: true,
  22042. configurable: true
  22043. });
  22044. Object.defineProperty(Mesh, "CAP_END", {
  22045. /**
  22046. * Mesh cap setting : one cap at the end of the mesh
  22047. */
  22048. get: function () {
  22049. return Mesh._CAP_END;
  22050. },
  22051. enumerable: true,
  22052. configurable: true
  22053. });
  22054. Object.defineProperty(Mesh, "CAP_ALL", {
  22055. /**
  22056. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  22057. */
  22058. get: function () {
  22059. return Mesh._CAP_ALL;
  22060. },
  22061. enumerable: true,
  22062. configurable: true
  22063. });
  22064. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  22065. set: function (callback) {
  22066. if (this._onBeforeDrawObserver) {
  22067. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  22068. }
  22069. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  22070. },
  22071. enumerable: true,
  22072. configurable: true
  22073. });
  22074. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  22075. get: function () {
  22076. return this._morphTargetManager;
  22077. },
  22078. set: function (value) {
  22079. if (this._morphTargetManager === value) {
  22080. return;
  22081. }
  22082. this._morphTargetManager = value;
  22083. this._syncGeometryWithMorphTargetManager();
  22084. },
  22085. enumerable: true,
  22086. configurable: true
  22087. });
  22088. Object.defineProperty(Mesh.prototype, "source", {
  22089. get: function () {
  22090. return this._source;
  22091. },
  22092. enumerable: true,
  22093. configurable: true
  22094. });
  22095. // Methods
  22096. /**
  22097. * Returns the string "Mesh".
  22098. */
  22099. Mesh.prototype.getClassName = function () {
  22100. return "Mesh";
  22101. };
  22102. /**
  22103. * Returns a string.
  22104. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22105. */
  22106. Mesh.prototype.toString = function (fullDetails) {
  22107. var ret = _super.prototype.toString.call(this, fullDetails);
  22108. ret += ", n vertices: " + this.getTotalVertices();
  22109. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  22110. if (this.animations) {
  22111. for (var i = 0; i < this.animations.length; i++) {
  22112. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22113. }
  22114. }
  22115. if (fullDetails) {
  22116. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  22117. }
  22118. return ret;
  22119. };
  22120. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  22121. /**
  22122. * True if the mesh has some Levels Of Details (LOD).
  22123. * Returns a boolean.
  22124. */
  22125. get: function () {
  22126. return this._LODLevels.length > 0;
  22127. },
  22128. enumerable: true,
  22129. configurable: true
  22130. });
  22131. Mesh.prototype._sortLODLevels = function () {
  22132. this._LODLevels.sort(function (a, b) {
  22133. if (a.distance < b.distance) {
  22134. return 1;
  22135. }
  22136. if (a.distance > b.distance) {
  22137. return -1;
  22138. }
  22139. return 0;
  22140. });
  22141. };
  22142. /**
  22143. * Add a mesh as LOD level triggered at the given distance.
  22144. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22145. * @param {number} distance The distance from the center of the object to show this level
  22146. * @param {Mesh} mesh The mesh to be added as LOD level
  22147. * @return {Mesh} This mesh (for chaining)
  22148. */
  22149. Mesh.prototype.addLODLevel = function (distance, mesh) {
  22150. if (mesh && mesh._masterMesh) {
  22151. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  22152. return this;
  22153. }
  22154. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  22155. this._LODLevels.push(level);
  22156. if (mesh) {
  22157. mesh._masterMesh = this;
  22158. }
  22159. this._sortLODLevels();
  22160. return this;
  22161. };
  22162. /**
  22163. * Returns the LOD level mesh at the passed distance or null if not found.
  22164. * It is related to the method `addLODLevel(distance, mesh)`.
  22165. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22166. * Returns an object Mesh or `null`.
  22167. */
  22168. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  22169. for (var index = 0; index < this._LODLevels.length; index++) {
  22170. var level = this._LODLevels[index];
  22171. if (level.distance === distance) {
  22172. return level.mesh;
  22173. }
  22174. }
  22175. return null;
  22176. };
  22177. /**
  22178. * Remove a mesh from the LOD array
  22179. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22180. * @param {Mesh} mesh The mesh to be removed.
  22181. * @return {Mesh} This mesh (for chaining)
  22182. */
  22183. Mesh.prototype.removeLODLevel = function (mesh) {
  22184. for (var index = 0; index < this._LODLevels.length; index++) {
  22185. if (this._LODLevels[index].mesh === mesh) {
  22186. this._LODLevels.splice(index, 1);
  22187. if (mesh) {
  22188. mesh._masterMesh = null;
  22189. }
  22190. }
  22191. }
  22192. this._sortLODLevels();
  22193. return this;
  22194. };
  22195. /**
  22196. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  22197. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22198. */
  22199. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  22200. if (!this._LODLevels || this._LODLevels.length === 0) {
  22201. return this;
  22202. }
  22203. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  22204. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  22205. if (this.onLODLevelSelection) {
  22206. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  22207. }
  22208. return this;
  22209. }
  22210. for (var index = 0; index < this._LODLevels.length; index++) {
  22211. var level = this._LODLevels[index];
  22212. if (level.distance < distanceToCamera) {
  22213. if (level.mesh) {
  22214. level.mesh._preActivate();
  22215. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  22216. }
  22217. if (this.onLODLevelSelection) {
  22218. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  22219. }
  22220. return level.mesh;
  22221. }
  22222. }
  22223. if (this.onLODLevelSelection) {
  22224. this.onLODLevelSelection(distanceToCamera, this, this);
  22225. }
  22226. return this;
  22227. };
  22228. Object.defineProperty(Mesh.prototype, "geometry", {
  22229. /**
  22230. * Returns the mesh internal Geometry object.
  22231. */
  22232. get: function () {
  22233. return this._geometry;
  22234. },
  22235. enumerable: true,
  22236. configurable: true
  22237. });
  22238. /**
  22239. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  22240. */
  22241. Mesh.prototype.getTotalVertices = function () {
  22242. if (!this._geometry) {
  22243. return 0;
  22244. }
  22245. return this._geometry.getTotalVertices();
  22246. };
  22247. /**
  22248. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  22249. * 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.
  22250. * You can force the copy with forceCopy === true
  22251. * Returns null if the mesh has no geometry or no vertex buffer.
  22252. * Possible `kind` values :
  22253. * - BABYLON.VertexBuffer.PositionKind
  22254. * - BABYLON.VertexBuffer.UVKind
  22255. * - BABYLON.VertexBuffer.UV2Kind
  22256. * - BABYLON.VertexBuffer.UV3Kind
  22257. * - BABYLON.VertexBuffer.UV4Kind
  22258. * - BABYLON.VertexBuffer.UV5Kind
  22259. * - BABYLON.VertexBuffer.UV6Kind
  22260. * - BABYLON.VertexBuffer.ColorKind
  22261. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22262. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22263. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22264. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22265. */
  22266. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  22267. if (!this._geometry) {
  22268. return null;
  22269. }
  22270. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  22271. };
  22272. /**
  22273. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  22274. * Returns `undefined` if the mesh has no geometry.
  22275. * Possible `kind` values :
  22276. * - BABYLON.VertexBuffer.PositionKind
  22277. * - BABYLON.VertexBuffer.UVKind
  22278. * - BABYLON.VertexBuffer.UV2Kind
  22279. * - BABYLON.VertexBuffer.UV3Kind
  22280. * - BABYLON.VertexBuffer.UV4Kind
  22281. * - BABYLON.VertexBuffer.UV5Kind
  22282. * - BABYLON.VertexBuffer.UV6Kind
  22283. * - BABYLON.VertexBuffer.ColorKind
  22284. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22285. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22286. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22287. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22288. */
  22289. Mesh.prototype.getVertexBuffer = function (kind) {
  22290. if (!this._geometry) {
  22291. return undefined;
  22292. }
  22293. return this._geometry.getVertexBuffer(kind);
  22294. };
  22295. /**
  22296. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  22297. * Possible `kind` values :
  22298. * - BABYLON.VertexBuffer.PositionKind
  22299. * - BABYLON.VertexBuffer.UVKind
  22300. * - BABYLON.VertexBuffer.UV2Kind
  22301. * - BABYLON.VertexBuffer.UV3Kind
  22302. * - BABYLON.VertexBuffer.UV4Kind
  22303. * - BABYLON.VertexBuffer.UV5Kind
  22304. * - BABYLON.VertexBuffer.UV6Kind
  22305. * - BABYLON.VertexBuffer.ColorKind
  22306. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22307. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22308. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22309. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22310. */
  22311. Mesh.prototype.isVerticesDataPresent = function (kind) {
  22312. if (!this._geometry) {
  22313. if (this._delayInfo) {
  22314. return this._delayInfo.indexOf(kind) !== -1;
  22315. }
  22316. return false;
  22317. }
  22318. return this._geometry.isVerticesDataPresent(kind);
  22319. };
  22320. /**
  22321. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  22322. * Possible `kind` values :
  22323. * - BABYLON.VertexBuffer.PositionKind
  22324. * - BABYLON.VertexBuffer.UVKind
  22325. * - BABYLON.VertexBuffer.UV2Kind
  22326. * - BABYLON.VertexBuffer.UV3Kind
  22327. * - BABYLON.VertexBuffer.UV4Kind
  22328. * - BABYLON.VertexBuffer.UV5Kind
  22329. * - BABYLON.VertexBuffer.UV6Kind
  22330. * - BABYLON.VertexBuffer.ColorKind
  22331. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22332. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22333. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22334. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22335. */
  22336. Mesh.prototype.getVerticesDataKinds = function () {
  22337. if (!this._geometry) {
  22338. var result = new Array();
  22339. if (this._delayInfo) {
  22340. this._delayInfo.forEach(function (kind, index, array) {
  22341. result.push(kind);
  22342. });
  22343. }
  22344. return result;
  22345. }
  22346. return this._geometry.getVerticesDataKinds();
  22347. };
  22348. /**
  22349. * Returns a positive integer : the total number of indices in this mesh geometry.
  22350. * Returns zero if the mesh has no geometry.
  22351. */
  22352. Mesh.prototype.getTotalIndices = function () {
  22353. if (!this._geometry) {
  22354. return 0;
  22355. }
  22356. return this._geometry.getTotalIndices();
  22357. };
  22358. /**
  22359. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  22360. * 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.
  22361. * Returns an empty array if the mesh has no geometry.
  22362. */
  22363. Mesh.prototype.getIndices = function (copyWhenShared) {
  22364. if (!this._geometry) {
  22365. return [];
  22366. }
  22367. return this._geometry.getIndices(copyWhenShared);
  22368. };
  22369. Object.defineProperty(Mesh.prototype, "isBlocked", {
  22370. get: function () {
  22371. return this._masterMesh !== null && this._masterMesh !== undefined;
  22372. },
  22373. enumerable: true,
  22374. configurable: true
  22375. });
  22376. /**
  22377. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  22378. */
  22379. Mesh.prototype.isReady = function () {
  22380. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22381. return false;
  22382. }
  22383. return _super.prototype.isReady.call(this);
  22384. };
  22385. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  22386. /**
  22387. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  22388. * This property is pertinent only for updatable parametric shapes.
  22389. */
  22390. get: function () {
  22391. return this._areNormalsFrozen;
  22392. },
  22393. enumerable: true,
  22394. configurable: true
  22395. });
  22396. /**
  22397. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  22398. * It has no effect at all on other shapes.
  22399. * It prevents the mesh normals from being recomputed on next `positions` array update.
  22400. * Returns the Mesh.
  22401. */
  22402. Mesh.prototype.freezeNormals = function () {
  22403. this._areNormalsFrozen = true;
  22404. return this;
  22405. };
  22406. /**
  22407. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  22408. * It has no effect at all on other shapes.
  22409. * It reactivates the mesh normals computation if it was previously frozen.
  22410. * Returns the Mesh.
  22411. */
  22412. Mesh.prototype.unfreezeNormals = function () {
  22413. this._areNormalsFrozen = false;
  22414. return this;
  22415. };
  22416. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  22417. /**
  22418. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  22419. */
  22420. set: function (count) {
  22421. this._overridenInstanceCount = count;
  22422. },
  22423. enumerable: true,
  22424. configurable: true
  22425. });
  22426. // Methods
  22427. Mesh.prototype._preActivate = function () {
  22428. var sceneRenderId = this.getScene().getRenderId();
  22429. if (this._preActivateId === sceneRenderId) {
  22430. return this;
  22431. }
  22432. this._preActivateId = sceneRenderId;
  22433. this._visibleInstances = null;
  22434. return this;
  22435. };
  22436. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  22437. if (this._visibleInstances) {
  22438. this._visibleInstances.intermediateDefaultRenderId = renderId;
  22439. }
  22440. return this;
  22441. };
  22442. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  22443. if (!this._visibleInstances) {
  22444. this._visibleInstances = {};
  22445. this._visibleInstances.defaultRenderId = renderId;
  22446. this._visibleInstances.selfDefaultRenderId = this._renderId;
  22447. }
  22448. if (!this._visibleInstances[renderId]) {
  22449. this._visibleInstances[renderId] = new Array();
  22450. }
  22451. this._visibleInstances[renderId].push(instance);
  22452. return this;
  22453. };
  22454. /**
  22455. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  22456. * This means the mesh underlying bounding box and sphere are recomputed.
  22457. * Returns the Mesh.
  22458. */
  22459. Mesh.prototype.refreshBoundingInfo = function () {
  22460. if (this._boundingInfo.isLocked) {
  22461. return this;
  22462. }
  22463. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22464. if (data) {
  22465. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  22466. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22467. }
  22468. if (this.subMeshes) {
  22469. for (var index = 0; index < this.subMeshes.length; index++) {
  22470. this.subMeshes[index].refreshBoundingInfo();
  22471. }
  22472. }
  22473. this._updateBoundingInfo();
  22474. return this;
  22475. };
  22476. Mesh.prototype._createGlobalSubMesh = function (force) {
  22477. var totalVertices = this.getTotalVertices();
  22478. if (!totalVertices || !this.getIndices()) {
  22479. return null;
  22480. }
  22481. // Check if we need to recreate the submeshes
  22482. if (this.subMeshes && this.subMeshes.length > 0) {
  22483. var totalIndices = this.getIndices().length;
  22484. var needToRecreate = false;
  22485. if (force) {
  22486. needToRecreate = true;
  22487. }
  22488. else {
  22489. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  22490. var submesh = _a[_i];
  22491. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  22492. needToRecreate = true;
  22493. break;
  22494. }
  22495. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  22496. needToRecreate = true;
  22497. break;
  22498. }
  22499. }
  22500. }
  22501. if (!needToRecreate) {
  22502. return this.subMeshes[0];
  22503. }
  22504. }
  22505. this.releaseSubMeshes();
  22506. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  22507. };
  22508. Mesh.prototype.subdivide = function (count) {
  22509. if (count < 1) {
  22510. return;
  22511. }
  22512. var totalIndices = this.getTotalIndices();
  22513. var subdivisionSize = (totalIndices / count) | 0;
  22514. var offset = 0;
  22515. // Ensure that subdivisionSize is a multiple of 3
  22516. while (subdivisionSize % 3 !== 0) {
  22517. subdivisionSize++;
  22518. }
  22519. this.releaseSubMeshes();
  22520. for (var index = 0; index < count; index++) {
  22521. if (offset >= totalIndices) {
  22522. break;
  22523. }
  22524. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  22525. offset += subdivisionSize;
  22526. }
  22527. this.synchronizeInstances();
  22528. };
  22529. /**
  22530. * Sets the vertex data of the mesh geometry for the requested `kind`.
  22531. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  22532. * The `data` are either a numeric array either a Float32Array.
  22533. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  22534. * 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).
  22535. * Note that a new underlying VertexBuffer object is created each call.
  22536. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  22537. *
  22538. * Possible `kind` values :
  22539. * - BABYLON.VertexBuffer.PositionKind
  22540. * - BABYLON.VertexBuffer.UVKind
  22541. * - BABYLON.VertexBuffer.UV2Kind
  22542. * - BABYLON.VertexBuffer.UV3Kind
  22543. * - BABYLON.VertexBuffer.UV4Kind
  22544. * - BABYLON.VertexBuffer.UV5Kind
  22545. * - BABYLON.VertexBuffer.UV6Kind
  22546. * - BABYLON.VertexBuffer.ColorKind
  22547. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22548. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22549. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22550. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22551. *
  22552. * Returns the Mesh.
  22553. */
  22554. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  22555. if (updatable === void 0) { updatable = false; }
  22556. if (!this._geometry) {
  22557. var vertexData = new BABYLON.VertexData();
  22558. vertexData.set(data, kind);
  22559. var scene = this.getScene();
  22560. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  22561. }
  22562. else {
  22563. this._geometry.setVerticesData(kind, data, updatable, stride);
  22564. }
  22565. return this;
  22566. };
  22567. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  22568. if (updatable === void 0) { updatable = true; }
  22569. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  22570. return;
  22571. }
  22572. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  22573. };
  22574. /**
  22575. * Sets the mesh VertexBuffer.
  22576. * Returns the Mesh.
  22577. */
  22578. Mesh.prototype.setVerticesBuffer = function (buffer) {
  22579. if (!this._geometry) {
  22580. var scene = this.getScene();
  22581. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  22582. }
  22583. this._geometry.setVerticesBuffer(buffer);
  22584. return this;
  22585. };
  22586. /**
  22587. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  22588. * If the mesh has no geometry, it is simply returned as it is.
  22589. * The `data` are either a numeric array either a Float32Array.
  22590. * No new underlying VertexBuffer object is created.
  22591. * 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.
  22592. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  22593. *
  22594. * Possible `kind` values :
  22595. * - BABYLON.VertexBuffer.PositionKind
  22596. * - BABYLON.VertexBuffer.UVKind
  22597. * - BABYLON.VertexBuffer.UV2Kind
  22598. * - BABYLON.VertexBuffer.UV3Kind
  22599. * - BABYLON.VertexBuffer.UV4Kind
  22600. * - BABYLON.VertexBuffer.UV5Kind
  22601. * - BABYLON.VertexBuffer.UV6Kind
  22602. * - BABYLON.VertexBuffer.ColorKind
  22603. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22604. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22605. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22606. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22607. *
  22608. * Returns the Mesh.
  22609. */
  22610. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  22611. if (!this._geometry) {
  22612. return this;
  22613. }
  22614. if (!makeItUnique) {
  22615. this._geometry.updateVerticesData(kind, data, updateExtends);
  22616. }
  22617. else {
  22618. this.makeGeometryUnique();
  22619. this.updateVerticesData(kind, data, updateExtends, false);
  22620. }
  22621. return this;
  22622. };
  22623. /**
  22624. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  22625. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  22626. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  22627. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  22628. * Returns the Mesh.
  22629. */
  22630. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  22631. if (computeNormals === void 0) { computeNormals = true; }
  22632. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22633. positionFunction(positions);
  22634. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  22635. if (computeNormals) {
  22636. var indices = this.getIndices();
  22637. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22638. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  22639. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  22640. }
  22641. return this;
  22642. };
  22643. /**
  22644. * Creates a un-shared specific occurence of the geometry for the mesh.
  22645. * Returns the Mesh.
  22646. */
  22647. Mesh.prototype.makeGeometryUnique = function () {
  22648. if (!this._geometry) {
  22649. return this;
  22650. }
  22651. var oldGeometry = this._geometry;
  22652. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  22653. oldGeometry.releaseForMesh(this, true);
  22654. geometry.applyToMesh(this);
  22655. return this;
  22656. };
  22657. /**
  22658. * Sets the mesh indices.
  22659. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  22660. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  22661. * This method creates a new index buffer each call.
  22662. * Returns the Mesh.
  22663. */
  22664. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  22665. if (totalVertices === void 0) { totalVertices = null; }
  22666. if (updatable === void 0) { updatable = false; }
  22667. if (!this._geometry) {
  22668. var vertexData = new BABYLON.VertexData();
  22669. vertexData.indices = indices;
  22670. var scene = this.getScene();
  22671. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  22672. }
  22673. else {
  22674. this._geometry.setIndices(indices, totalVertices, updatable);
  22675. }
  22676. return this;
  22677. };
  22678. /**
  22679. * Update the current index buffer
  22680. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  22681. * Returns the Mesh.
  22682. */
  22683. Mesh.prototype.updateIndices = function (indices, offset) {
  22684. if (!this._geometry) {
  22685. return this;
  22686. }
  22687. this._geometry.updateIndices(indices, offset);
  22688. return this;
  22689. };
  22690. /**
  22691. * Invert the geometry to move from a right handed system to a left handed one.
  22692. * Returns the Mesh.
  22693. */
  22694. Mesh.prototype.toLeftHanded = function () {
  22695. if (!this._geometry) {
  22696. return this;
  22697. }
  22698. this._geometry.toLeftHanded();
  22699. return this;
  22700. };
  22701. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  22702. var engine = this.getScene().getEngine();
  22703. // Wireframe
  22704. var indexToBind;
  22705. if (this._unIndexed) {
  22706. indexToBind = null;
  22707. }
  22708. else {
  22709. switch (fillMode) {
  22710. case BABYLON.Material.PointFillMode:
  22711. indexToBind = null;
  22712. break;
  22713. case BABYLON.Material.WireFrameFillMode:
  22714. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  22715. break;
  22716. default:
  22717. case BABYLON.Material.TriangleFillMode:
  22718. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  22719. break;
  22720. }
  22721. }
  22722. // VBOs
  22723. this._geometry._bind(effect, indexToBind);
  22724. return this;
  22725. };
  22726. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  22727. if (alternate === void 0) { alternate = false; }
  22728. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  22729. return this;
  22730. }
  22731. this.onBeforeDrawObservable.notifyObservers(this);
  22732. var scene = this.getScene();
  22733. var engine = scene.getEngine();
  22734. // Draw order
  22735. switch (fillMode) {
  22736. case BABYLON.Material.PointFillMode:
  22737. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  22738. break;
  22739. case BABYLON.Material.WireFrameFillMode:
  22740. if (this._unIndexed) {
  22741. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  22742. }
  22743. else {
  22744. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  22745. }
  22746. break;
  22747. default:
  22748. if (this._unIndexed) {
  22749. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  22750. }
  22751. else {
  22752. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  22753. }
  22754. }
  22755. if (scene._isAlternateRenderingEnabled && !alternate) {
  22756. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  22757. scene._switchToAlternateCameraConfiguration(true);
  22758. this._effectiveMaterial.bindView(effect);
  22759. this._effectiveMaterial.bindViewProjection(effect);
  22760. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  22761. this._draw(subMesh, fillMode, instancesCount, true);
  22762. engine.setViewport(scene.activeCamera.viewport);
  22763. scene._switchToAlternateCameraConfiguration(false);
  22764. this._effectiveMaterial.bindView(effect);
  22765. this._effectiveMaterial.bindViewProjection(effect);
  22766. }
  22767. return this;
  22768. };
  22769. /**
  22770. * Registers for this mesh a javascript function called just before the rendering process.
  22771. * This function is passed the current mesh.
  22772. * Return the Mesh.
  22773. */
  22774. Mesh.prototype.registerBeforeRender = function (func) {
  22775. this.onBeforeRenderObservable.add(func);
  22776. return this;
  22777. };
  22778. /**
  22779. * Disposes a previously registered javascript function called before the rendering.
  22780. * This function is passed the current mesh.
  22781. * Returns the Mesh.
  22782. */
  22783. Mesh.prototype.unregisterBeforeRender = function (func) {
  22784. this.onBeforeRenderObservable.removeCallback(func);
  22785. return this;
  22786. };
  22787. /**
  22788. * Registers for this mesh a javascript function called just after the rendering is complete.
  22789. * This function is passed the current mesh.
  22790. * Returns the Mesh.
  22791. */
  22792. Mesh.prototype.registerAfterRender = function (func) {
  22793. this.onAfterRenderObservable.add(func);
  22794. return this;
  22795. };
  22796. /**
  22797. * Disposes a previously registered javascript function called after the rendering.
  22798. * This function is passed the current mesh.
  22799. * Return the Mesh.
  22800. */
  22801. Mesh.prototype.unregisterAfterRender = function (func) {
  22802. this.onAfterRenderObservable.removeCallback(func);
  22803. return this;
  22804. };
  22805. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  22806. var scene = this.getScene();
  22807. this._batchCache.mustReturn = false;
  22808. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  22809. this._batchCache.visibleInstances[subMeshId] = null;
  22810. if (this._visibleInstances) {
  22811. var currentRenderId = scene.getRenderId();
  22812. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  22813. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  22814. var selfRenderId = this._renderId;
  22815. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  22816. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  22817. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  22818. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  22819. }
  22820. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  22821. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  22822. this._batchCache.mustReturn = true;
  22823. return this._batchCache;
  22824. }
  22825. if (currentRenderId !== selfRenderId) {
  22826. this._batchCache.renderSelf[subMeshId] = false;
  22827. }
  22828. }
  22829. this._renderIdForInstances[subMeshId] = currentRenderId;
  22830. }
  22831. return this._batchCache;
  22832. };
  22833. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  22834. var visibleInstances = batch.visibleInstances[subMesh._id];
  22835. var matricesCount = visibleInstances.length + 1;
  22836. var bufferSize = matricesCount * 16 * 4;
  22837. var currentInstancesBufferSize = this._instancesBufferSize;
  22838. var instancesBuffer = this._instancesBuffer;
  22839. while (this._instancesBufferSize < bufferSize) {
  22840. this._instancesBufferSize *= 2;
  22841. }
  22842. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  22843. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  22844. }
  22845. var offset = 0;
  22846. var instancesCount = 0;
  22847. var world = this.getWorldMatrix();
  22848. if (batch.renderSelf[subMesh._id]) {
  22849. world.copyToArray(this._instancesData, offset);
  22850. offset += 16;
  22851. instancesCount++;
  22852. }
  22853. if (visibleInstances) {
  22854. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  22855. var instance = visibleInstances[instanceIndex];
  22856. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  22857. offset += 16;
  22858. instancesCount++;
  22859. }
  22860. }
  22861. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  22862. if (instancesBuffer) {
  22863. instancesBuffer.dispose();
  22864. }
  22865. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  22866. this._instancesBuffer = instancesBuffer;
  22867. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  22868. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  22869. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  22870. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  22871. }
  22872. else {
  22873. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  22874. }
  22875. this._bind(subMesh, effect, fillMode);
  22876. this._draw(subMesh, fillMode, instancesCount);
  22877. engine.unbindInstanceAttributes();
  22878. return this;
  22879. };
  22880. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  22881. var scene = this.getScene();
  22882. var engine = scene.getEngine();
  22883. if (hardwareInstancedRendering) {
  22884. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  22885. }
  22886. else {
  22887. if (batch.renderSelf[subMesh._id]) {
  22888. // Draw
  22889. if (onBeforeDraw) {
  22890. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  22891. }
  22892. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  22893. }
  22894. if (batch.visibleInstances[subMesh._id]) {
  22895. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  22896. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  22897. // World
  22898. var world = instance.getWorldMatrix();
  22899. if (onBeforeDraw) {
  22900. onBeforeDraw(true, world, effectiveMaterial);
  22901. }
  22902. // Draw
  22903. this._draw(subMesh, fillMode);
  22904. }
  22905. }
  22906. }
  22907. return this;
  22908. };
  22909. /**
  22910. * Triggers the draw call for the mesh.
  22911. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  22912. * Returns the Mesh.
  22913. */
  22914. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  22915. this.checkOcclusionQuery();
  22916. if (this._isOccluded) {
  22917. return this;
  22918. }
  22919. var scene = this.getScene();
  22920. // Managing instances
  22921. var batch = this._getInstancesRenderList(subMesh._id);
  22922. if (batch.mustReturn) {
  22923. return this;
  22924. }
  22925. // Checking geometry state
  22926. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  22927. return this;
  22928. }
  22929. this.onBeforeRenderObservable.notifyObservers(this);
  22930. var engine = scene.getEngine();
  22931. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  22932. // Material
  22933. this._effectiveMaterial = subMesh.getMaterial();
  22934. if (!this._effectiveMaterial) {
  22935. return this;
  22936. }
  22937. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  22938. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  22939. return this;
  22940. }
  22941. }
  22942. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  22943. return this;
  22944. }
  22945. // Alpha mode
  22946. if (enableAlphaMode) {
  22947. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  22948. }
  22949. // Outline - step 1
  22950. var savedDepthWrite = engine.getDepthWrite();
  22951. if (this.renderOutline) {
  22952. engine.setDepthWrite(false);
  22953. scene.getOutlineRenderer().render(subMesh, batch);
  22954. engine.setDepthWrite(savedDepthWrite);
  22955. }
  22956. var effect;
  22957. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  22958. effect = subMesh.effect;
  22959. }
  22960. else {
  22961. effect = this._effectiveMaterial.getEffect();
  22962. }
  22963. var reverse = this._effectiveMaterial._preBind(effect, this.overrideMaterialSideOrientation);
  22964. if (this._effectiveMaterial.forceDepthWrite) {
  22965. engine.setDepthWrite(true);
  22966. }
  22967. // Bind
  22968. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  22969. if (!hardwareInstancedRendering) {
  22970. this._bind(subMesh, effect, fillMode);
  22971. }
  22972. var world = this.getWorldMatrix();
  22973. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  22974. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  22975. }
  22976. else {
  22977. this._effectiveMaterial.bind(world, this);
  22978. }
  22979. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  22980. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  22981. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  22982. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  22983. }
  22984. // Draw
  22985. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  22986. // Unbind
  22987. this._effectiveMaterial.unbind();
  22988. // Outline - step 2
  22989. if (this.renderOutline && savedDepthWrite) {
  22990. engine.setDepthWrite(true);
  22991. engine.setColorWrite(false);
  22992. scene.getOutlineRenderer().render(subMesh, batch);
  22993. engine.setColorWrite(true);
  22994. }
  22995. // Overlay
  22996. if (this.renderOverlay) {
  22997. var currentMode = engine.getAlphaMode();
  22998. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  22999. scene.getOutlineRenderer().render(subMesh, batch, true);
  23000. engine.setAlphaMode(currentMode);
  23001. }
  23002. this.onAfterRenderObservable.notifyObservers(this);
  23003. return this;
  23004. };
  23005. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  23006. if (isInstance) {
  23007. effectiveMaterial.bindOnlyWorldMatrix(world);
  23008. }
  23009. return this;
  23010. };
  23011. /**
  23012. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  23013. */
  23014. Mesh.prototype.getEmittedParticleSystems = function () {
  23015. var results = new Array();
  23016. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23017. var particleSystem = this.getScene().particleSystems[index];
  23018. if (particleSystem.emitter === this) {
  23019. results.push(particleSystem);
  23020. }
  23021. }
  23022. return results;
  23023. };
  23024. /**
  23025. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  23026. */
  23027. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  23028. var results = new Array();
  23029. var descendants = this.getDescendants();
  23030. descendants.push(this);
  23031. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23032. var particleSystem = this.getScene().particleSystems[index];
  23033. var emitter = particleSystem.emitter;
  23034. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  23035. results.push(particleSystem);
  23036. }
  23037. }
  23038. return results;
  23039. };
  23040. Mesh.prototype._checkDelayState = function () {
  23041. var scene = this.getScene();
  23042. if (this._geometry) {
  23043. this._geometry.load(scene);
  23044. }
  23045. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23046. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  23047. this._queueLoad(this, scene);
  23048. }
  23049. return this;
  23050. };
  23051. Mesh.prototype._queueLoad = function (mesh, scene) {
  23052. var _this = this;
  23053. scene._addPendingData(mesh);
  23054. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  23055. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  23056. if (data instanceof ArrayBuffer) {
  23057. _this._delayLoadingFunction(data, _this);
  23058. }
  23059. else {
  23060. _this._delayLoadingFunction(JSON.parse(data), _this);
  23061. }
  23062. _this.instances.forEach(function (instance) {
  23063. instance._syncSubMeshes();
  23064. });
  23065. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23066. scene._removePendingData(_this);
  23067. }, function () { }, scene.database, getBinaryData);
  23068. return this;
  23069. };
  23070. /**
  23071. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  23072. */
  23073. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  23074. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23075. return false;
  23076. }
  23077. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  23078. return false;
  23079. }
  23080. this._checkDelayState();
  23081. return true;
  23082. };
  23083. /**
  23084. * Sets the mesh material by the material or multiMaterial `id` property.
  23085. * The material `id` is a string identifying the material or the multiMaterial.
  23086. * This method returns the Mesh.
  23087. */
  23088. Mesh.prototype.setMaterialByID = function (id) {
  23089. var materials = this.getScene().materials;
  23090. var index;
  23091. for (index = materials.length - 1; index > -1; index--) {
  23092. if (materials[index].id === id) {
  23093. this.material = materials[index];
  23094. return this;
  23095. }
  23096. }
  23097. // Multi
  23098. var multiMaterials = this.getScene().multiMaterials;
  23099. for (index = multiMaterials.length - 1; index > -1; index--) {
  23100. if (multiMaterials[index].id === id) {
  23101. this.material = multiMaterials[index];
  23102. return this;
  23103. }
  23104. }
  23105. return this;
  23106. };
  23107. /**
  23108. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  23109. */
  23110. Mesh.prototype.getAnimatables = function () {
  23111. var results = new Array();
  23112. if (this.material) {
  23113. results.push(this.material);
  23114. }
  23115. if (this.skeleton) {
  23116. results.push(this.skeleton);
  23117. }
  23118. return results;
  23119. };
  23120. /**
  23121. * Modifies the mesh geometry according to the passed transformation matrix.
  23122. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  23123. * The mesh normals are modified accordingly the same transformation.
  23124. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23125. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23126. * Returns the Mesh.
  23127. */
  23128. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  23129. // Position
  23130. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23131. return this;
  23132. }
  23133. var submeshes = this.subMeshes.splice(0);
  23134. this._resetPointsArrayCache();
  23135. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23136. var temp = new Array();
  23137. var index;
  23138. for (index = 0; index < data.length; index += 3) {
  23139. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  23140. }
  23141. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  23142. // Normals
  23143. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23144. return this;
  23145. }
  23146. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23147. temp = [];
  23148. for (index = 0; index < data.length; index += 3) {
  23149. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  23150. }
  23151. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  23152. // flip faces?
  23153. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  23154. this.flipFaces();
  23155. }
  23156. // Restore submeshes
  23157. this.releaseSubMeshes();
  23158. this.subMeshes = submeshes;
  23159. return this;
  23160. };
  23161. /**
  23162. * Modifies the mesh geometry according to its own current World Matrix.
  23163. * The mesh World Matrix is then reset.
  23164. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  23165. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23166. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23167. * Returns the Mesh.
  23168. */
  23169. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  23170. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  23171. this.scaling.copyFromFloats(1, 1, 1);
  23172. this.position.copyFromFloats(0, 0, 0);
  23173. this.rotation.copyFromFloats(0, 0, 0);
  23174. //only if quaternion is already set
  23175. if (this.rotationQuaternion) {
  23176. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  23177. }
  23178. this._worldMatrix = BABYLON.Matrix.Identity();
  23179. return this;
  23180. };
  23181. Object.defineProperty(Mesh.prototype, "_positions", {
  23182. // Cache
  23183. get: function () {
  23184. if (this._geometry) {
  23185. return this._geometry._positions;
  23186. }
  23187. return null;
  23188. },
  23189. enumerable: true,
  23190. configurable: true
  23191. });
  23192. Mesh.prototype._resetPointsArrayCache = function () {
  23193. if (this._geometry) {
  23194. this._geometry._resetPointsArrayCache();
  23195. }
  23196. return this;
  23197. };
  23198. Mesh.prototype._generatePointsArray = function () {
  23199. if (this._geometry) {
  23200. return this._geometry._generatePointsArray();
  23201. }
  23202. return false;
  23203. };
  23204. /**
  23205. * Returns a new Mesh object generated from the current mesh properties.
  23206. * This method must not get confused with createInstance().
  23207. * The parameter `name` is a string, the name given to the new mesh.
  23208. * The optional parameter `newParent` can be any Node object (default `null`).
  23209. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  23210. * 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.
  23211. */
  23212. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  23213. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  23214. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  23215. };
  23216. /**
  23217. * Disposes the mesh.
  23218. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  23219. */
  23220. Mesh.prototype.dispose = function (doNotRecurse) {
  23221. var _this = this;
  23222. this.morphTargetManager = undefined;
  23223. if (this._geometry) {
  23224. this._geometry.releaseForMesh(this, true);
  23225. }
  23226. // Sources
  23227. var meshes = this.getScene().meshes;
  23228. meshes.forEach(function (mesh) {
  23229. if (mesh._source && mesh._source === _this) {
  23230. mesh._source = null;
  23231. }
  23232. });
  23233. this._source = null;
  23234. // Instances
  23235. if (this._instancesBuffer) {
  23236. this._instancesBuffer.dispose();
  23237. this._instancesBuffer = null;
  23238. }
  23239. while (this.instances.length) {
  23240. this.instances[0].dispose();
  23241. }
  23242. // Highlight layers.
  23243. var highlightLayers = this.getScene().highlightLayers;
  23244. for (var i = 0; i < highlightLayers.length; i++) {
  23245. var highlightLayer = highlightLayers[i];
  23246. if (highlightLayer) {
  23247. highlightLayer.removeMesh(this);
  23248. highlightLayer.removeExcludedMesh(this);
  23249. }
  23250. }
  23251. _super.prototype.dispose.call(this, doNotRecurse);
  23252. };
  23253. /**
  23254. * Modifies the mesh geometry according to a displacement map.
  23255. * 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.
  23256. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  23257. * This method returns nothing.
  23258. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  23259. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  23260. * 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.
  23261. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  23262. * The parameter `uvScale` is an optional vector2 used to scale UV.
  23263. *
  23264. * Returns the Mesh.
  23265. */
  23266. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  23267. var _this = this;
  23268. var scene = this.getScene();
  23269. var onload = function (img) {
  23270. // Getting height map data
  23271. var canvas = document.createElement("canvas");
  23272. var context = canvas.getContext("2d");
  23273. var heightMapWidth = img.width;
  23274. var heightMapHeight = img.height;
  23275. canvas.width = heightMapWidth;
  23276. canvas.height = heightMapHeight;
  23277. context.drawImage(img, 0, 0);
  23278. // Create VertexData from map data
  23279. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  23280. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  23281. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  23282. //execute success callback, if set
  23283. if (onSuccess) {
  23284. onSuccess(_this);
  23285. }
  23286. };
  23287. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  23288. return this;
  23289. };
  23290. /**
  23291. * Modifies the mesh geometry according to a displacementMap buffer.
  23292. * 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.
  23293. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  23294. * This method returns nothing.
  23295. * 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.
  23296. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  23297. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  23298. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  23299. * The parameter `uvScale` is an optional vector2 used to scale UV.
  23300. *
  23301. * Returns the Mesh.
  23302. */
  23303. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  23304. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  23305. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  23306. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23307. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  23308. return this;
  23309. }
  23310. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23311. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23312. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  23313. var position = BABYLON.Vector3.Zero();
  23314. var normal = BABYLON.Vector3.Zero();
  23315. var uv = BABYLON.Vector2.Zero();
  23316. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  23317. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  23318. for (var index = 0; index < positions.length; index += 3) {
  23319. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  23320. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  23321. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  23322. // Compute height
  23323. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  23324. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  23325. var pos = (u + v * heightMapWidth) * 4;
  23326. var r = buffer[pos] / 255.0;
  23327. var g = buffer[pos + 1] / 255.0;
  23328. var b = buffer[pos + 2] / 255.0;
  23329. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  23330. normal.normalize();
  23331. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  23332. position = position.add(normal);
  23333. position.toArray(positions, index);
  23334. }
  23335. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  23336. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  23337. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  23338. return this;
  23339. };
  23340. /**
  23341. * Modify the mesh to get a flat shading rendering.
  23342. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  23343. * This method returns the Mesh.
  23344. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  23345. */
  23346. Mesh.prototype.convertToFlatShadedMesh = function () {
  23347. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  23348. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  23349. var kinds = this.getVerticesDataKinds();
  23350. var vbs = {};
  23351. var data = {};
  23352. var newdata = {};
  23353. var updatableNormals = false;
  23354. var kindIndex;
  23355. var kind;
  23356. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23357. kind = kinds[kindIndex];
  23358. var vertexBuffer = this.getVertexBuffer(kind);
  23359. if (kind === BABYLON.VertexBuffer.NormalKind) {
  23360. updatableNormals = vertexBuffer.isUpdatable();
  23361. kinds.splice(kindIndex, 1);
  23362. kindIndex--;
  23363. continue;
  23364. }
  23365. vbs[kind] = vertexBuffer;
  23366. data[kind] = vbs[kind].getData();
  23367. newdata[kind] = [];
  23368. }
  23369. // Save previous submeshes
  23370. var previousSubmeshes = this.subMeshes.slice(0);
  23371. var indices = this.getIndices();
  23372. var totalIndices = this.getTotalIndices();
  23373. // Generating unique vertices per face
  23374. var index;
  23375. for (index = 0; index < totalIndices; index++) {
  23376. var vertexIndex = indices[index];
  23377. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23378. kind = kinds[kindIndex];
  23379. var stride = vbs[kind].getStrideSize();
  23380. for (var offset = 0; offset < stride; offset++) {
  23381. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  23382. }
  23383. }
  23384. }
  23385. // Updating faces & normal
  23386. var normals = [];
  23387. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  23388. for (index = 0; index < totalIndices; index += 3) {
  23389. indices[index] = index;
  23390. indices[index + 1] = index + 1;
  23391. indices[index + 2] = index + 2;
  23392. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  23393. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  23394. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  23395. var p1p2 = p1.subtract(p2);
  23396. var p3p2 = p3.subtract(p2);
  23397. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  23398. // Store same normals for every vertex
  23399. for (var localIndex = 0; localIndex < 3; localIndex++) {
  23400. normals.push(normal.x);
  23401. normals.push(normal.y);
  23402. normals.push(normal.z);
  23403. }
  23404. }
  23405. this.setIndices(indices);
  23406. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  23407. // Updating vertex buffers
  23408. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23409. kind = kinds[kindIndex];
  23410. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  23411. }
  23412. // Updating submeshes
  23413. this.releaseSubMeshes();
  23414. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  23415. var previousOne = previousSubmeshes[submeshIndex];
  23416. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  23417. }
  23418. this.synchronizeInstances();
  23419. return this;
  23420. };
  23421. /**
  23422. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  23423. * In other words, more vertices, no more indices and a single bigger VBO.
  23424. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  23425. * Returns the Mesh.
  23426. */
  23427. Mesh.prototype.convertToUnIndexedMesh = function () {
  23428. /// <summary>Remove indices by unfolding faces into buffers</summary>
  23429. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  23430. var kinds = this.getVerticesDataKinds();
  23431. var vbs = {};
  23432. var data = {};
  23433. var newdata = {};
  23434. var kindIndex;
  23435. var kind;
  23436. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23437. kind = kinds[kindIndex];
  23438. var vertexBuffer = this.getVertexBuffer(kind);
  23439. vbs[kind] = vertexBuffer;
  23440. data[kind] = vbs[kind].getData();
  23441. newdata[kind] = [];
  23442. }
  23443. // Save previous submeshes
  23444. var previousSubmeshes = this.subMeshes.slice(0);
  23445. var indices = this.getIndices();
  23446. var totalIndices = this.getTotalIndices();
  23447. // Generating unique vertices per face
  23448. var index;
  23449. for (index = 0; index < totalIndices; index++) {
  23450. var vertexIndex = indices[index];
  23451. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23452. kind = kinds[kindIndex];
  23453. var stride = vbs[kind].getStrideSize();
  23454. for (var offset = 0; offset < stride; offset++) {
  23455. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  23456. }
  23457. }
  23458. }
  23459. // Updating indices
  23460. for (index = 0; index < totalIndices; index += 3) {
  23461. indices[index] = index;
  23462. indices[index + 1] = index + 1;
  23463. indices[index + 2] = index + 2;
  23464. }
  23465. this.setIndices(indices);
  23466. // Updating vertex buffers
  23467. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23468. kind = kinds[kindIndex];
  23469. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  23470. }
  23471. // Updating submeshes
  23472. this.releaseSubMeshes();
  23473. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  23474. var previousOne = previousSubmeshes[submeshIndex];
  23475. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  23476. }
  23477. this._unIndexed = true;
  23478. this.synchronizeInstances();
  23479. return this;
  23480. };
  23481. /**
  23482. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  23483. * This method returns the Mesh.
  23484. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  23485. */
  23486. Mesh.prototype.flipFaces = function (flipNormals) {
  23487. if (flipNormals === void 0) { flipNormals = false; }
  23488. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  23489. var i;
  23490. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23491. for (i = 0; i < vertex_data.normals.length; i++) {
  23492. vertex_data.normals[i] *= -1;
  23493. }
  23494. }
  23495. var temp;
  23496. for (i = 0; i < vertex_data.indices.length; i += 3) {
  23497. // reassign indices
  23498. temp = vertex_data.indices[i + 1];
  23499. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  23500. vertex_data.indices[i + 2] = temp;
  23501. }
  23502. vertex_data.applyToMesh(this);
  23503. return this;
  23504. };
  23505. // Instances
  23506. /**
  23507. * Creates a new InstancedMesh object from the mesh model.
  23508. * An instance shares the same properties and the same material than its model.
  23509. * Only these properties of each instance can then be set individually :
  23510. * - position
  23511. * - rotation
  23512. * - rotationQuaternion
  23513. * - setPivotMatrix
  23514. * - scaling
  23515. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  23516. * Warning : this method is not supported for Line mesh and LineSystem
  23517. */
  23518. Mesh.prototype.createInstance = function (name) {
  23519. return new BABYLON.InstancedMesh(name, this);
  23520. };
  23521. /**
  23522. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  23523. * After this call, all the mesh instances have the same submeshes than the current mesh.
  23524. * This method returns the Mesh.
  23525. */
  23526. Mesh.prototype.synchronizeInstances = function () {
  23527. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  23528. var instance = this.instances[instanceIndex];
  23529. instance._syncSubMeshes();
  23530. }
  23531. return this;
  23532. };
  23533. /**
  23534. * Simplify the mesh according to the given array of settings.
  23535. * Function will return immediately and will simplify async. It returns the Mesh.
  23536. * @param settings a collection of simplification settings.
  23537. * @param parallelProcessing should all levels calculate parallel or one after the other.
  23538. * @param type the type of simplification to run.
  23539. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  23540. */
  23541. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  23542. if (parallelProcessing === void 0) { parallelProcessing = true; }
  23543. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  23544. this.getScene().simplificationQueue.addTask({
  23545. settings: settings,
  23546. parallelProcessing: parallelProcessing,
  23547. mesh: this,
  23548. simplificationType: simplificationType,
  23549. successCallback: successCallback
  23550. });
  23551. return this;
  23552. };
  23553. /**
  23554. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  23555. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  23556. * This should be used together with the simplification to avoid disappearing triangles.
  23557. * Returns the Mesh.
  23558. * @param successCallback an optional success callback to be called after the optimization finished.
  23559. */
  23560. Mesh.prototype.optimizeIndices = function (successCallback) {
  23561. var _this = this;
  23562. var indices = this.getIndices();
  23563. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23564. var vectorPositions = new Array();
  23565. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  23566. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  23567. }
  23568. var dupes = new Array();
  23569. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  23570. var realPos = vectorPositions.length - 1 - iteration;
  23571. var testedPosition = vectorPositions[realPos];
  23572. for (var j = 0; j < realPos; ++j) {
  23573. var againstPosition = vectorPositions[j];
  23574. if (testedPosition.equals(againstPosition)) {
  23575. dupes[realPos] = j;
  23576. break;
  23577. }
  23578. }
  23579. }, function () {
  23580. for (var i = 0; i < indices.length; ++i) {
  23581. indices[i] = dupes[indices[i]] || indices[i];
  23582. }
  23583. //indices are now reordered
  23584. var originalSubMeshes = _this.subMeshes.slice(0);
  23585. _this.setIndices(indices);
  23586. _this.subMeshes = originalSubMeshes;
  23587. if (successCallback) {
  23588. successCallback(_this);
  23589. }
  23590. });
  23591. return this;
  23592. };
  23593. Mesh.prototype.serialize = function (serializationObject) {
  23594. serializationObject.name = this.name;
  23595. serializationObject.id = this.id;
  23596. serializationObject.type = this.getClassName();
  23597. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  23598. serializationObject.tags = BABYLON.Tags.GetTags(this);
  23599. }
  23600. serializationObject.position = this.position.asArray();
  23601. if (this.rotationQuaternion) {
  23602. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  23603. }
  23604. else if (this.rotation) {
  23605. serializationObject.rotation = this.rotation.asArray();
  23606. }
  23607. serializationObject.scaling = this.scaling.asArray();
  23608. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  23609. serializationObject.isEnabled = this.isEnabled();
  23610. serializationObject.isVisible = this.isVisible;
  23611. serializationObject.infiniteDistance = this.infiniteDistance;
  23612. serializationObject.pickable = this.isPickable;
  23613. serializationObject.receiveShadows = this.receiveShadows;
  23614. serializationObject.billboardMode = this.billboardMode;
  23615. serializationObject.visibility = this.visibility;
  23616. serializationObject.checkCollisions = this.checkCollisions;
  23617. serializationObject.isBlocker = this.isBlocker;
  23618. // Parent
  23619. if (this.parent) {
  23620. serializationObject.parentId = this.parent.id;
  23621. }
  23622. // Geometry
  23623. var geometry = this._geometry;
  23624. if (geometry) {
  23625. var geometryId = geometry.id;
  23626. serializationObject.geometryId = geometryId;
  23627. // SubMeshes
  23628. serializationObject.subMeshes = [];
  23629. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  23630. var subMesh = this.subMeshes[subIndex];
  23631. serializationObject.subMeshes.push({
  23632. materialIndex: subMesh.materialIndex,
  23633. verticesStart: subMesh.verticesStart,
  23634. verticesCount: subMesh.verticesCount,
  23635. indexStart: subMesh.indexStart,
  23636. indexCount: subMesh.indexCount
  23637. });
  23638. }
  23639. }
  23640. // Material
  23641. if (this.material) {
  23642. serializationObject.materialId = this.material.id;
  23643. }
  23644. else {
  23645. this.material = null;
  23646. }
  23647. // Morph targets
  23648. if (this.morphTargetManager) {
  23649. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  23650. }
  23651. // Skeleton
  23652. if (this.skeleton) {
  23653. serializationObject.skeletonId = this.skeleton.id;
  23654. }
  23655. // Physics
  23656. //TODO implement correct serialization for physics impostors.
  23657. if (this.getPhysicsImpostor()) {
  23658. var impostor = this.getPhysicsImpostor();
  23659. serializationObject.physicsMass = impostor.getParam("mass");
  23660. serializationObject.physicsFriction = impostor.getParam("friction");
  23661. serializationObject.physicsRestitution = impostor.getParam("mass");
  23662. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  23663. }
  23664. // Metadata
  23665. if (this.metadata) {
  23666. serializationObject.metadata = this.metadata;
  23667. }
  23668. // Instances
  23669. serializationObject.instances = [];
  23670. for (var index = 0; index < this.instances.length; index++) {
  23671. var instance = this.instances[index];
  23672. var serializationInstance = {
  23673. name: instance.name,
  23674. position: instance.position.asArray(),
  23675. scaling: instance.scaling.asArray()
  23676. };
  23677. if (instance.rotationQuaternion) {
  23678. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  23679. }
  23680. else if (instance.rotation) {
  23681. serializationInstance.rotation = instance.rotation.asArray();
  23682. }
  23683. serializationObject.instances.push(serializationInstance);
  23684. // Animations
  23685. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  23686. serializationInstance.ranges = instance.serializeAnimationRanges();
  23687. }
  23688. //
  23689. // Animations
  23690. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23691. serializationObject.ranges = this.serializeAnimationRanges();
  23692. // Layer mask
  23693. serializationObject.layerMask = this.layerMask;
  23694. // Alpha
  23695. serializationObject.alphaIndex = this.alphaIndex;
  23696. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  23697. // Overlay
  23698. serializationObject.overlayAlpha = this.overlayAlpha;
  23699. serializationObject.overlayColor = this.overlayColor.asArray();
  23700. serializationObject.renderOverlay = this.renderOverlay;
  23701. // Fog
  23702. serializationObject.applyFog = this.applyFog;
  23703. // Action Manager
  23704. if (this.actionManager) {
  23705. serializationObject.actions = this.actionManager.serialize(this.name);
  23706. }
  23707. };
  23708. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  23709. if (!this.geometry) {
  23710. return;
  23711. }
  23712. this._markSubMeshesAsAttributesDirty();
  23713. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  23714. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  23715. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  23716. this.morphTargetManager = undefined;
  23717. return;
  23718. }
  23719. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  23720. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  23721. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  23722. if (morphTarget.hasNormals) {
  23723. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  23724. }
  23725. if (morphTarget.hasTangents) {
  23726. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  23727. }
  23728. }
  23729. }
  23730. else {
  23731. var index = 0;
  23732. // Positions
  23733. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  23734. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  23735. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  23736. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  23737. }
  23738. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  23739. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  23740. }
  23741. index++;
  23742. }
  23743. }
  23744. };
  23745. // Statics
  23746. /**
  23747. * Returns a new Mesh object what is a deep copy of the passed mesh.
  23748. * The parameter `parsedMesh` is the mesh to be copied.
  23749. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  23750. */
  23751. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  23752. var mesh;
  23753. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  23754. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  23755. }
  23756. else {
  23757. mesh = new Mesh(parsedMesh.name, scene);
  23758. }
  23759. mesh.id = parsedMesh.id;
  23760. if (BABYLON.Tags) {
  23761. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  23762. }
  23763. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  23764. if (parsedMesh.metadata !== undefined) {
  23765. mesh.metadata = parsedMesh.metadata;
  23766. }
  23767. if (parsedMesh.rotationQuaternion) {
  23768. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  23769. }
  23770. else if (parsedMesh.rotation) {
  23771. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  23772. }
  23773. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  23774. if (parsedMesh.localMatrix) {
  23775. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  23776. }
  23777. else if (parsedMesh.pivotMatrix) {
  23778. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  23779. }
  23780. mesh.setEnabled(parsedMesh.isEnabled);
  23781. mesh.isVisible = parsedMesh.isVisible;
  23782. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  23783. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  23784. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  23785. if (parsedMesh.applyFog !== undefined) {
  23786. mesh.applyFog = parsedMesh.applyFog;
  23787. }
  23788. if (parsedMesh.pickable !== undefined) {
  23789. mesh.isPickable = parsedMesh.pickable;
  23790. }
  23791. if (parsedMesh.alphaIndex !== undefined) {
  23792. mesh.alphaIndex = parsedMesh.alphaIndex;
  23793. }
  23794. mesh.receiveShadows = parsedMesh.receiveShadows;
  23795. mesh.billboardMode = parsedMesh.billboardMode;
  23796. if (parsedMesh.visibility !== undefined) {
  23797. mesh.visibility = parsedMesh.visibility;
  23798. }
  23799. mesh.checkCollisions = parsedMesh.checkCollisions;
  23800. if (parsedMesh.isBlocker !== undefined) {
  23801. mesh.isBlocker = parsedMesh.isBlocker;
  23802. }
  23803. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  23804. // freezeWorldMatrix
  23805. if (parsedMesh.freezeWorldMatrix) {
  23806. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  23807. }
  23808. // Parent
  23809. if (parsedMesh.parentId) {
  23810. mesh._waitingParentId = parsedMesh.parentId;
  23811. }
  23812. // Actions
  23813. if (parsedMesh.actions !== undefined) {
  23814. mesh._waitingActions = parsedMesh.actions;
  23815. }
  23816. // Overlay
  23817. if (parsedMesh.overlayAlpha !== undefined) {
  23818. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  23819. }
  23820. if (parsedMesh.overlayColor !== undefined) {
  23821. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  23822. }
  23823. if (parsedMesh.renderOverlay !== undefined) {
  23824. mesh.renderOverlay = parsedMesh.renderOverlay;
  23825. }
  23826. // Geometry
  23827. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  23828. if (parsedMesh.delayLoadingFile) {
  23829. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23830. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  23831. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  23832. if (parsedMesh._binaryInfo) {
  23833. mesh._binaryInfo = parsedMesh._binaryInfo;
  23834. }
  23835. mesh._delayInfo = [];
  23836. if (parsedMesh.hasUVs) {
  23837. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  23838. }
  23839. if (parsedMesh.hasUVs2) {
  23840. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  23841. }
  23842. if (parsedMesh.hasUVs3) {
  23843. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  23844. }
  23845. if (parsedMesh.hasUVs4) {
  23846. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  23847. }
  23848. if (parsedMesh.hasUVs5) {
  23849. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  23850. }
  23851. if (parsedMesh.hasUVs6) {
  23852. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  23853. }
  23854. if (parsedMesh.hasColors) {
  23855. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  23856. }
  23857. if (parsedMesh.hasMatricesIndices) {
  23858. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23859. }
  23860. if (parsedMesh.hasMatricesWeights) {
  23861. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23862. }
  23863. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  23864. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  23865. mesh._checkDelayState();
  23866. }
  23867. }
  23868. else {
  23869. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  23870. }
  23871. // Material
  23872. if (parsedMesh.materialId) {
  23873. mesh.setMaterialByID(parsedMesh.materialId);
  23874. }
  23875. else {
  23876. mesh.material = null;
  23877. }
  23878. // Morph targets
  23879. if (parsedMesh.morphTargetManagerId > -1) {
  23880. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  23881. }
  23882. // Skeleton
  23883. if (parsedMesh.skeletonId > -1) {
  23884. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  23885. if (parsedMesh.numBoneInfluencers) {
  23886. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  23887. }
  23888. }
  23889. // Animations
  23890. if (parsedMesh.animations) {
  23891. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  23892. var parsedAnimation = parsedMesh.animations[animationIndex];
  23893. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23894. }
  23895. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  23896. }
  23897. if (parsedMesh.autoAnimate) {
  23898. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  23899. }
  23900. // Layer Mask
  23901. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  23902. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  23903. }
  23904. else {
  23905. mesh.layerMask = 0x0FFFFFFF;
  23906. }
  23907. // Physics
  23908. if (parsedMesh.physicsImpostor) {
  23909. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  23910. mass: parsedMesh.physicsMass,
  23911. friction: parsedMesh.physicsFriction,
  23912. restitution: parsedMesh.physicsRestitution
  23913. }, scene);
  23914. }
  23915. // Instances
  23916. if (parsedMesh.instances) {
  23917. for (var index = 0; index < parsedMesh.instances.length; index++) {
  23918. var parsedInstance = parsedMesh.instances[index];
  23919. var instance = mesh.createInstance(parsedInstance.name);
  23920. if (BABYLON.Tags) {
  23921. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  23922. }
  23923. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  23924. if (parsedInstance.parentId) {
  23925. instance._waitingParentId = parsedInstance.parentId;
  23926. }
  23927. if (parsedInstance.rotationQuaternion) {
  23928. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  23929. }
  23930. else if (parsedInstance.rotation) {
  23931. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  23932. }
  23933. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  23934. instance.checkCollisions = mesh.checkCollisions;
  23935. if (parsedMesh.animations) {
  23936. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  23937. parsedAnimation = parsedMesh.animations[animationIndex];
  23938. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23939. }
  23940. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  23941. }
  23942. }
  23943. }
  23944. return mesh;
  23945. };
  23946. /**
  23947. * Creates a ribbon mesh.
  23948. * Please consider using the same method from the MeshBuilder class instead.
  23949. * 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.
  23950. *
  23951. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  23952. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  23953. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  23954. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  23955. * 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.
  23956. * 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.
  23957. * 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
  23958. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23959. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23960. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23961. */
  23962. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  23963. return BABYLON.MeshBuilder.CreateRibbon(name, {
  23964. pathArray: pathArray,
  23965. closeArray: closeArray,
  23966. closePath: closePath,
  23967. offset: offset,
  23968. updatable: updatable,
  23969. sideOrientation: sideOrientation,
  23970. instance: instance
  23971. }, scene);
  23972. };
  23973. /**
  23974. * Creates a plane polygonal mesh. By default, this is a disc.
  23975. * Please consider using the same method from the MeshBuilder class instead.
  23976. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  23977. * 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.
  23978. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23979. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23980. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23981. */
  23982. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  23983. var options = {
  23984. radius: radius,
  23985. tessellation: tessellation,
  23986. sideOrientation: sideOrientation,
  23987. updatable: updatable
  23988. };
  23989. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  23990. };
  23991. /**
  23992. * Creates a box mesh.
  23993. * Please consider using the same method from the MeshBuilder class instead.
  23994. * The parameter `size` sets the size (float) of each box side (default 1).
  23995. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23996. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23997. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23998. */
  23999. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  24000. var options = {
  24001. size: size,
  24002. sideOrientation: sideOrientation,
  24003. updatable: updatable
  24004. };
  24005. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  24006. };
  24007. /**
  24008. * Creates a sphere mesh.
  24009. * Please consider using the same method from the MeshBuilder class instead.
  24010. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  24011. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  24012. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24013. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24014. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24015. */
  24016. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  24017. var options = {
  24018. segments: segments,
  24019. diameterX: diameter,
  24020. diameterY: diameter,
  24021. diameterZ: diameter,
  24022. sideOrientation: sideOrientation,
  24023. updatable: updatable
  24024. };
  24025. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  24026. };
  24027. /**
  24028. * Creates a cylinder or a cone mesh.
  24029. * Please consider using the same method from the MeshBuilder class instead.
  24030. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  24031. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  24032. * 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.
  24033. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  24034. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  24035. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24036. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24037. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24038. */
  24039. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  24040. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  24041. if (scene !== undefined) {
  24042. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  24043. updatable = scene;
  24044. }
  24045. scene = subdivisions;
  24046. subdivisions = 1;
  24047. }
  24048. var options = {
  24049. height: height,
  24050. diameterTop: diameterTop,
  24051. diameterBottom: diameterBottom,
  24052. tessellation: tessellation,
  24053. subdivisions: subdivisions,
  24054. sideOrientation: sideOrientation,
  24055. updatable: updatable
  24056. };
  24057. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  24058. };
  24059. // Torus (Code from SharpDX.org)
  24060. /**
  24061. * Creates a torus mesh.
  24062. * Please consider using the same method from the MeshBuilder class instead.
  24063. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  24064. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  24065. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  24066. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24067. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24068. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24069. */
  24070. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  24071. var options = {
  24072. diameter: diameter,
  24073. thickness: thickness,
  24074. tessellation: tessellation,
  24075. sideOrientation: sideOrientation,
  24076. updatable: updatable
  24077. };
  24078. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  24079. };
  24080. /**
  24081. * Creates a torus knot mesh.
  24082. * Please consider using the same method from the MeshBuilder class instead.
  24083. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  24084. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  24085. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  24086. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  24087. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24088. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24089. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24090. */
  24091. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  24092. var options = {
  24093. radius: radius,
  24094. tube: tube,
  24095. radialSegments: radialSegments,
  24096. tubularSegments: tubularSegments,
  24097. p: p,
  24098. q: q,
  24099. sideOrientation: sideOrientation,
  24100. updatable: updatable
  24101. };
  24102. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  24103. };
  24104. /**
  24105. * Creates a line mesh.
  24106. * Please consider using the same method from the MeshBuilder class instead.
  24107. * 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.
  24108. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24109. * The parameter `points` is an array successive Vector3.
  24110. * 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
  24111. * When updating an instance, remember that only point positions can change, not the number of points.
  24112. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24113. */
  24114. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  24115. if (scene === void 0) { scene = null; }
  24116. if (updatable === void 0) { updatable = false; }
  24117. if (instance === void 0) { instance = null; }
  24118. var options = {
  24119. points: points,
  24120. updatable: updatable,
  24121. instance: instance
  24122. };
  24123. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  24124. };
  24125. /**
  24126. * Creates a dashed line mesh.
  24127. * Please consider using the same method from the MeshBuilder class instead.
  24128. * 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.
  24129. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24130. * The parameter `points` is an array successive Vector3.
  24131. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  24132. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  24133. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  24134. * 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
  24135. * When updating an instance, remember that only point positions can change, not the number of points.
  24136. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24137. */
  24138. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  24139. var options = {
  24140. points: points,
  24141. dashSize: dashSize,
  24142. gapSize: gapSize,
  24143. dashNb: dashNb,
  24144. updatable: updatable,
  24145. instance: instance
  24146. };
  24147. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  24148. };
  24149. /**
  24150. * Creates a polygon mesh.
  24151. * Please consider using the same method from the MeshBuilder class instead.
  24152. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  24153. * 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.
  24154. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24155. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24156. * Remember you can only change the shape positions, not their number when updating a polygon.
  24157. */
  24158. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  24159. var options = {
  24160. shape: shape,
  24161. holes: holes,
  24162. updatable: updatable,
  24163. sideOrientation: sideOrientation
  24164. };
  24165. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  24166. };
  24167. /**
  24168. * Creates an extruded polygon mesh, with depth in the Y direction.
  24169. * Please consider using the same method from the MeshBuilder class instead.
  24170. */
  24171. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  24172. var options = {
  24173. shape: shape,
  24174. holes: holes,
  24175. depth: depth,
  24176. updatable: updatable,
  24177. sideOrientation: sideOrientation
  24178. };
  24179. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  24180. };
  24181. /**
  24182. * Creates an extruded shape mesh.
  24183. * 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.
  24184. * Please consider using the same method from the MeshBuilder class instead.
  24185. *
  24186. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24187. * 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
  24188. * extruded along the Z axis.
  24189. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24190. * 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.
  24191. * The parameter `scale` (float, default 1) is the value to scale the shape.
  24192. * 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
  24193. * 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
  24194. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24195. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24196. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24197. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24198. */
  24199. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  24200. var options = {
  24201. shape: shape,
  24202. path: path,
  24203. scale: scale,
  24204. rotation: rotation,
  24205. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24206. sideOrientation: sideOrientation,
  24207. instance: instance,
  24208. updatable: updatable
  24209. };
  24210. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  24211. };
  24212. /**
  24213. * Creates an custom extruded shape mesh.
  24214. * 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.
  24215. * Please consider using the same method from the MeshBuilder class instead.
  24216. *
  24217. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24218. * 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
  24219. * extruded along the Z axis.
  24220. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24221. * 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
  24222. * and the distance of this point from the begining of the path :
  24223. * ```javascript
  24224. * var rotationFunction = function(i, distance) {
  24225. * // do things
  24226. * return rotationValue; }
  24227. * ```
  24228. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  24229. * 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
  24230. * and the distance of this point from the begining of the path :
  24231. * ```javascript
  24232. * var scaleFunction = function(i, distance) {
  24233. * // do things
  24234. * return scaleValue;}
  24235. * ```
  24236. * It must returns a float value that will be the scale value applied to the shape on each path point.
  24237. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  24238. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  24239. * 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
  24240. * 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
  24241. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24242. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24243. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24244. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24245. */
  24246. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  24247. var options = {
  24248. shape: shape,
  24249. path: path,
  24250. scaleFunction: scaleFunction,
  24251. rotationFunction: rotationFunction,
  24252. ribbonCloseArray: ribbonCloseArray,
  24253. ribbonClosePath: ribbonClosePath,
  24254. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24255. sideOrientation: sideOrientation,
  24256. instance: instance,
  24257. updatable: updatable
  24258. };
  24259. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  24260. };
  24261. /**
  24262. * Creates lathe mesh.
  24263. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  24264. * Please consider using the same method from the MeshBuilder class instead.
  24265. * 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
  24266. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  24267. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  24268. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  24269. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24270. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24271. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24272. */
  24273. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  24274. var options = {
  24275. shape: shape,
  24276. radius: radius,
  24277. tessellation: tessellation,
  24278. sideOrientation: sideOrientation,
  24279. updatable: updatable
  24280. };
  24281. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  24282. };
  24283. /**
  24284. * Creates a plane mesh.
  24285. * Please consider using the same method from the MeshBuilder class instead.
  24286. * The parameter `size` sets the size (float) of both sides of the plane at once (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.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  24292. var options = {
  24293. size: size,
  24294. width: size,
  24295. height: size,
  24296. sideOrientation: sideOrientation,
  24297. updatable: updatable
  24298. };
  24299. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  24300. };
  24301. /**
  24302. * Creates a ground mesh.
  24303. * Please consider using the same method from the MeshBuilder class instead.
  24304. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  24305. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  24306. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24307. */
  24308. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  24309. var options = {
  24310. width: width,
  24311. height: height,
  24312. subdivisions: subdivisions,
  24313. updatable: updatable
  24314. };
  24315. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  24316. };
  24317. /**
  24318. * Creates a tiled ground mesh.
  24319. * Please consider using the same method from the MeshBuilder class instead.
  24320. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  24321. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  24322. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  24323. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  24324. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  24325. * numbers of subdivisions on the ground width and height of each tile.
  24326. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24327. */
  24328. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  24329. var options = {
  24330. xmin: xmin,
  24331. zmin: zmin,
  24332. xmax: xmax,
  24333. zmax: zmax,
  24334. subdivisions: subdivisions,
  24335. precision: precision,
  24336. updatable: updatable
  24337. };
  24338. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  24339. };
  24340. /**
  24341. * Creates a ground mesh from a height map.
  24342. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  24343. * Please consider using the same method from the MeshBuilder class instead.
  24344. * The parameter `url` sets the URL of the height map image resource.
  24345. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  24346. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  24347. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  24348. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  24349. * 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).
  24350. * This function is passed the newly built mesh :
  24351. * ```javascript
  24352. * function(mesh) { // do things
  24353. * return; }
  24354. * ```
  24355. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24356. */
  24357. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  24358. var options = {
  24359. width: width,
  24360. height: height,
  24361. subdivisions: subdivisions,
  24362. minHeight: minHeight,
  24363. maxHeight: maxHeight,
  24364. updatable: updatable,
  24365. onReady: onReady
  24366. };
  24367. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  24368. };
  24369. /**
  24370. * Creates a tube mesh.
  24371. * 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.
  24372. * Please consider using the same method from the MeshBuilder class instead.
  24373. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  24374. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  24375. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  24376. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  24377. * 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.
  24378. * It must return a radius value (positive float) :
  24379. * ```javascript
  24380. * var radiusFunction = function(i, distance) {
  24381. * // do things
  24382. * return radius; }
  24383. * ```
  24384. * 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
  24385. * 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
  24386. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24387. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  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.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  24391. var options = {
  24392. path: path,
  24393. radius: radius,
  24394. tessellation: tessellation,
  24395. radiusFunction: radiusFunction,
  24396. arc: 1,
  24397. cap: cap,
  24398. updatable: updatable,
  24399. sideOrientation: sideOrientation,
  24400. instance: instance
  24401. };
  24402. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  24403. };
  24404. /**
  24405. * Creates a polyhedron mesh.
  24406. * Please consider using the same method from the MeshBuilder class instead.
  24407. * 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
  24408. * to choose the wanted type.
  24409. * The parameter `size` (positive float, default 1) sets the polygon size.
  24410. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  24411. * 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`.
  24412. * 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
  24413. * 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)`).
  24414. * 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
  24415. * 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.
  24416. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24417. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24418. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24419. */
  24420. Mesh.CreatePolyhedron = function (name, options, scene) {
  24421. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  24422. };
  24423. /**
  24424. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  24425. * Please consider using the same method from the MeshBuilder class instead.
  24426. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  24427. * 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`).
  24428. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  24429. * 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.
  24430. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24431. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24432. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24433. */
  24434. Mesh.CreateIcoSphere = function (name, options, scene) {
  24435. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  24436. };
  24437. /**
  24438. * Creates a decal mesh.
  24439. * Please consider using the same method from the MeshBuilder class instead.
  24440. * 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.
  24441. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  24442. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  24443. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  24444. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  24445. */
  24446. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  24447. var options = {
  24448. position: position,
  24449. normal: normal,
  24450. size: size,
  24451. angle: angle
  24452. };
  24453. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  24454. };
  24455. // Skeletons
  24456. /**
  24457. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  24458. */
  24459. Mesh.prototype.setPositionsForCPUSkinning = function () {
  24460. var source;
  24461. if (!this._sourcePositions) {
  24462. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24463. this._sourcePositions = new Float32Array(source);
  24464. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  24465. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  24466. }
  24467. }
  24468. return this._sourcePositions;
  24469. };
  24470. /**
  24471. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  24472. */
  24473. Mesh.prototype.setNormalsForCPUSkinning = function () {
  24474. var source;
  24475. if (!this._sourceNormals) {
  24476. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24477. this._sourceNormals = new Float32Array(source);
  24478. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  24479. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  24480. }
  24481. }
  24482. return this._sourceNormals;
  24483. };
  24484. /**
  24485. * Updates the vertex buffer by applying transformation from the bones.
  24486. * Returns the Mesh.
  24487. *
  24488. * @param {skeleton} skeleton to apply
  24489. */
  24490. Mesh.prototype.applySkeleton = function (skeleton) {
  24491. if (!this.geometry) {
  24492. return this;
  24493. }
  24494. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  24495. return this;
  24496. }
  24497. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  24498. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24499. return this;
  24500. }
  24501. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24502. return this;
  24503. }
  24504. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24505. return this;
  24506. }
  24507. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24508. return this;
  24509. }
  24510. if (!this._sourcePositions) {
  24511. var submeshes = this.subMeshes.slice();
  24512. this.setPositionsForCPUSkinning();
  24513. this.subMeshes = submeshes;
  24514. }
  24515. if (!this._sourceNormals) {
  24516. this.setNormalsForCPUSkinning();
  24517. }
  24518. // positionsData checks for not being Float32Array will only pass at most once
  24519. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24520. if (!(positionsData instanceof Float32Array)) {
  24521. positionsData = new Float32Array(positionsData);
  24522. }
  24523. // normalsData checks for not being Float32Array will only pass at most once
  24524. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24525. if (!(normalsData instanceof Float32Array)) {
  24526. normalsData = new Float32Array(normalsData);
  24527. }
  24528. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  24529. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  24530. var needExtras = this.numBoneInfluencers > 4;
  24531. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  24532. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  24533. var skeletonMatrices = skeleton.getTransformMatrices(this);
  24534. var tempVector3 = BABYLON.Vector3.Zero();
  24535. var finalMatrix = new BABYLON.Matrix();
  24536. var tempMatrix = new BABYLON.Matrix();
  24537. var matWeightIdx = 0;
  24538. var inf;
  24539. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  24540. var weight;
  24541. for (inf = 0; inf < 4; inf++) {
  24542. weight = matricesWeightsData[matWeightIdx + inf];
  24543. if (weight > 0) {
  24544. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  24545. finalMatrix.addToSelf(tempMatrix);
  24546. }
  24547. else
  24548. break;
  24549. }
  24550. if (needExtras) {
  24551. for (inf = 0; inf < 4; inf++) {
  24552. weight = matricesWeightsExtraData[matWeightIdx + inf];
  24553. if (weight > 0) {
  24554. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  24555. finalMatrix.addToSelf(tempMatrix);
  24556. }
  24557. else
  24558. break;
  24559. }
  24560. }
  24561. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  24562. tempVector3.toArray(positionsData, index);
  24563. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  24564. tempVector3.toArray(normalsData, index);
  24565. finalMatrix.reset();
  24566. }
  24567. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  24568. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  24569. return this;
  24570. };
  24571. // Tools
  24572. /**
  24573. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  24574. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  24575. */
  24576. Mesh.MinMax = function (meshes) {
  24577. var minVector = null;
  24578. var maxVector = null;
  24579. meshes.forEach(function (mesh, index, array) {
  24580. var boundingBox = mesh.getBoundingInfo().boundingBox;
  24581. if (!minVector) {
  24582. minVector = boundingBox.minimumWorld;
  24583. maxVector = boundingBox.maximumWorld;
  24584. }
  24585. else {
  24586. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  24587. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  24588. }
  24589. });
  24590. return {
  24591. min: minVector,
  24592. max: maxVector
  24593. };
  24594. };
  24595. /**
  24596. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  24597. */
  24598. Mesh.Center = function (meshesOrMinMaxVector) {
  24599. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  24600. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  24601. };
  24602. /**
  24603. * Merge the array of meshes into a single mesh for performance reasons.
  24604. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  24605. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  24606. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  24607. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  24608. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  24609. */
  24610. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  24611. if (disposeSource === void 0) { disposeSource = true; }
  24612. var index;
  24613. if (!allow32BitsIndices) {
  24614. var totalVertices = 0;
  24615. // Counting vertices
  24616. for (index = 0; index < meshes.length; index++) {
  24617. if (meshes[index]) {
  24618. totalVertices += meshes[index].getTotalVertices();
  24619. if (totalVertices > 65536) {
  24620. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  24621. return null;
  24622. }
  24623. }
  24624. }
  24625. }
  24626. // Merge
  24627. var vertexData;
  24628. var otherVertexData;
  24629. var indiceArray = new Array();
  24630. var source;
  24631. for (index = 0; index < meshes.length; index++) {
  24632. if (meshes[index]) {
  24633. meshes[index].computeWorldMatrix(true);
  24634. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  24635. otherVertexData.transform(meshes[index].getWorldMatrix());
  24636. if (vertexData) {
  24637. vertexData.merge(otherVertexData);
  24638. }
  24639. else {
  24640. vertexData = otherVertexData;
  24641. source = meshes[index];
  24642. }
  24643. if (subdivideWithSubMeshes) {
  24644. indiceArray.push(meshes[index].getTotalIndices());
  24645. }
  24646. }
  24647. }
  24648. if (!meshSubclass) {
  24649. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  24650. }
  24651. vertexData.applyToMesh(meshSubclass);
  24652. // Setting properties
  24653. meshSubclass.material = source.material;
  24654. meshSubclass.checkCollisions = source.checkCollisions;
  24655. // Cleaning
  24656. if (disposeSource) {
  24657. for (index = 0; index < meshes.length; index++) {
  24658. if (meshes[index]) {
  24659. meshes[index].dispose();
  24660. }
  24661. }
  24662. }
  24663. // Subdivide
  24664. if (subdivideWithSubMeshes) {
  24665. //-- Suppresions du submesh global
  24666. meshSubclass.releaseSubMeshes();
  24667. index = 0;
  24668. var offset = 0;
  24669. //-- aplique la subdivision en fonction du tableau d'indices
  24670. while (index < indiceArray.length) {
  24671. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  24672. offset += indiceArray[index];
  24673. index++;
  24674. }
  24675. }
  24676. return meshSubclass;
  24677. };
  24678. // Consts
  24679. Mesh._FRONTSIDE = 0;
  24680. Mesh._BACKSIDE = 1;
  24681. Mesh._DOUBLESIDE = 2;
  24682. Mesh._DEFAULTSIDE = 0;
  24683. Mesh._NO_CAP = 0;
  24684. Mesh._CAP_START = 1;
  24685. Mesh._CAP_END = 2;
  24686. Mesh._CAP_ALL = 3;
  24687. return Mesh;
  24688. }(BABYLON.AbstractMesh));
  24689. BABYLON.Mesh = Mesh;
  24690. })(BABYLON || (BABYLON = {}));
  24691. //# sourceMappingURL=babylon.mesh.js.map
  24692. var BABYLON;
  24693. (function (BABYLON) {
  24694. var BaseSubMesh = /** @class */ (function () {
  24695. function BaseSubMesh() {
  24696. }
  24697. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  24698. get: function () {
  24699. return this._materialEffect;
  24700. },
  24701. enumerable: true,
  24702. configurable: true
  24703. });
  24704. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  24705. if (defines === void 0) { defines = null; }
  24706. if (this._materialEffect === effect) {
  24707. if (!effect) {
  24708. this._materialDefines = null;
  24709. }
  24710. return;
  24711. }
  24712. this._materialDefines = defines;
  24713. this._materialEffect = effect;
  24714. };
  24715. return BaseSubMesh;
  24716. }());
  24717. BABYLON.BaseSubMesh = BaseSubMesh;
  24718. var SubMesh = /** @class */ (function (_super) {
  24719. __extends(SubMesh, _super);
  24720. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  24721. if (createBoundingBox === void 0) { createBoundingBox = true; }
  24722. var _this = _super.call(this) || this;
  24723. _this.materialIndex = materialIndex;
  24724. _this.verticesStart = verticesStart;
  24725. _this.verticesCount = verticesCount;
  24726. _this.indexStart = indexStart;
  24727. _this.indexCount = indexCount;
  24728. _this._renderId = 0;
  24729. _this._mesh = mesh;
  24730. _this._renderingMesh = renderingMesh || mesh;
  24731. mesh.subMeshes.push(_this);
  24732. _this._trianglePlanes = [];
  24733. _this._id = mesh.subMeshes.length - 1;
  24734. if (createBoundingBox) {
  24735. _this.refreshBoundingInfo();
  24736. mesh.computeWorldMatrix(true);
  24737. }
  24738. return _this;
  24739. }
  24740. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  24741. if (createBoundingBox === void 0) { createBoundingBox = true; }
  24742. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  24743. };
  24744. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  24745. get: function () {
  24746. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  24747. },
  24748. enumerable: true,
  24749. configurable: true
  24750. });
  24751. /**
  24752. * Returns the submesh BoudingInfo object.
  24753. */
  24754. SubMesh.prototype.getBoundingInfo = function () {
  24755. if (this.IsGlobal) {
  24756. return this._mesh.getBoundingInfo();
  24757. }
  24758. return this._boundingInfo;
  24759. };
  24760. /**
  24761. * Sets the submesh BoundingInfo.
  24762. * Return the SubMesh.
  24763. */
  24764. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  24765. this._boundingInfo = boundingInfo;
  24766. return this;
  24767. };
  24768. /**
  24769. * Returns the mesh of the current submesh.
  24770. */
  24771. SubMesh.prototype.getMesh = function () {
  24772. return this._mesh;
  24773. };
  24774. /**
  24775. * Returns the rendering mesh of the submesh.
  24776. */
  24777. SubMesh.prototype.getRenderingMesh = function () {
  24778. return this._renderingMesh;
  24779. };
  24780. /**
  24781. * Returns the submesh material.
  24782. */
  24783. SubMesh.prototype.getMaterial = function () {
  24784. var rootMaterial = this._renderingMesh.material;
  24785. if (rootMaterial && rootMaterial.getSubMaterial) {
  24786. var multiMaterial = rootMaterial;
  24787. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  24788. if (this._currentMaterial !== effectiveMaterial) {
  24789. this._currentMaterial = effectiveMaterial;
  24790. this._materialDefines = null;
  24791. }
  24792. return effectiveMaterial;
  24793. }
  24794. if (!rootMaterial) {
  24795. return this._mesh.getScene().defaultMaterial;
  24796. }
  24797. return rootMaterial;
  24798. };
  24799. // Methods
  24800. /**
  24801. * Sets a new updated BoundingInfo object to the submesh.
  24802. * Returns the SubMesh.
  24803. */
  24804. SubMesh.prototype.refreshBoundingInfo = function () {
  24805. this._lastColliderWorldVertices = null;
  24806. if (this.IsGlobal) {
  24807. return this;
  24808. }
  24809. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24810. if (!data) {
  24811. this._boundingInfo = this._mesh._boundingInfo;
  24812. return this;
  24813. }
  24814. var indices = this._renderingMesh.getIndices();
  24815. var extend;
  24816. //is this the only submesh?
  24817. if (this.indexStart === 0 && this.indexCount === indices.length) {
  24818. var boundingInfo = this._renderingMesh.getBoundingInfo();
  24819. if (!boundingInfo) {
  24820. return this;
  24821. }
  24822. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  24823. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  24824. }
  24825. else {
  24826. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  24827. }
  24828. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24829. return this;
  24830. };
  24831. SubMesh.prototype._checkCollision = function (collider) {
  24832. var boundingInfo = this._renderingMesh.getBoundingInfo();
  24833. if (!boundingInfo) {
  24834. return false;
  24835. }
  24836. return boundingInfo._checkCollision(collider);
  24837. };
  24838. /**
  24839. * Updates the submesh BoundingInfo.
  24840. * Returns the Submesh.
  24841. */
  24842. SubMesh.prototype.updateBoundingInfo = function (world) {
  24843. var boundingInfo = this.getBoundingInfo();
  24844. if (!boundingInfo) {
  24845. this.refreshBoundingInfo();
  24846. }
  24847. boundingInfo.update(world);
  24848. return this;
  24849. };
  24850. /**
  24851. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  24852. * Boolean returned.
  24853. */
  24854. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  24855. var boundingInfo = this.getBoundingInfo();
  24856. if (!boundingInfo) {
  24857. return false;
  24858. }
  24859. return boundingInfo.isInFrustum(frustumPlanes);
  24860. };
  24861. /**
  24862. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  24863. * Boolean returned.
  24864. */
  24865. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  24866. var boundingInfo = this.getBoundingInfo();
  24867. if (!boundingInfo) {
  24868. return false;
  24869. }
  24870. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  24871. };
  24872. /**
  24873. * Renders the submesh.
  24874. * Returns it.
  24875. */
  24876. SubMesh.prototype.render = function (enableAlphaMode) {
  24877. this._renderingMesh.render(this, enableAlphaMode);
  24878. return this;
  24879. };
  24880. /**
  24881. * Returns a new Index Buffer.
  24882. * Type returned : WebGLBuffer.
  24883. */
  24884. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  24885. if (!this._linesIndexBuffer) {
  24886. var linesIndices = [];
  24887. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  24888. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  24889. }
  24890. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  24891. this.linesIndexCount = linesIndices.length;
  24892. }
  24893. return this._linesIndexBuffer;
  24894. };
  24895. /**
  24896. * True is the passed Ray intersects the submesh bounding box.
  24897. * Boolean returned.
  24898. */
  24899. SubMesh.prototype.canIntersects = function (ray) {
  24900. var boundingInfo = this.getBoundingInfo();
  24901. if (!boundingInfo) {
  24902. return false;
  24903. }
  24904. return ray.intersectsBox(boundingInfo.boundingBox);
  24905. };
  24906. /**
  24907. * Returns an object IntersectionInfo.
  24908. */
  24909. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  24910. var intersectInfo = null;
  24911. // LineMesh first as it's also a Mesh...
  24912. if (this._mesh instanceof BABYLON.LinesMesh) {
  24913. var lineMesh = this._mesh;
  24914. // Line test
  24915. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  24916. var p0 = positions[indices[index]];
  24917. var p1 = positions[indices[index + 1]];
  24918. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  24919. if (length < 0) {
  24920. continue;
  24921. }
  24922. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  24923. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  24924. if (fastCheck) {
  24925. break;
  24926. }
  24927. }
  24928. }
  24929. }
  24930. else {
  24931. // Triangles test
  24932. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  24933. var p0 = positions[indices[index]];
  24934. var p1 = positions[indices[index + 1]];
  24935. var p2 = positions[indices[index + 2]];
  24936. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  24937. if (currentIntersectInfo) {
  24938. if (currentIntersectInfo.distance < 0) {
  24939. continue;
  24940. }
  24941. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  24942. intersectInfo = currentIntersectInfo;
  24943. intersectInfo.faceId = index / 3;
  24944. if (fastCheck) {
  24945. break;
  24946. }
  24947. }
  24948. }
  24949. }
  24950. }
  24951. return intersectInfo;
  24952. };
  24953. SubMesh.prototype._rebuild = function () {
  24954. if (this._linesIndexBuffer) {
  24955. this._linesIndexBuffer = null;
  24956. }
  24957. };
  24958. // Clone
  24959. /**
  24960. * Creates a new Submesh from the passed Mesh.
  24961. */
  24962. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  24963. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  24964. if (!this.IsGlobal) {
  24965. var boundingInfo = this.getBoundingInfo();
  24966. if (!boundingInfo) {
  24967. return result;
  24968. }
  24969. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  24970. }
  24971. return result;
  24972. };
  24973. // Dispose
  24974. /**
  24975. * Disposes the Submesh.
  24976. * Returns nothing.
  24977. */
  24978. SubMesh.prototype.dispose = function () {
  24979. if (this._linesIndexBuffer) {
  24980. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  24981. this._linesIndexBuffer = null;
  24982. }
  24983. // Remove from mesh
  24984. var index = this._mesh.subMeshes.indexOf(this);
  24985. this._mesh.subMeshes.splice(index, 1);
  24986. };
  24987. // Statics
  24988. /**
  24989. * Creates a new Submesh from the passed parameters :
  24990. * - materialIndex (integer) : the index of the main mesh material.
  24991. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  24992. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  24993. * - mesh (Mesh) : the main mesh to create the submesh from.
  24994. * - renderingMesh (optional Mesh) : rendering mesh.
  24995. */
  24996. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  24997. var minVertexIndex = Number.MAX_VALUE;
  24998. var maxVertexIndex = -Number.MAX_VALUE;
  24999. renderingMesh = (renderingMesh || mesh);
  25000. var indices = renderingMesh.getIndices();
  25001. for (var index = startIndex; index < startIndex + indexCount; index++) {
  25002. var vertexIndex = indices[index];
  25003. if (vertexIndex < minVertexIndex)
  25004. minVertexIndex = vertexIndex;
  25005. if (vertexIndex > maxVertexIndex)
  25006. maxVertexIndex = vertexIndex;
  25007. }
  25008. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  25009. };
  25010. return SubMesh;
  25011. }(BaseSubMesh));
  25012. BABYLON.SubMesh = SubMesh;
  25013. })(BABYLON || (BABYLON = {}));
  25014. //# sourceMappingURL=babylon.subMesh.js.map
  25015. var BABYLON;
  25016. (function (BABYLON) {
  25017. var EffectFallbacks = /** @class */ (function () {
  25018. function EffectFallbacks() {
  25019. this._defines = {};
  25020. this._currentRank = 32;
  25021. this._maxRank = -1;
  25022. }
  25023. EffectFallbacks.prototype.unBindMesh = function () {
  25024. this._mesh = null;
  25025. };
  25026. EffectFallbacks.prototype.addFallback = function (rank, define) {
  25027. if (!this._defines[rank]) {
  25028. if (rank < this._currentRank) {
  25029. this._currentRank = rank;
  25030. }
  25031. if (rank > this._maxRank) {
  25032. this._maxRank = rank;
  25033. }
  25034. this._defines[rank] = new Array();
  25035. }
  25036. this._defines[rank].push(define);
  25037. };
  25038. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  25039. this._meshRank = rank;
  25040. this._mesh = mesh;
  25041. if (rank < this._currentRank) {
  25042. this._currentRank = rank;
  25043. }
  25044. if (rank > this._maxRank) {
  25045. this._maxRank = rank;
  25046. }
  25047. };
  25048. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  25049. get: function () {
  25050. return this._currentRank <= this._maxRank;
  25051. },
  25052. enumerable: true,
  25053. configurable: true
  25054. });
  25055. EffectFallbacks.prototype.reduce = function (currentDefines) {
  25056. // First we try to switch to CPU skinning
  25057. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  25058. this._mesh.computeBonesUsingShaders = false;
  25059. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  25060. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  25061. var scene = this._mesh.getScene();
  25062. for (var index = 0; index < scene.meshes.length; index++) {
  25063. var otherMesh = scene.meshes[index];
  25064. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  25065. otherMesh.computeBonesUsingShaders = false;
  25066. }
  25067. }
  25068. }
  25069. else {
  25070. var currentFallbacks = this._defines[this._currentRank];
  25071. if (currentFallbacks) {
  25072. for (var index = 0; index < currentFallbacks.length; index++) {
  25073. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  25074. }
  25075. }
  25076. this._currentRank++;
  25077. }
  25078. return currentDefines;
  25079. };
  25080. return EffectFallbacks;
  25081. }());
  25082. BABYLON.EffectFallbacks = EffectFallbacks;
  25083. var EffectCreationOptions = /** @class */ (function () {
  25084. function EffectCreationOptions() {
  25085. }
  25086. return EffectCreationOptions;
  25087. }());
  25088. BABYLON.EffectCreationOptions = EffectCreationOptions;
  25089. var Effect = /** @class */ (function () {
  25090. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  25091. if (samplers === void 0) { samplers = null; }
  25092. if (defines === void 0) { defines = null; }
  25093. if (fallbacks === void 0) { fallbacks = null; }
  25094. if (onCompiled === void 0) { onCompiled = null; }
  25095. if (onError === void 0) { onError = null; }
  25096. var _this = this;
  25097. this.uniqueId = 0;
  25098. this.onCompileObservable = new BABYLON.Observable();
  25099. this.onErrorObservable = new BABYLON.Observable();
  25100. this.onBindObservable = new BABYLON.Observable();
  25101. this._uniformBuffersNames = {};
  25102. this._isReady = false;
  25103. this._compilationError = "";
  25104. this.name = baseName;
  25105. if (attributesNamesOrOptions.attributes) {
  25106. var options = attributesNamesOrOptions;
  25107. this._engine = uniformsNamesOrEngine;
  25108. this._attributesNames = options.attributes;
  25109. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  25110. this._samplers = options.samplers;
  25111. this.defines = options.defines;
  25112. this.onError = options.onError;
  25113. this.onCompiled = options.onCompiled;
  25114. this._fallbacks = options.fallbacks;
  25115. this._indexParameters = options.indexParameters;
  25116. if (options.uniformBuffersNames) {
  25117. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  25118. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  25119. }
  25120. }
  25121. }
  25122. else {
  25123. this._engine = engine;
  25124. this.defines = defines;
  25125. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  25126. this._samplers = samplers;
  25127. this._attributesNames = attributesNamesOrOptions;
  25128. this.onError = onError;
  25129. this.onCompiled = onCompiled;
  25130. this._indexParameters = indexParameters;
  25131. this._fallbacks = fallbacks;
  25132. }
  25133. this.uniqueId = Effect._uniqueIdSeed++;
  25134. var vertexSource;
  25135. var fragmentSource;
  25136. if (baseName.vertexElement) {
  25137. vertexSource = document.getElementById(baseName.vertexElement);
  25138. if (!vertexSource) {
  25139. vertexSource = baseName.vertexElement;
  25140. }
  25141. }
  25142. else {
  25143. vertexSource = baseName.vertex || baseName;
  25144. }
  25145. if (baseName.fragmentElement) {
  25146. fragmentSource = document.getElementById(baseName.fragmentElement);
  25147. if (!fragmentSource) {
  25148. fragmentSource = baseName.fragmentElement;
  25149. }
  25150. }
  25151. else {
  25152. fragmentSource = baseName.fragment || baseName;
  25153. }
  25154. this._loadVertexShader(vertexSource, function (vertexCode) {
  25155. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  25156. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  25157. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  25158. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  25159. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  25160. if (baseName) {
  25161. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  25162. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  25163. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  25164. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  25165. }
  25166. else {
  25167. _this._vertexSourceCode = migratedVertexCode;
  25168. _this._fragmentSourceCode = migratedFragmentCode;
  25169. }
  25170. _this._prepareEffect();
  25171. });
  25172. });
  25173. });
  25174. });
  25175. });
  25176. });
  25177. }
  25178. Object.defineProperty(Effect.prototype, "key", {
  25179. get: function () {
  25180. return this._key;
  25181. },
  25182. enumerable: true,
  25183. configurable: true
  25184. });
  25185. // Properties
  25186. Effect.prototype.isReady = function () {
  25187. return this._isReady;
  25188. };
  25189. Effect.prototype.getEngine = function () {
  25190. return this._engine;
  25191. };
  25192. Effect.prototype.getProgram = function () {
  25193. return this._program;
  25194. };
  25195. Effect.prototype.getAttributesNames = function () {
  25196. return this._attributesNames;
  25197. };
  25198. Effect.prototype.getAttributeLocation = function (index) {
  25199. return this._attributes[index];
  25200. };
  25201. Effect.prototype.getAttributeLocationByName = function (name) {
  25202. var index = this._attributesNames.indexOf(name);
  25203. return this._attributes[index];
  25204. };
  25205. Effect.prototype.getAttributesCount = function () {
  25206. return this._attributes.length;
  25207. };
  25208. Effect.prototype.getUniformIndex = function (uniformName) {
  25209. return this._uniformsNames.indexOf(uniformName);
  25210. };
  25211. Effect.prototype.getUniform = function (uniformName) {
  25212. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  25213. };
  25214. Effect.prototype.getSamplers = function () {
  25215. return this._samplers;
  25216. };
  25217. Effect.prototype.getCompilationError = function () {
  25218. return this._compilationError;
  25219. };
  25220. // Methods
  25221. Effect.prototype.executeWhenCompiled = function (func) {
  25222. if (this.isReady()) {
  25223. func(this);
  25224. return;
  25225. }
  25226. this.onCompileObservable.add(function (effect) {
  25227. func(effect);
  25228. });
  25229. };
  25230. Effect.prototype._loadVertexShader = function (vertex, callback) {
  25231. if (BABYLON.Tools.IsWindowObjectExist()) {
  25232. // DOM element ?
  25233. if (vertex instanceof HTMLElement) {
  25234. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  25235. callback(vertexCode);
  25236. return;
  25237. }
  25238. }
  25239. // Base64 encoded ?
  25240. if (vertex.substr(0, 7) === "base64:") {
  25241. var vertexBinary = window.atob(vertex.substr(7));
  25242. callback(vertexBinary);
  25243. return;
  25244. }
  25245. // Is in local store ?
  25246. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  25247. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  25248. return;
  25249. }
  25250. var vertexShaderUrl;
  25251. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  25252. vertexShaderUrl = vertex;
  25253. }
  25254. else {
  25255. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  25256. }
  25257. // Vertex shader
  25258. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  25259. };
  25260. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  25261. if (BABYLON.Tools.IsWindowObjectExist()) {
  25262. // DOM element ?
  25263. if (fragment instanceof HTMLElement) {
  25264. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  25265. callback(fragmentCode);
  25266. return;
  25267. }
  25268. }
  25269. // Base64 encoded ?
  25270. if (fragment.substr(0, 7) === "base64:") {
  25271. var fragmentBinary = window.atob(fragment.substr(7));
  25272. callback(fragmentBinary);
  25273. return;
  25274. }
  25275. // Is in local store ?
  25276. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  25277. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  25278. return;
  25279. }
  25280. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  25281. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  25282. return;
  25283. }
  25284. var fragmentShaderUrl;
  25285. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  25286. fragmentShaderUrl = fragment;
  25287. }
  25288. else {
  25289. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  25290. }
  25291. // Fragment shader
  25292. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  25293. };
  25294. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  25295. // Rebuild shaders source code
  25296. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  25297. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  25298. vertexCode = prefix + vertexCode;
  25299. fragmentCode = prefix + fragmentCode;
  25300. // Number lines of shaders source code
  25301. var i = 2;
  25302. var regex = /\n/gm;
  25303. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  25304. i = 2;
  25305. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  25306. // Dump shaders name and formatted source code
  25307. if (this.name.vertexElement) {
  25308. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  25309. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  25310. }
  25311. else if (this.name.vertex) {
  25312. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  25313. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  25314. }
  25315. else {
  25316. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  25317. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  25318. }
  25319. };
  25320. ;
  25321. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  25322. var preparedSourceCode = this._processPrecision(sourceCode);
  25323. if (this._engine.webGLVersion == 1) {
  25324. callback(preparedSourceCode);
  25325. return;
  25326. }
  25327. // Already converted
  25328. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  25329. callback(preparedSourceCode.replace("#version 300 es", ""));
  25330. return;
  25331. }
  25332. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  25333. // Remove extensions
  25334. // #extension GL_OES_standard_derivatives : enable
  25335. // #extension GL_EXT_shader_texture_lod : enable
  25336. // #extension GL_EXT_frag_depth : enable
  25337. // #extension GL_EXT_draw_buffers : require
  25338. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  25339. var result = preparedSourceCode.replace(regex, "");
  25340. // Migrate to GLSL v300
  25341. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  25342. result = result.replace(/attribute[ \t]/g, "in ");
  25343. result = result.replace(/[ \t]attribute/g, " in");
  25344. if (isFragment) {
  25345. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  25346. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  25347. result = result.replace(/texture2D\s*\(/g, "texture(");
  25348. result = result.replace(/textureCube\s*\(/g, "texture(");
  25349. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  25350. result = result.replace(/gl_FragColor/g, "glFragColor");
  25351. result = result.replace(/gl_FragData/g, "glFragData");
  25352. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  25353. }
  25354. callback(result);
  25355. };
  25356. Effect.prototype._processIncludes = function (sourceCode, callback) {
  25357. var _this = this;
  25358. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  25359. var match = regex.exec(sourceCode);
  25360. var returnValue = new String(sourceCode);
  25361. while (match != null) {
  25362. var includeFile = match[1];
  25363. // Uniform declaration
  25364. if (includeFile.indexOf("__decl__") !== -1) {
  25365. includeFile = includeFile.replace(/__decl__/, "");
  25366. if (this._engine.supportsUniformBuffers) {
  25367. includeFile = includeFile.replace(/Vertex/, "Ubo");
  25368. includeFile = includeFile.replace(/Fragment/, "Ubo");
  25369. }
  25370. includeFile = includeFile + "Declaration";
  25371. }
  25372. if (Effect.IncludesShadersStore[includeFile]) {
  25373. // Substitution
  25374. var includeContent = Effect.IncludesShadersStore[includeFile];
  25375. if (match[2]) {
  25376. var splits = match[3].split(",");
  25377. for (var index = 0; index < splits.length; index += 2) {
  25378. var source = new RegExp(splits[index], "g");
  25379. var dest = splits[index + 1];
  25380. includeContent = includeContent.replace(source, dest);
  25381. }
  25382. }
  25383. if (match[4]) {
  25384. var indexString = match[5];
  25385. if (indexString.indexOf("..") !== -1) {
  25386. var indexSplits = indexString.split("..");
  25387. var minIndex = parseInt(indexSplits[0]);
  25388. var maxIndex = parseInt(indexSplits[1]);
  25389. var sourceIncludeContent = includeContent.slice(0);
  25390. includeContent = "";
  25391. if (isNaN(maxIndex)) {
  25392. maxIndex = this._indexParameters[indexSplits[1]];
  25393. }
  25394. for (var i = minIndex; i < maxIndex; i++) {
  25395. if (!this._engine.supportsUniformBuffers) {
  25396. // Ubo replacement
  25397. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  25398. return p1 + "{X}";
  25399. });
  25400. }
  25401. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  25402. }
  25403. }
  25404. else {
  25405. if (!this._engine.supportsUniformBuffers) {
  25406. // Ubo replacement
  25407. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  25408. return p1 + "{X}";
  25409. });
  25410. }
  25411. includeContent = includeContent.replace(/\{X\}/g, indexString);
  25412. }
  25413. }
  25414. // Replace
  25415. returnValue = returnValue.replace(match[0], includeContent);
  25416. }
  25417. else {
  25418. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  25419. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  25420. Effect.IncludesShadersStore[includeFile] = fileContent;
  25421. _this._processIncludes(returnValue, callback);
  25422. });
  25423. return;
  25424. }
  25425. match = regex.exec(sourceCode);
  25426. }
  25427. callback(returnValue);
  25428. };
  25429. Effect.prototype._processPrecision = function (source) {
  25430. if (source.indexOf("precision highp float") === -1) {
  25431. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  25432. source = "precision mediump float;\n" + source;
  25433. }
  25434. else {
  25435. source = "precision highp float;\n" + source;
  25436. }
  25437. }
  25438. else {
  25439. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  25440. source = source.replace("precision highp float", "precision mediump float");
  25441. }
  25442. }
  25443. return source;
  25444. };
  25445. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  25446. var _this = this;
  25447. this._isReady = false;
  25448. this._vertexSourceCodeOverride = vertexSourceCode;
  25449. this._fragmentSourceCodeOverride = fragmentSourceCode;
  25450. this.onError = function (effect, error) {
  25451. if (onError) {
  25452. onError(error);
  25453. }
  25454. };
  25455. this.onCompiled = function () {
  25456. var scenes = _this.getEngine().scenes;
  25457. for (var i = 0; i < scenes.length; i++) {
  25458. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25459. }
  25460. if (onCompiled) {
  25461. onCompiled(_this._program);
  25462. }
  25463. };
  25464. this._fallbacks = null;
  25465. this._prepareEffect();
  25466. };
  25467. Effect.prototype._prepareEffect = function () {
  25468. var attributesNames = this._attributesNames;
  25469. var defines = this.defines;
  25470. var fallbacks = this._fallbacks;
  25471. this._valueCache = {};
  25472. var previousProgram = this._program;
  25473. try {
  25474. var engine = this._engine;
  25475. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  25476. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride);
  25477. }
  25478. else {
  25479. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines);
  25480. }
  25481. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  25482. if (engine.webGLVersion > 1) {
  25483. for (var name in this._uniformBuffersNames) {
  25484. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  25485. }
  25486. }
  25487. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  25488. this._attributes = engine.getAttributes(this._program, attributesNames);
  25489. var index;
  25490. for (index = 0; index < this._samplers.length; index++) {
  25491. var sampler = this.getUniform(this._samplers[index]);
  25492. if (sampler == null) {
  25493. this._samplers.splice(index, 1);
  25494. index--;
  25495. }
  25496. }
  25497. engine.bindSamplers(this);
  25498. this._compilationError = "";
  25499. this._isReady = true;
  25500. if (this.onCompiled) {
  25501. this.onCompiled(this);
  25502. }
  25503. this.onCompileObservable.notifyObservers(this);
  25504. this.onCompileObservable.clear();
  25505. // Unbind mesh reference in fallbacks
  25506. if (this._fallbacks) {
  25507. this._fallbacks.unBindMesh();
  25508. }
  25509. if (previousProgram) {
  25510. this.getEngine()._deleteProgram(previousProgram);
  25511. }
  25512. }
  25513. catch (e) {
  25514. this._compilationError = e.message;
  25515. // Let's go through fallbacks then
  25516. BABYLON.Tools.Error("Unable to compile effect:");
  25517. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  25518. return " " + uniform;
  25519. }));
  25520. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  25521. return " " + attribute;
  25522. }));
  25523. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  25524. BABYLON.Tools.Error("Error: " + this._compilationError);
  25525. if (previousProgram) {
  25526. this._program = previousProgram;
  25527. this._isReady = true;
  25528. if (this.onError) {
  25529. this.onError(this, this._compilationError);
  25530. }
  25531. this.onErrorObservable.notifyObservers(this);
  25532. }
  25533. if (fallbacks && fallbacks.isMoreFallbacks) {
  25534. BABYLON.Tools.Error("Trying next fallback.");
  25535. this.defines = fallbacks.reduce(this.defines);
  25536. this._prepareEffect();
  25537. }
  25538. else {
  25539. if (this.onError) {
  25540. this.onError(this, this._compilationError);
  25541. }
  25542. this.onErrorObservable.notifyObservers(this);
  25543. this.onErrorObservable.clear();
  25544. // Unbind mesh reference in fallbacks
  25545. if (this._fallbacks) {
  25546. this._fallbacks.unBindMesh();
  25547. }
  25548. }
  25549. }
  25550. };
  25551. Object.defineProperty(Effect.prototype, "isSupported", {
  25552. get: function () {
  25553. return this._compilationError === "";
  25554. },
  25555. enumerable: true,
  25556. configurable: true
  25557. });
  25558. Effect.prototype._bindTexture = function (channel, texture) {
  25559. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  25560. };
  25561. Effect.prototype.setTexture = function (channel, texture) {
  25562. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  25563. };
  25564. Effect.prototype.setTextureArray = function (channel, textures) {
  25565. if (this._samplers.indexOf(channel + "Ex") === -1) {
  25566. var initialPos = this._samplers.indexOf(channel);
  25567. for (var index = 1; index < textures.length; index++) {
  25568. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  25569. }
  25570. }
  25571. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  25572. };
  25573. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  25574. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  25575. };
  25576. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  25577. var cache = this._valueCache[uniformName];
  25578. var flag = matrix.updateFlag;
  25579. if (cache !== undefined && cache === flag) {
  25580. return false;
  25581. }
  25582. this._valueCache[uniformName] = flag;
  25583. return true;
  25584. };
  25585. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  25586. var cache = this._valueCache[uniformName];
  25587. if (!cache) {
  25588. cache = [x, y];
  25589. this._valueCache[uniformName] = cache;
  25590. return true;
  25591. }
  25592. var changed = false;
  25593. if (cache[0] !== x) {
  25594. cache[0] = x;
  25595. changed = true;
  25596. }
  25597. if (cache[1] !== y) {
  25598. cache[1] = y;
  25599. changed = true;
  25600. }
  25601. return changed;
  25602. };
  25603. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  25604. var cache = this._valueCache[uniformName];
  25605. if (!cache) {
  25606. cache = [x, y, z];
  25607. this._valueCache[uniformName] = cache;
  25608. return true;
  25609. }
  25610. var changed = false;
  25611. if (cache[0] !== x) {
  25612. cache[0] = x;
  25613. changed = true;
  25614. }
  25615. if (cache[1] !== y) {
  25616. cache[1] = y;
  25617. changed = true;
  25618. }
  25619. if (cache[2] !== z) {
  25620. cache[2] = z;
  25621. changed = true;
  25622. }
  25623. return changed;
  25624. };
  25625. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  25626. var cache = this._valueCache[uniformName];
  25627. if (!cache) {
  25628. cache = [x, y, z, w];
  25629. this._valueCache[uniformName] = cache;
  25630. return true;
  25631. }
  25632. var changed = false;
  25633. if (cache[0] !== x) {
  25634. cache[0] = x;
  25635. changed = true;
  25636. }
  25637. if (cache[1] !== y) {
  25638. cache[1] = y;
  25639. changed = true;
  25640. }
  25641. if (cache[2] !== z) {
  25642. cache[2] = z;
  25643. changed = true;
  25644. }
  25645. if (cache[3] !== w) {
  25646. cache[3] = w;
  25647. changed = true;
  25648. }
  25649. return changed;
  25650. };
  25651. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  25652. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  25653. return;
  25654. }
  25655. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  25656. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  25657. };
  25658. Effect.prototype.bindUniformBlock = function (blockName, index) {
  25659. this._engine.bindUniformBlock(this._program, blockName, index);
  25660. };
  25661. Effect.prototype.setIntArray = function (uniformName, array) {
  25662. this._valueCache[uniformName] = null;
  25663. this._engine.setIntArray(this.getUniform(uniformName), array);
  25664. return this;
  25665. };
  25666. Effect.prototype.setIntArray2 = function (uniformName, array) {
  25667. this._valueCache[uniformName] = null;
  25668. this._engine.setIntArray2(this.getUniform(uniformName), array);
  25669. return this;
  25670. };
  25671. Effect.prototype.setIntArray3 = function (uniformName, array) {
  25672. this._valueCache[uniformName] = null;
  25673. this._engine.setIntArray3(this.getUniform(uniformName), array);
  25674. return this;
  25675. };
  25676. Effect.prototype.setIntArray4 = function (uniformName, array) {
  25677. this._valueCache[uniformName] = null;
  25678. this._engine.setIntArray4(this.getUniform(uniformName), array);
  25679. return this;
  25680. };
  25681. Effect.prototype.setFloatArray = function (uniformName, array) {
  25682. this._valueCache[uniformName] = null;
  25683. this._engine.setFloatArray(this.getUniform(uniformName), array);
  25684. return this;
  25685. };
  25686. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  25687. this._valueCache[uniformName] = null;
  25688. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  25689. return this;
  25690. };
  25691. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  25692. this._valueCache[uniformName] = null;
  25693. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  25694. return this;
  25695. };
  25696. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  25697. this._valueCache[uniformName] = null;
  25698. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  25699. return this;
  25700. };
  25701. Effect.prototype.setArray = function (uniformName, array) {
  25702. this._valueCache[uniformName] = null;
  25703. this._engine.setArray(this.getUniform(uniformName), array);
  25704. return this;
  25705. };
  25706. Effect.prototype.setArray2 = function (uniformName, array) {
  25707. this._valueCache[uniformName] = null;
  25708. this._engine.setArray2(this.getUniform(uniformName), array);
  25709. return this;
  25710. };
  25711. Effect.prototype.setArray3 = function (uniformName, array) {
  25712. this._valueCache[uniformName] = null;
  25713. this._engine.setArray3(this.getUniform(uniformName), array);
  25714. return this;
  25715. };
  25716. Effect.prototype.setArray4 = function (uniformName, array) {
  25717. this._valueCache[uniformName] = null;
  25718. this._engine.setArray4(this.getUniform(uniformName), array);
  25719. return this;
  25720. };
  25721. Effect.prototype.setMatrices = function (uniformName, matrices) {
  25722. if (!matrices) {
  25723. return this;
  25724. }
  25725. this._valueCache[uniformName] = null;
  25726. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  25727. return this;
  25728. };
  25729. Effect.prototype.setMatrix = function (uniformName, matrix) {
  25730. if (this._cacheMatrix(uniformName, matrix)) {
  25731. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  25732. }
  25733. return this;
  25734. };
  25735. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  25736. this._valueCache[uniformName] = null;
  25737. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  25738. return this;
  25739. };
  25740. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  25741. this._valueCache[uniformName] = null;
  25742. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  25743. return this;
  25744. };
  25745. Effect.prototype.setFloat = function (uniformName, value) {
  25746. var cache = this._valueCache[uniformName];
  25747. if (cache !== undefined && cache === value)
  25748. return this;
  25749. this._valueCache[uniformName] = value;
  25750. this._engine.setFloat(this.getUniform(uniformName), value);
  25751. return this;
  25752. };
  25753. Effect.prototype.setBool = function (uniformName, bool) {
  25754. var cache = this._valueCache[uniformName];
  25755. if (cache !== undefined && cache === bool)
  25756. return this;
  25757. this._valueCache[uniformName] = bool;
  25758. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  25759. return this;
  25760. };
  25761. Effect.prototype.setVector2 = function (uniformName, vector2) {
  25762. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  25763. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  25764. }
  25765. return this;
  25766. };
  25767. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  25768. if (this._cacheFloat2(uniformName, x, y)) {
  25769. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  25770. }
  25771. return this;
  25772. };
  25773. Effect.prototype.setVector3 = function (uniformName, vector3) {
  25774. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  25775. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  25776. }
  25777. return this;
  25778. };
  25779. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  25780. if (this._cacheFloat3(uniformName, x, y, z)) {
  25781. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  25782. }
  25783. return this;
  25784. };
  25785. Effect.prototype.setVector4 = function (uniformName, vector4) {
  25786. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  25787. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  25788. }
  25789. return this;
  25790. };
  25791. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  25792. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  25793. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  25794. }
  25795. return this;
  25796. };
  25797. Effect.prototype.setColor3 = function (uniformName, color3) {
  25798. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  25799. this._engine.setColor3(this.getUniform(uniformName), color3);
  25800. }
  25801. return this;
  25802. };
  25803. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  25804. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  25805. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  25806. }
  25807. return this;
  25808. };
  25809. Effect.ResetCache = function () {
  25810. Effect._baseCache = {};
  25811. };
  25812. Effect._uniqueIdSeed = 0;
  25813. Effect._baseCache = {};
  25814. // Statics
  25815. Effect.ShadersStore = {};
  25816. Effect.IncludesShadersStore = {};
  25817. return Effect;
  25818. }());
  25819. BABYLON.Effect = Effect;
  25820. })(BABYLON || (BABYLON = {}));
  25821. //# sourceMappingURL=babylon.effect.js.map
  25822. var BABYLON;
  25823. (function (BABYLON) {
  25824. var MaterialHelper = /** @class */ (function () {
  25825. function MaterialHelper() {
  25826. }
  25827. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  25828. defines._needUVs = true;
  25829. defines[key] = true;
  25830. if (texture.getTextureMatrix().isIdentity(true)) {
  25831. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  25832. if (texture.coordinatesIndex === 0) {
  25833. defines["MAINUV1"] = true;
  25834. }
  25835. else {
  25836. defines["MAINUV2"] = true;
  25837. }
  25838. }
  25839. else {
  25840. defines[key + "DIRECTUV"] = 0;
  25841. }
  25842. };
  25843. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  25844. var matrix = texture.getTextureMatrix();
  25845. if (!matrix.isIdentity(true)) {
  25846. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  25847. }
  25848. };
  25849. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  25850. if (defines._areMiscDirty) {
  25851. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  25852. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  25853. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  25854. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  25855. }
  25856. };
  25857. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  25858. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  25859. var changed = false;
  25860. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  25861. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  25862. changed = true;
  25863. }
  25864. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  25865. defines["ALPHATEST"] = !defines["ALPHATEST"];
  25866. changed = true;
  25867. }
  25868. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  25869. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  25870. changed = true;
  25871. }
  25872. if (defines["INSTANCES"] !== useInstances) {
  25873. defines["INSTANCES"] = useInstances;
  25874. changed = true;
  25875. }
  25876. if (changed) {
  25877. defines.markAsUnprocessed();
  25878. }
  25879. };
  25880. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  25881. if (useMorphTargets === void 0) { useMorphTargets = false; }
  25882. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  25883. return false;
  25884. }
  25885. defines._normals = defines._needNormals;
  25886. defines._uvs = defines._needUVs;
  25887. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  25888. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  25889. defines["TANGENT"] = true;
  25890. }
  25891. if (defines._needUVs) {
  25892. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  25893. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  25894. }
  25895. else {
  25896. defines["UV1"] = false;
  25897. defines["UV2"] = false;
  25898. }
  25899. if (useVertexColor) {
  25900. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  25901. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  25902. }
  25903. if (useBones) {
  25904. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  25905. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  25906. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  25907. }
  25908. else {
  25909. defines["NUM_BONE_INFLUENCERS"] = 0;
  25910. defines["BonesPerMesh"] = 0;
  25911. }
  25912. }
  25913. if (useMorphTargets) {
  25914. if (mesh.morphTargetManager) {
  25915. var manager = mesh.morphTargetManager;
  25916. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  25917. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  25918. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  25919. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  25920. }
  25921. else {
  25922. defines["MORPHTARGETS_TANGENT"] = false;
  25923. defines["MORPHTARGETS_NORMAL"] = false;
  25924. defines["MORPHTARGETS"] = false;
  25925. defines["NUM_MORPH_INFLUENCERS"] = 0;
  25926. }
  25927. }
  25928. return true;
  25929. };
  25930. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  25931. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25932. if (disableLighting === void 0) { disableLighting = false; }
  25933. if (!defines._areLightsDirty) {
  25934. return defines._needNormals;
  25935. }
  25936. var lightIndex = 0;
  25937. var needNormals = false;
  25938. var needRebuild = false;
  25939. var lightmapMode = false;
  25940. var shadowEnabled = false;
  25941. var specularEnabled = false;
  25942. if (scene.lightsEnabled && !disableLighting) {
  25943. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  25944. var light = _a[_i];
  25945. needNormals = true;
  25946. if (defines["LIGHT" + lightIndex] === undefined) {
  25947. needRebuild = true;
  25948. }
  25949. defines["LIGHT" + lightIndex] = true;
  25950. defines["SPOTLIGHT" + lightIndex] = false;
  25951. defines["HEMILIGHT" + lightIndex] = false;
  25952. defines["POINTLIGHT" + lightIndex] = false;
  25953. defines["DIRLIGHT" + lightIndex] = false;
  25954. var type;
  25955. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  25956. type = "SPOTLIGHT" + lightIndex;
  25957. }
  25958. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  25959. type = "HEMILIGHT" + lightIndex;
  25960. }
  25961. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  25962. type = "POINTLIGHT" + lightIndex;
  25963. }
  25964. else {
  25965. type = "DIRLIGHT" + lightIndex;
  25966. }
  25967. defines[type] = true;
  25968. // Specular
  25969. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  25970. specularEnabled = true;
  25971. }
  25972. // Shadows
  25973. defines["SHADOW" + lightIndex] = false;
  25974. defines["SHADOWPCF" + lightIndex] = false;
  25975. defines["SHADOWESM" + lightIndex] = false;
  25976. defines["SHADOWCUBE" + lightIndex] = false;
  25977. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  25978. var shadowGenerator = light.getShadowGenerator();
  25979. if (shadowGenerator) {
  25980. shadowEnabled = true;
  25981. shadowGenerator.prepareDefines(defines, lightIndex);
  25982. }
  25983. }
  25984. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  25985. lightmapMode = true;
  25986. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  25987. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  25988. }
  25989. else {
  25990. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  25991. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  25992. }
  25993. lightIndex++;
  25994. if (lightIndex === maxSimultaneousLights)
  25995. break;
  25996. }
  25997. }
  25998. defines["SPECULARTERM"] = specularEnabled;
  25999. defines["SHADOWS"] = shadowEnabled;
  26000. // Resetting all other lights if any
  26001. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  26002. if (defines["LIGHT" + index] !== undefined) {
  26003. defines["LIGHT" + index] = false;
  26004. defines["HEMILIGHT" + lightIndex] = false;
  26005. defines["POINTLIGHT" + lightIndex] = false;
  26006. defines["DIRLIGHT" + lightIndex] = false;
  26007. defines["SPOTLIGHT" + lightIndex] = false;
  26008. defines["SHADOW" + lightIndex] = false;
  26009. }
  26010. }
  26011. var caps = scene.getEngine().getCaps();
  26012. if (defines["SHADOWFLOAT"] === undefined) {
  26013. needRebuild = true;
  26014. }
  26015. defines["SHADOWFLOAT"] = shadowEnabled &&
  26016. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  26017. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  26018. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  26019. if (needRebuild) {
  26020. defines.rebuild();
  26021. }
  26022. return needNormals;
  26023. };
  26024. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  26025. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26026. var uniformsList, uniformBuffersList, samplersList, defines;
  26027. if (uniformsListOrOptions.uniformsNames) {
  26028. var options = uniformsListOrOptions;
  26029. uniformsList = options.uniformsNames;
  26030. uniformBuffersList = options.uniformBuffersNames;
  26031. samplersList = options.samplers;
  26032. defines = options.defines;
  26033. maxSimultaneousLights = options.maxSimultaneousLights;
  26034. }
  26035. else {
  26036. uniformsList = uniformsListOrOptions;
  26037. }
  26038. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  26039. if (!defines["LIGHT" + lightIndex]) {
  26040. break;
  26041. }
  26042. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  26043. if (uniformBuffersList) {
  26044. uniformBuffersList.push("Light" + lightIndex);
  26045. }
  26046. samplersList.push("shadowSampler" + lightIndex);
  26047. }
  26048. if (defines["NUM_MORPH_INFLUENCERS"]) {
  26049. uniformsList.push("morphTargetInfluences");
  26050. }
  26051. };
  26052. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  26053. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26054. if (!defines["SHADOWS"]) {
  26055. return;
  26056. }
  26057. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  26058. if (!defines["LIGHT" + lightIndex]) {
  26059. break;
  26060. }
  26061. if (lightIndex > 0) {
  26062. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  26063. }
  26064. if (defines["SHADOW" + lightIndex]) {
  26065. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  26066. }
  26067. if (defines["SHADOWPCF" + lightIndex]) {
  26068. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  26069. }
  26070. if (defines["SHADOWESM" + lightIndex]) {
  26071. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  26072. }
  26073. }
  26074. };
  26075. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  26076. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  26077. if (influencers > 0) {
  26078. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  26079. var manager = mesh.morphTargetManager;
  26080. var normal = manager.supportsNormals && defines["NORMAL"];
  26081. var tangent = manager.supportsTangents && defines["TANGENT"];
  26082. for (var index = 0; index < influencers; index++) {
  26083. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  26084. if (normal) {
  26085. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  26086. }
  26087. if (tangent) {
  26088. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  26089. }
  26090. if (attribs.length > maxAttributesCount) {
  26091. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  26092. }
  26093. }
  26094. }
  26095. };
  26096. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  26097. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  26098. fallbacks.addCPUSkinningFallback(0, mesh);
  26099. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26100. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26101. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  26102. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  26103. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  26104. }
  26105. }
  26106. };
  26107. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  26108. if (defines["INSTANCES"]) {
  26109. attribs.push("world0");
  26110. attribs.push("world1");
  26111. attribs.push("world2");
  26112. attribs.push("world3");
  26113. }
  26114. };
  26115. // Bindings
  26116. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  26117. if (light.shadowEnabled && mesh.receiveShadows) {
  26118. var shadowGenerator = light.getShadowGenerator();
  26119. if (shadowGenerator) {
  26120. shadowGenerator.bindShadowLight(lightIndex, effect);
  26121. }
  26122. }
  26123. };
  26124. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  26125. light.transferToEffect(effect, lightIndex + "");
  26126. };
  26127. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  26128. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26129. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  26130. var lightIndex = 0;
  26131. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  26132. var light = _a[_i];
  26133. var scaledIntensity = light.getScaledIntensity();
  26134. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  26135. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  26136. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  26137. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  26138. if (defines["SPECULARTERM"]) {
  26139. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  26140. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  26141. }
  26142. // Shadows
  26143. if (scene.shadowsEnabled) {
  26144. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  26145. }
  26146. light._uniformBuffer.update();
  26147. lightIndex++;
  26148. if (lightIndex === maxSimultaneousLights)
  26149. break;
  26150. }
  26151. };
  26152. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  26153. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  26154. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  26155. effect.setColor3("vFogColor", scene.fogColor);
  26156. }
  26157. };
  26158. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  26159. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  26160. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  26161. if (matrices) {
  26162. effect.setMatrices("mBones", matrices);
  26163. }
  26164. }
  26165. };
  26166. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  26167. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  26168. return;
  26169. }
  26170. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  26171. };
  26172. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  26173. if (defines["LOGARITHMICDEPTH"]) {
  26174. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  26175. }
  26176. };
  26177. MaterialHelper.BindClipPlane = function (effect, scene) {
  26178. if (scene.clipPlane) {
  26179. var clipPlane = scene.clipPlane;
  26180. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  26181. }
  26182. };
  26183. return MaterialHelper;
  26184. }());
  26185. BABYLON.MaterialHelper = MaterialHelper;
  26186. })(BABYLON || (BABYLON = {}));
  26187. //# sourceMappingURL=babylon.materialHelper.js.map
  26188. var BABYLON;
  26189. (function (BABYLON) {
  26190. var MaterialDefines = /** @class */ (function () {
  26191. function MaterialDefines() {
  26192. this._isDirty = true;
  26193. this._areLightsDirty = true;
  26194. this._areAttributesDirty = true;
  26195. this._areTexturesDirty = true;
  26196. this._areFresnelDirty = true;
  26197. this._areMiscDirty = true;
  26198. this._areImageProcessingDirty = true;
  26199. this._normals = false;
  26200. this._uvs = false;
  26201. this._needNormals = false;
  26202. this._needUVs = false;
  26203. }
  26204. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  26205. get: function () {
  26206. return this._isDirty;
  26207. },
  26208. enumerable: true,
  26209. configurable: true
  26210. });
  26211. MaterialDefines.prototype.markAsProcessed = function () {
  26212. this._isDirty = false;
  26213. this._areAttributesDirty = false;
  26214. this._areTexturesDirty = false;
  26215. this._areFresnelDirty = false;
  26216. this._areLightsDirty = false;
  26217. this._areMiscDirty = false;
  26218. this._areImageProcessingDirty = false;
  26219. };
  26220. MaterialDefines.prototype.markAsUnprocessed = function () {
  26221. this._isDirty = true;
  26222. };
  26223. MaterialDefines.prototype.markAllAsDirty = function () {
  26224. this._areTexturesDirty = true;
  26225. this._areAttributesDirty = true;
  26226. this._areLightsDirty = true;
  26227. this._areFresnelDirty = true;
  26228. this._areMiscDirty = true;
  26229. this._areImageProcessingDirty = true;
  26230. this._isDirty = true;
  26231. };
  26232. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  26233. this._areImageProcessingDirty = true;
  26234. this._isDirty = true;
  26235. };
  26236. MaterialDefines.prototype.markAsLightDirty = function () {
  26237. this._areLightsDirty = true;
  26238. this._isDirty = true;
  26239. };
  26240. MaterialDefines.prototype.markAsAttributesDirty = function () {
  26241. this._areAttributesDirty = true;
  26242. this._isDirty = true;
  26243. };
  26244. MaterialDefines.prototype.markAsTexturesDirty = function () {
  26245. this._areTexturesDirty = true;
  26246. this._isDirty = true;
  26247. };
  26248. MaterialDefines.prototype.markAsFresnelDirty = function () {
  26249. this._areFresnelDirty = true;
  26250. this._isDirty = true;
  26251. };
  26252. MaterialDefines.prototype.markAsMiscDirty = function () {
  26253. this._areMiscDirty = true;
  26254. this._isDirty = true;
  26255. };
  26256. MaterialDefines.prototype.rebuild = function () {
  26257. if (this._keys) {
  26258. delete this._keys;
  26259. }
  26260. this._keys = [];
  26261. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  26262. var key = _a[_i];
  26263. if (key[0] === "_") {
  26264. continue;
  26265. }
  26266. this._keys.push(key);
  26267. }
  26268. };
  26269. MaterialDefines.prototype.isEqual = function (other) {
  26270. if (this._keys.length !== other._keys.length) {
  26271. return false;
  26272. }
  26273. for (var index = 0; index < this._keys.length; index++) {
  26274. var prop = this._keys[index];
  26275. if (this[prop] !== other[prop]) {
  26276. return false;
  26277. }
  26278. }
  26279. return true;
  26280. };
  26281. MaterialDefines.prototype.cloneTo = function (other) {
  26282. if (this._keys.length !== other._keys.length) {
  26283. other._keys = this._keys.slice(0);
  26284. }
  26285. for (var index = 0; index < this._keys.length; index++) {
  26286. var prop = this._keys[index];
  26287. other[prop] = this[prop];
  26288. }
  26289. };
  26290. MaterialDefines.prototype.reset = function () {
  26291. for (var index = 0; index < this._keys.length; index++) {
  26292. var prop = this._keys[index];
  26293. if (typeof (this[prop]) === "number") {
  26294. this[prop] = 0;
  26295. }
  26296. else {
  26297. this[prop] = false;
  26298. }
  26299. }
  26300. };
  26301. MaterialDefines.prototype.toString = function () {
  26302. var result = "";
  26303. for (var index = 0; index < this._keys.length; index++) {
  26304. var prop = this._keys[index];
  26305. var value = this[prop];
  26306. if (typeof (value) === "number") {
  26307. result += "#define " + prop + " " + this[prop] + "\n";
  26308. }
  26309. else if (value) {
  26310. result += "#define " + prop + "\n";
  26311. }
  26312. }
  26313. return result;
  26314. };
  26315. return MaterialDefines;
  26316. }());
  26317. BABYLON.MaterialDefines = MaterialDefines;
  26318. var Material = /** @class */ (function () {
  26319. function Material(name, scene, doNotAdd) {
  26320. this.checkReadyOnEveryCall = false;
  26321. this.checkReadyOnlyOnce = false;
  26322. this.state = "";
  26323. this.alpha = 1.0;
  26324. this._backFaceCulling = true;
  26325. this.doNotSerialize = false;
  26326. this.storeEffectOnSubMeshes = false;
  26327. /**
  26328. * An event triggered when the material is disposed.
  26329. * @type {BABYLON.Observable}
  26330. */
  26331. this.onDisposeObservable = new BABYLON.Observable();
  26332. /**
  26333. * An event triggered when the material is bound.
  26334. * @type {BABYLON.Observable}
  26335. */
  26336. this.onBindObservable = new BABYLON.Observable();
  26337. /**
  26338. * An event triggered when the material is unbound.
  26339. * @type {BABYLON.Observable}
  26340. */
  26341. this.onUnBindObservable = new BABYLON.Observable();
  26342. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  26343. this._needDepthPrePass = false;
  26344. this.disableDepthWrite = false;
  26345. this.forceDepthWrite = false;
  26346. this.separateCullingPass = false;
  26347. this._fogEnabled = true;
  26348. this.pointSize = 1.0;
  26349. this.zOffset = 0;
  26350. this._wasPreviouslyReady = false;
  26351. this._fillMode = Material.TriangleFillMode;
  26352. this.name = name;
  26353. this.id = name || BABYLON.Tools.RandomId();
  26354. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26355. if (this._scene.useRightHandedSystem) {
  26356. this.sideOrientation = Material.ClockWiseSideOrientation;
  26357. }
  26358. else {
  26359. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  26360. }
  26361. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  26362. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  26363. if (!doNotAdd) {
  26364. this._scene.materials.push(this);
  26365. }
  26366. }
  26367. Object.defineProperty(Material, "TriangleFillMode", {
  26368. get: function () {
  26369. return Material._TriangleFillMode;
  26370. },
  26371. enumerable: true,
  26372. configurable: true
  26373. });
  26374. Object.defineProperty(Material, "WireFrameFillMode", {
  26375. get: function () {
  26376. return Material._WireFrameFillMode;
  26377. },
  26378. enumerable: true,
  26379. configurable: true
  26380. });
  26381. Object.defineProperty(Material, "PointFillMode", {
  26382. get: function () {
  26383. return Material._PointFillMode;
  26384. },
  26385. enumerable: true,
  26386. configurable: true
  26387. });
  26388. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  26389. get: function () {
  26390. return Material._ClockWiseSideOrientation;
  26391. },
  26392. enumerable: true,
  26393. configurable: true
  26394. });
  26395. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  26396. get: function () {
  26397. return Material._CounterClockWiseSideOrientation;
  26398. },
  26399. enumerable: true,
  26400. configurable: true
  26401. });
  26402. Object.defineProperty(Material, "TextureDirtyFlag", {
  26403. get: function () {
  26404. return Material._TextureDirtyFlag;
  26405. },
  26406. enumerable: true,
  26407. configurable: true
  26408. });
  26409. Object.defineProperty(Material, "LightDirtyFlag", {
  26410. get: function () {
  26411. return Material._LightDirtyFlag;
  26412. },
  26413. enumerable: true,
  26414. configurable: true
  26415. });
  26416. Object.defineProperty(Material, "FresnelDirtyFlag", {
  26417. get: function () {
  26418. return Material._FresnelDirtyFlag;
  26419. },
  26420. enumerable: true,
  26421. configurable: true
  26422. });
  26423. Object.defineProperty(Material, "AttributesDirtyFlag", {
  26424. get: function () {
  26425. return Material._AttributesDirtyFlag;
  26426. },
  26427. enumerable: true,
  26428. configurable: true
  26429. });
  26430. Object.defineProperty(Material, "MiscDirtyFlag", {
  26431. get: function () {
  26432. return Material._MiscDirtyFlag;
  26433. },
  26434. enumerable: true,
  26435. configurable: true
  26436. });
  26437. Object.defineProperty(Material.prototype, "backFaceCulling", {
  26438. get: function () {
  26439. return this._backFaceCulling;
  26440. },
  26441. set: function (value) {
  26442. if (this._backFaceCulling === value) {
  26443. return;
  26444. }
  26445. this._backFaceCulling = value;
  26446. this.markAsDirty(Material.TextureDirtyFlag);
  26447. },
  26448. enumerable: true,
  26449. configurable: true
  26450. });
  26451. Object.defineProperty(Material.prototype, "onDispose", {
  26452. set: function (callback) {
  26453. if (this._onDisposeObserver) {
  26454. this.onDisposeObservable.remove(this._onDisposeObserver);
  26455. }
  26456. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26457. },
  26458. enumerable: true,
  26459. configurable: true
  26460. });
  26461. Object.defineProperty(Material.prototype, "onBind", {
  26462. set: function (callback) {
  26463. if (this._onBindObserver) {
  26464. this.onBindObservable.remove(this._onBindObserver);
  26465. }
  26466. this._onBindObserver = this.onBindObservable.add(callback);
  26467. },
  26468. enumerable: true,
  26469. configurable: true
  26470. });
  26471. Object.defineProperty(Material.prototype, "alphaMode", {
  26472. get: function () {
  26473. return this._alphaMode;
  26474. },
  26475. set: function (value) {
  26476. if (this._alphaMode === value) {
  26477. return;
  26478. }
  26479. this._alphaMode = value;
  26480. this.markAsDirty(Material.TextureDirtyFlag);
  26481. },
  26482. enumerable: true,
  26483. configurable: true
  26484. });
  26485. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  26486. get: function () {
  26487. return this._needDepthPrePass;
  26488. },
  26489. set: function (value) {
  26490. if (this._needDepthPrePass === value) {
  26491. return;
  26492. }
  26493. this._needDepthPrePass = value;
  26494. if (this._needDepthPrePass) {
  26495. this.checkReadyOnEveryCall = true;
  26496. }
  26497. },
  26498. enumerable: true,
  26499. configurable: true
  26500. });
  26501. Object.defineProperty(Material.prototype, "fogEnabled", {
  26502. get: function () {
  26503. return this._fogEnabled;
  26504. },
  26505. set: function (value) {
  26506. if (this._fogEnabled === value) {
  26507. return;
  26508. }
  26509. this._fogEnabled = value;
  26510. this.markAsDirty(Material.MiscDirtyFlag);
  26511. },
  26512. enumerable: true,
  26513. configurable: true
  26514. });
  26515. Object.defineProperty(Material.prototype, "wireframe", {
  26516. get: function () {
  26517. return this._fillMode === Material.WireFrameFillMode;
  26518. },
  26519. set: function (value) {
  26520. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  26521. },
  26522. enumerable: true,
  26523. configurable: true
  26524. });
  26525. Object.defineProperty(Material.prototype, "pointsCloud", {
  26526. get: function () {
  26527. return this._fillMode === Material.PointFillMode;
  26528. },
  26529. set: function (value) {
  26530. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  26531. },
  26532. enumerable: true,
  26533. configurable: true
  26534. });
  26535. Object.defineProperty(Material.prototype, "fillMode", {
  26536. get: function () {
  26537. return this._fillMode;
  26538. },
  26539. set: function (value) {
  26540. if (this._fillMode === value) {
  26541. return;
  26542. }
  26543. this._fillMode = value;
  26544. this.markAsDirty(Material.MiscDirtyFlag);
  26545. },
  26546. enumerable: true,
  26547. configurable: true
  26548. });
  26549. /**
  26550. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26551. * subclasses should override adding information pertainent to themselves
  26552. */
  26553. Material.prototype.toString = function (fullDetails) {
  26554. var ret = "Name: " + this.name;
  26555. if (fullDetails) {
  26556. }
  26557. return ret;
  26558. };
  26559. /**
  26560. * Child classes can use it to update shaders
  26561. */
  26562. Material.prototype.getClassName = function () {
  26563. return "Material";
  26564. };
  26565. Object.defineProperty(Material.prototype, "isFrozen", {
  26566. get: function () {
  26567. return this.checkReadyOnlyOnce;
  26568. },
  26569. enumerable: true,
  26570. configurable: true
  26571. });
  26572. Material.prototype.freeze = function () {
  26573. this.checkReadyOnlyOnce = true;
  26574. };
  26575. Material.prototype.unfreeze = function () {
  26576. this.checkReadyOnlyOnce = false;
  26577. };
  26578. Material.prototype.isReady = function (mesh, useInstances) {
  26579. return true;
  26580. };
  26581. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  26582. return false;
  26583. };
  26584. Material.prototype.getEffect = function () {
  26585. return this._effect;
  26586. };
  26587. Material.prototype.getScene = function () {
  26588. return this._scene;
  26589. };
  26590. Material.prototype.needAlphaBlending = function () {
  26591. return (this.alpha < 1.0);
  26592. };
  26593. Material.prototype.needAlphaTesting = function () {
  26594. return false;
  26595. };
  26596. Material.prototype.getAlphaTestTexture = function () {
  26597. return null;
  26598. };
  26599. Material.prototype.markDirty = function () {
  26600. this._wasPreviouslyReady = false;
  26601. };
  26602. Material.prototype._preBind = function (effect, overrideOrientation) {
  26603. var engine = this._scene.getEngine();
  26604. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  26605. var reverse = orientation === Material.ClockWiseSideOrientation;
  26606. engine.enableEffect(effect ? effect : this._effect);
  26607. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  26608. return reverse;
  26609. };
  26610. Material.prototype.bind = function (world, mesh) {
  26611. };
  26612. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  26613. };
  26614. Material.prototype.bindOnlyWorldMatrix = function (world) {
  26615. };
  26616. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  26617. sceneUbo.bindToEffect(effect, "Scene");
  26618. };
  26619. Material.prototype.bindView = function (effect) {
  26620. if (!this._useUBO) {
  26621. effect.setMatrix("view", this.getScene().getViewMatrix());
  26622. }
  26623. else {
  26624. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  26625. }
  26626. };
  26627. Material.prototype.bindViewProjection = function (effect) {
  26628. if (!this._useUBO) {
  26629. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  26630. }
  26631. else {
  26632. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  26633. }
  26634. };
  26635. Material.prototype._afterBind = function (mesh) {
  26636. this._scene._cachedMaterial = this;
  26637. if (mesh) {
  26638. this._scene._cachedVisibility = mesh.visibility;
  26639. }
  26640. else {
  26641. this._scene._cachedVisibility = 1;
  26642. }
  26643. this.onBindObservable.notifyObservers(mesh);
  26644. if (this.disableDepthWrite) {
  26645. var engine = this._scene.getEngine();
  26646. this._cachedDepthWriteState = engine.getDepthWrite();
  26647. engine.setDepthWrite(false);
  26648. }
  26649. };
  26650. Material.prototype.unbind = function () {
  26651. this.onUnBindObservable.notifyObservers(this);
  26652. if (this.disableDepthWrite) {
  26653. var engine = this._scene.getEngine();
  26654. engine.setDepthWrite(this._cachedDepthWriteState);
  26655. }
  26656. };
  26657. Material.prototype.getActiveTextures = function () {
  26658. return [];
  26659. };
  26660. Material.prototype.hasTexture = function (texture) {
  26661. return false;
  26662. };
  26663. Material.prototype.clone = function (name) {
  26664. return null;
  26665. };
  26666. Material.prototype.getBindedMeshes = function () {
  26667. var result = new Array();
  26668. for (var index = 0; index < this._scene.meshes.length; index++) {
  26669. var mesh = this._scene.meshes[index];
  26670. if (mesh.material === this) {
  26671. result.push(mesh);
  26672. }
  26673. }
  26674. return result;
  26675. };
  26676. /**
  26677. * Force shader compilation including textures ready check
  26678. */
  26679. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  26680. var _this = this;
  26681. var subMesh = new BABYLON.BaseSubMesh();
  26682. var scene = this.getScene();
  26683. var engine = scene.getEngine();
  26684. var checkReady = function () {
  26685. if (!_this._scene || !_this._scene.getEngine()) {
  26686. return;
  26687. }
  26688. if (subMesh._materialDefines) {
  26689. subMesh._materialDefines._renderId = -1;
  26690. }
  26691. var alphaTestState = engine.getAlphaTesting();
  26692. var clipPlaneState = scene.clipPlane;
  26693. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  26694. if (options && options.clipPlane) {
  26695. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  26696. }
  26697. if (_this.storeEffectOnSubMeshes) {
  26698. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  26699. if (onCompiled) {
  26700. onCompiled(_this);
  26701. }
  26702. }
  26703. else {
  26704. setTimeout(checkReady, 16);
  26705. }
  26706. }
  26707. else {
  26708. if (_this.isReady(mesh)) {
  26709. if (onCompiled) {
  26710. onCompiled(_this);
  26711. }
  26712. }
  26713. else {
  26714. setTimeout(checkReady, 16);
  26715. }
  26716. }
  26717. engine.setAlphaTesting(alphaTestState);
  26718. if (options && options.clipPlane) {
  26719. scene.clipPlane = clipPlaneState;
  26720. }
  26721. };
  26722. checkReady();
  26723. };
  26724. Material.prototype.markAsDirty = function (flag) {
  26725. if (flag & Material.TextureDirtyFlag) {
  26726. this._markAllSubMeshesAsTexturesDirty();
  26727. }
  26728. if (flag & Material.LightDirtyFlag) {
  26729. this._markAllSubMeshesAsLightsDirty();
  26730. }
  26731. if (flag & Material.FresnelDirtyFlag) {
  26732. this._markAllSubMeshesAsFresnelDirty();
  26733. }
  26734. if (flag & Material.AttributesDirtyFlag) {
  26735. this._markAllSubMeshesAsAttributesDirty();
  26736. }
  26737. if (flag & Material.MiscDirtyFlag) {
  26738. this._markAllSubMeshesAsMiscDirty();
  26739. }
  26740. this.getScene().resetCachedMaterial();
  26741. };
  26742. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  26743. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  26744. var mesh = _a[_i];
  26745. if (!mesh.subMeshes) {
  26746. continue;
  26747. }
  26748. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  26749. var subMesh = _c[_b];
  26750. if (subMesh.getMaterial() !== this) {
  26751. continue;
  26752. }
  26753. if (!subMesh._materialDefines) {
  26754. continue;
  26755. }
  26756. func(subMesh._materialDefines);
  26757. }
  26758. }
  26759. };
  26760. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  26761. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  26762. };
  26763. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  26764. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  26765. };
  26766. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  26767. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  26768. };
  26769. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  26770. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  26771. };
  26772. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  26773. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  26774. };
  26775. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  26776. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  26777. };
  26778. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  26779. // Animations
  26780. this.getScene().stopAnimation(this);
  26781. // Remove from scene
  26782. var index = this._scene.materials.indexOf(this);
  26783. if (index >= 0) {
  26784. this._scene.materials.splice(index, 1);
  26785. }
  26786. // Remove from meshes
  26787. for (index = 0; index < this._scene.meshes.length; index++) {
  26788. var mesh = this._scene.meshes[index];
  26789. if (mesh.material === this) {
  26790. mesh.material = null;
  26791. if (mesh.geometry) {
  26792. var geometry = mesh.geometry;
  26793. if (this.storeEffectOnSubMeshes) {
  26794. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  26795. var subMesh = _a[_i];
  26796. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  26797. }
  26798. }
  26799. else {
  26800. geometry._releaseVertexArrayObject(this._effect);
  26801. }
  26802. }
  26803. }
  26804. }
  26805. this._uniformBuffer.dispose();
  26806. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  26807. if (forceDisposeEffect && this._effect) {
  26808. if (this.storeEffectOnSubMeshes) {
  26809. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  26810. var subMesh = _c[_b];
  26811. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  26812. }
  26813. }
  26814. else {
  26815. this._scene.getEngine()._releaseEffect(this._effect);
  26816. }
  26817. this._effect = null;
  26818. }
  26819. // Callback
  26820. this.onDisposeObservable.notifyObservers(this);
  26821. this.onDisposeObservable.clear();
  26822. this.onBindObservable.clear();
  26823. this.onUnBindObservable.clear();
  26824. };
  26825. Material.prototype.serialize = function () {
  26826. return BABYLON.SerializationHelper.Serialize(this);
  26827. };
  26828. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  26829. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  26830. multiMaterial.id = parsedMultiMaterial.id;
  26831. if (BABYLON.Tags) {
  26832. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  26833. }
  26834. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  26835. var subMatId = parsedMultiMaterial.materials[matIndex];
  26836. if (subMatId) {
  26837. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  26838. }
  26839. else {
  26840. multiMaterial.subMaterials.push(null);
  26841. }
  26842. }
  26843. return multiMaterial;
  26844. };
  26845. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  26846. if (!parsedMaterial.customType) {
  26847. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  26848. }
  26849. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  26850. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  26851. if (!BABYLON.LegacyPBRMaterial) {
  26852. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  26853. return;
  26854. }
  26855. }
  26856. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  26857. return materialType.Parse(parsedMaterial, scene, rootUrl);
  26858. ;
  26859. };
  26860. Material._TriangleFillMode = 0;
  26861. Material._WireFrameFillMode = 1;
  26862. Material._PointFillMode = 2;
  26863. Material._ClockWiseSideOrientation = 0;
  26864. Material._CounterClockWiseSideOrientation = 1;
  26865. Material._TextureDirtyFlag = 1;
  26866. Material._LightDirtyFlag = 2;
  26867. Material._FresnelDirtyFlag = 4;
  26868. Material._AttributesDirtyFlag = 8;
  26869. Material._MiscDirtyFlag = 16;
  26870. __decorate([
  26871. BABYLON.serialize()
  26872. ], Material.prototype, "id", void 0);
  26873. __decorate([
  26874. BABYLON.serialize()
  26875. ], Material.prototype, "name", void 0);
  26876. __decorate([
  26877. BABYLON.serialize()
  26878. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  26879. __decorate([
  26880. BABYLON.serialize()
  26881. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  26882. __decorate([
  26883. BABYLON.serialize()
  26884. ], Material.prototype, "state", void 0);
  26885. __decorate([
  26886. BABYLON.serialize()
  26887. ], Material.prototype, "alpha", void 0);
  26888. __decorate([
  26889. BABYLON.serialize("backFaceCulling")
  26890. ], Material.prototype, "_backFaceCulling", void 0);
  26891. __decorate([
  26892. BABYLON.serialize()
  26893. ], Material.prototype, "sideOrientation", void 0);
  26894. __decorate([
  26895. BABYLON.serialize("alphaMode")
  26896. ], Material.prototype, "_alphaMode", void 0);
  26897. __decorate([
  26898. BABYLON.serialize()
  26899. ], Material.prototype, "_needDepthPrePass", void 0);
  26900. __decorate([
  26901. BABYLON.serialize()
  26902. ], Material.prototype, "disableDepthWrite", void 0);
  26903. __decorate([
  26904. BABYLON.serialize()
  26905. ], Material.prototype, "forceDepthWrite", void 0);
  26906. __decorate([
  26907. BABYLON.serialize()
  26908. ], Material.prototype, "separateCullingPass", void 0);
  26909. __decorate([
  26910. BABYLON.serialize("fogEnabled")
  26911. ], Material.prototype, "_fogEnabled", void 0);
  26912. __decorate([
  26913. BABYLON.serialize()
  26914. ], Material.prototype, "pointSize", void 0);
  26915. __decorate([
  26916. BABYLON.serialize()
  26917. ], Material.prototype, "zOffset", void 0);
  26918. __decorate([
  26919. BABYLON.serialize()
  26920. ], Material.prototype, "wireframe", null);
  26921. __decorate([
  26922. BABYLON.serialize()
  26923. ], Material.prototype, "pointsCloud", null);
  26924. __decorate([
  26925. BABYLON.serialize()
  26926. ], Material.prototype, "fillMode", null);
  26927. return Material;
  26928. }());
  26929. BABYLON.Material = Material;
  26930. })(BABYLON || (BABYLON = {}));
  26931. //# sourceMappingURL=babylon.material.js.map
  26932. var BABYLON;
  26933. (function (BABYLON) {
  26934. var UniformBuffer = /** @class */ (function () {
  26935. /**
  26936. * Uniform buffer objects.
  26937. *
  26938. * Handles blocks of uniform on the GPU.
  26939. *
  26940. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  26941. *
  26942. * For more information, please refer to :
  26943. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  26944. */
  26945. function UniformBuffer(engine, data, dynamic) {
  26946. this._engine = engine;
  26947. this._noUBO = !engine.supportsUniformBuffers;
  26948. this._dynamic = dynamic;
  26949. this._data = data || [];
  26950. this._uniformLocations = {};
  26951. this._uniformSizes = {};
  26952. this._uniformLocationPointer = 0;
  26953. this._needSync = false;
  26954. if (this._noUBO) {
  26955. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  26956. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  26957. this.updateFloat = this._updateFloatForEffect;
  26958. this.updateFloat2 = this._updateFloat2ForEffect;
  26959. this.updateFloat3 = this._updateFloat3ForEffect;
  26960. this.updateFloat4 = this._updateFloat4ForEffect;
  26961. this.updateMatrix = this._updateMatrixForEffect;
  26962. this.updateVector3 = this._updateVector3ForEffect;
  26963. this.updateVector4 = this._updateVector4ForEffect;
  26964. this.updateColor3 = this._updateColor3ForEffect;
  26965. this.updateColor4 = this._updateColor4ForEffect;
  26966. }
  26967. else {
  26968. this._engine._uniformBuffers.push(this);
  26969. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  26970. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  26971. this.updateFloat = this._updateFloatForUniform;
  26972. this.updateFloat2 = this._updateFloat2ForUniform;
  26973. this.updateFloat3 = this._updateFloat3ForUniform;
  26974. this.updateFloat4 = this._updateFloat4ForUniform;
  26975. this.updateMatrix = this._updateMatrixForUniform;
  26976. this.updateVector3 = this._updateVector3ForUniform;
  26977. this.updateVector4 = this._updateVector4ForUniform;
  26978. this.updateColor3 = this._updateColor3ForUniform;
  26979. this.updateColor4 = this._updateColor4ForUniform;
  26980. }
  26981. }
  26982. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  26983. // Properties
  26984. /**
  26985. * Indicates if the buffer is using the WebGL2 UBO implementation,
  26986. * or just falling back on setUniformXXX calls.
  26987. */
  26988. get: function () {
  26989. return !this._noUBO;
  26990. },
  26991. enumerable: true,
  26992. configurable: true
  26993. });
  26994. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  26995. /**
  26996. * Indicates if the WebGL underlying uniform buffer is in sync
  26997. * with the javascript cache data.
  26998. */
  26999. get: function () {
  27000. return !this._needSync;
  27001. },
  27002. enumerable: true,
  27003. configurable: true
  27004. });
  27005. /**
  27006. * Indicates if the WebGL underlying uniform buffer is dynamic.
  27007. * Also, a dynamic UniformBuffer will disable cache verification and always
  27008. * update the underlying WebGL uniform buffer to the GPU.
  27009. */
  27010. UniformBuffer.prototype.isDynamic = function () {
  27011. return this._dynamic !== undefined;
  27012. };
  27013. /**
  27014. * The data cache on JS side.
  27015. */
  27016. UniformBuffer.prototype.getData = function () {
  27017. return this._bufferData;
  27018. };
  27019. /**
  27020. * The underlying WebGL Uniform buffer.
  27021. */
  27022. UniformBuffer.prototype.getBuffer = function () {
  27023. return this._buffer;
  27024. };
  27025. /**
  27026. * std140 layout specifies how to align data within an UBO structure.
  27027. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  27028. * for specs.
  27029. */
  27030. UniformBuffer.prototype._fillAlignment = function (size) {
  27031. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  27032. // and 4x4 matrices
  27033. // TODO : change if other types are used
  27034. var alignment;
  27035. if (size <= 2) {
  27036. alignment = size;
  27037. }
  27038. else {
  27039. alignment = 4;
  27040. }
  27041. if ((this._uniformLocationPointer % alignment) !== 0) {
  27042. var oldPointer = this._uniformLocationPointer;
  27043. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  27044. var diff = this._uniformLocationPointer - oldPointer;
  27045. for (var i = 0; i < diff; i++) {
  27046. this._data.push(0);
  27047. }
  27048. }
  27049. };
  27050. /**
  27051. * Adds an uniform in the buffer.
  27052. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  27053. * for the layout to be correct !
  27054. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27055. * @param {number|number[]} size Data size, or data directly.
  27056. */
  27057. UniformBuffer.prototype.addUniform = function (name, size) {
  27058. if (this._noUBO) {
  27059. return;
  27060. }
  27061. if (this._uniformLocations[name] !== undefined) {
  27062. // Already existing uniform
  27063. return;
  27064. }
  27065. // This function must be called in the order of the shader layout !
  27066. // size can be the size of the uniform, or data directly
  27067. var data;
  27068. if (size instanceof Array) {
  27069. data = size;
  27070. size = data.length;
  27071. }
  27072. else {
  27073. size = size;
  27074. data = [];
  27075. // Fill with zeros
  27076. for (var i = 0; i < size; i++) {
  27077. data.push(0);
  27078. }
  27079. }
  27080. this._fillAlignment(size);
  27081. this._uniformSizes[name] = size;
  27082. this._uniformLocations[name] = this._uniformLocationPointer;
  27083. this._uniformLocationPointer += size;
  27084. for (var i = 0; i < size; i++) {
  27085. this._data.push(data[i]);
  27086. }
  27087. this._needSync = true;
  27088. };
  27089. /**
  27090. * Wrapper for addUniform.
  27091. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27092. * @param {Matrix} mat A 4x4 matrix.
  27093. */
  27094. UniformBuffer.prototype.addMatrix = function (name, mat) {
  27095. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  27096. };
  27097. /**
  27098. * Wrapper for addUniform.
  27099. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27100. * @param {number} x
  27101. * @param {number} y
  27102. */
  27103. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  27104. var temp = [x, y];
  27105. this.addUniform(name, temp);
  27106. };
  27107. /**
  27108. * Wrapper for addUniform.
  27109. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27110. * @param {number} x
  27111. * @param {number} y
  27112. * @param {number} z
  27113. */
  27114. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  27115. var temp = [x, y, z];
  27116. this.addUniform(name, temp);
  27117. };
  27118. /**
  27119. * Wrapper for addUniform.
  27120. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27121. * @param {Color3} color
  27122. */
  27123. UniformBuffer.prototype.addColor3 = function (name, color) {
  27124. var temp = new Array();
  27125. color.toArray(temp);
  27126. this.addUniform(name, temp);
  27127. };
  27128. /**
  27129. * Wrapper for addUniform.
  27130. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27131. * @param {Color3} color
  27132. * @param {number} alpha
  27133. */
  27134. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  27135. var temp = new Array();
  27136. color.toArray(temp);
  27137. temp.push(alpha);
  27138. this.addUniform(name, temp);
  27139. };
  27140. /**
  27141. * Wrapper for addUniform.
  27142. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27143. * @param {Vector3} vector
  27144. */
  27145. UniformBuffer.prototype.addVector3 = function (name, vector) {
  27146. var temp = new Array();
  27147. vector.toArray(temp);
  27148. this.addUniform(name, temp);
  27149. };
  27150. /**
  27151. * Wrapper for addUniform.
  27152. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27153. */
  27154. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  27155. this.addUniform(name, 12);
  27156. };
  27157. /**
  27158. * Wrapper for addUniform.
  27159. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27160. */
  27161. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  27162. this.addUniform(name, 8);
  27163. };
  27164. /**
  27165. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  27166. */
  27167. UniformBuffer.prototype.create = function () {
  27168. if (this._noUBO) {
  27169. return;
  27170. }
  27171. if (this._buffer) {
  27172. return; // nothing to do
  27173. }
  27174. // See spec, alignment must be filled as a vec4
  27175. this._fillAlignment(4);
  27176. this._bufferData = new Float32Array(this._data);
  27177. this._rebuild();
  27178. this._needSync = true;
  27179. };
  27180. UniformBuffer.prototype._rebuild = function () {
  27181. if (this._noUBO) {
  27182. return;
  27183. }
  27184. if (this._dynamic) {
  27185. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  27186. }
  27187. else {
  27188. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  27189. }
  27190. };
  27191. /**
  27192. * Updates the WebGL Uniform Buffer on the GPU.
  27193. * If the `dynamic` flag is set to true, no cache comparison is done.
  27194. * Otherwise, the buffer will be updated only if the cache differs.
  27195. */
  27196. UniformBuffer.prototype.update = function () {
  27197. if (!this._buffer) {
  27198. this.create();
  27199. return;
  27200. }
  27201. if (!this._dynamic && !this._needSync) {
  27202. return;
  27203. }
  27204. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  27205. this._needSync = false;
  27206. };
  27207. /**
  27208. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  27209. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  27210. * @param {number[]|Float32Array} data Flattened data
  27211. * @param {number} size Size of the data.
  27212. */
  27213. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  27214. var location = this._uniformLocations[uniformName];
  27215. if (location === undefined) {
  27216. if (this._buffer) {
  27217. // Cannot add an uniform if the buffer is already created
  27218. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  27219. return;
  27220. }
  27221. this.addUniform(uniformName, size);
  27222. location = this._uniformLocations[uniformName];
  27223. }
  27224. if (!this._buffer) {
  27225. this.create();
  27226. }
  27227. if (!this._dynamic) {
  27228. // Cache for static uniform buffers
  27229. var changed = false;
  27230. for (var i = 0; i < size; i++) {
  27231. if (this._bufferData[location + i] !== data[i]) {
  27232. changed = true;
  27233. this._bufferData[location + i] = data[i];
  27234. }
  27235. }
  27236. this._needSync = this._needSync || changed;
  27237. }
  27238. else {
  27239. // No cache for dynamic
  27240. for (var i = 0; i < size; i++) {
  27241. this._bufferData[location + i] = data[i];
  27242. }
  27243. }
  27244. };
  27245. // Update methods
  27246. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  27247. // To match std140, matrix must be realigned
  27248. for (var i = 0; i < 3; i++) {
  27249. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  27250. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  27251. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  27252. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  27253. }
  27254. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  27255. };
  27256. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  27257. this._currentEffect.setMatrix3x3(name, matrix);
  27258. };
  27259. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  27260. this._currentEffect.setMatrix2x2(name, matrix);
  27261. };
  27262. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  27263. // To match std140, matrix must be realigned
  27264. for (var i = 0; i < 2; i++) {
  27265. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  27266. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  27267. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  27268. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  27269. }
  27270. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  27271. };
  27272. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  27273. this._currentEffect.setFloat(name, x);
  27274. };
  27275. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  27276. UniformBuffer._tempBuffer[0] = x;
  27277. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  27278. };
  27279. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  27280. if (suffix === void 0) { suffix = ""; }
  27281. this._currentEffect.setFloat2(name + suffix, x, y);
  27282. };
  27283. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  27284. if (suffix === void 0) { suffix = ""; }
  27285. UniformBuffer._tempBuffer[0] = x;
  27286. UniformBuffer._tempBuffer[1] = y;
  27287. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  27288. };
  27289. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  27290. if (suffix === void 0) { suffix = ""; }
  27291. this._currentEffect.setFloat3(name + suffix, x, y, z);
  27292. };
  27293. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  27294. if (suffix === void 0) { suffix = ""; }
  27295. UniformBuffer._tempBuffer[0] = x;
  27296. UniformBuffer._tempBuffer[1] = y;
  27297. UniformBuffer._tempBuffer[2] = z;
  27298. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  27299. };
  27300. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  27301. if (suffix === void 0) { suffix = ""; }
  27302. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  27303. };
  27304. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  27305. if (suffix === void 0) { suffix = ""; }
  27306. UniformBuffer._tempBuffer[0] = x;
  27307. UniformBuffer._tempBuffer[1] = y;
  27308. UniformBuffer._tempBuffer[2] = z;
  27309. UniformBuffer._tempBuffer[3] = w;
  27310. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  27311. };
  27312. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  27313. this._currentEffect.setMatrix(name, mat);
  27314. };
  27315. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  27316. this.updateUniform(name, mat.toArray(), 16);
  27317. };
  27318. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  27319. this._currentEffect.setVector3(name, vector);
  27320. };
  27321. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  27322. vector.toArray(UniformBuffer._tempBuffer);
  27323. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  27324. };
  27325. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  27326. this._currentEffect.setVector4(name, vector);
  27327. };
  27328. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  27329. vector.toArray(UniformBuffer._tempBuffer);
  27330. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  27331. };
  27332. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  27333. if (suffix === void 0) { suffix = ""; }
  27334. this._currentEffect.setColor3(name + suffix, color);
  27335. };
  27336. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  27337. if (suffix === void 0) { suffix = ""; }
  27338. color.toArray(UniformBuffer._tempBuffer);
  27339. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  27340. };
  27341. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  27342. if (suffix === void 0) { suffix = ""; }
  27343. this._currentEffect.setColor4(name + suffix, color, alpha);
  27344. };
  27345. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  27346. if (suffix === void 0) { suffix = ""; }
  27347. color.toArray(UniformBuffer._tempBuffer);
  27348. UniformBuffer._tempBuffer[3] = alpha;
  27349. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  27350. };
  27351. /**
  27352. * Sets a sampler uniform on the effect.
  27353. * @param {string} name Name of the sampler.
  27354. * @param {Texture} texture
  27355. */
  27356. UniformBuffer.prototype.setTexture = function (name, texture) {
  27357. this._currentEffect.setTexture(name, texture);
  27358. };
  27359. /**
  27360. * Directly updates the value of the uniform in the cache AND on the GPU.
  27361. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  27362. * @param {number[]|Float32Array} data Flattened data
  27363. */
  27364. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  27365. this.updateUniform(uniformName, data, data.length);
  27366. this.update();
  27367. };
  27368. /**
  27369. * Binds this uniform buffer to an effect.
  27370. * @param {Effect} effect
  27371. * @param {string} name Name of the uniform block in the shader.
  27372. */
  27373. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  27374. this._currentEffect = effect;
  27375. if (this._noUBO || !this._buffer) {
  27376. return;
  27377. }
  27378. effect.bindUniformBuffer(this._buffer, name);
  27379. };
  27380. /**
  27381. * Disposes the uniform buffer.
  27382. */
  27383. UniformBuffer.prototype.dispose = function () {
  27384. if (this._noUBO) {
  27385. return;
  27386. }
  27387. var index = this._engine._uniformBuffers.indexOf(this);
  27388. if (index !== -1) {
  27389. this._engine._uniformBuffers.splice(index, 1);
  27390. }
  27391. if (!this._buffer) {
  27392. return;
  27393. }
  27394. if (this._engine._releaseBuffer(this._buffer)) {
  27395. this._buffer = null;
  27396. }
  27397. };
  27398. // Pool for avoiding memory leaks
  27399. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  27400. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  27401. return UniformBuffer;
  27402. }());
  27403. BABYLON.UniformBuffer = UniformBuffer;
  27404. })(BABYLON || (BABYLON = {}));
  27405. //# sourceMappingURL=babylon.uniformBuffer.js.map
  27406. var BABYLON;
  27407. (function (BABYLON) {
  27408. var PushMaterial = /** @class */ (function (_super) {
  27409. __extends(PushMaterial, _super);
  27410. function PushMaterial(name, scene) {
  27411. var _this = _super.call(this, name, scene) || this;
  27412. _this.storeEffectOnSubMeshes = true;
  27413. return _this;
  27414. }
  27415. PushMaterial.prototype.getEffect = function () {
  27416. return this._activeEffect;
  27417. };
  27418. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  27419. if (!mesh) {
  27420. return false;
  27421. }
  27422. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  27423. return true;
  27424. }
  27425. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  27426. };
  27427. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  27428. this._activeEffect.setMatrix("world", world);
  27429. };
  27430. PushMaterial.prototype.bind = function (world, mesh) {
  27431. if (!mesh) {
  27432. return;
  27433. }
  27434. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  27435. };
  27436. PushMaterial.prototype._afterBind = function (mesh, effect) {
  27437. _super.prototype._afterBind.call(this, mesh);
  27438. this.getScene()._cachedEffect = effect;
  27439. };
  27440. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  27441. if (visibility === void 0) { visibility = 1; }
  27442. return scene.isCachedMaterialInvalid(this, effect, visibility);
  27443. };
  27444. return PushMaterial;
  27445. }(BABYLON.Material));
  27446. BABYLON.PushMaterial = PushMaterial;
  27447. })(BABYLON || (BABYLON = {}));
  27448. //# sourceMappingURL=babylon.pushMaterial.js.map
  27449. var BABYLON;
  27450. (function (BABYLON) {
  27451. var VertexData = /** @class */ (function () {
  27452. function VertexData() {
  27453. }
  27454. VertexData.prototype.set = function (data, kind) {
  27455. switch (kind) {
  27456. case BABYLON.VertexBuffer.PositionKind:
  27457. this.positions = data;
  27458. break;
  27459. case BABYLON.VertexBuffer.NormalKind:
  27460. this.normals = data;
  27461. break;
  27462. case BABYLON.VertexBuffer.TangentKind:
  27463. this.tangents = data;
  27464. break;
  27465. case BABYLON.VertexBuffer.UVKind:
  27466. this.uvs = data;
  27467. break;
  27468. case BABYLON.VertexBuffer.UV2Kind:
  27469. this.uvs2 = data;
  27470. break;
  27471. case BABYLON.VertexBuffer.UV3Kind:
  27472. this.uvs3 = data;
  27473. break;
  27474. case BABYLON.VertexBuffer.UV4Kind:
  27475. this.uvs4 = data;
  27476. break;
  27477. case BABYLON.VertexBuffer.UV5Kind:
  27478. this.uvs5 = data;
  27479. break;
  27480. case BABYLON.VertexBuffer.UV6Kind:
  27481. this.uvs6 = data;
  27482. break;
  27483. case BABYLON.VertexBuffer.ColorKind:
  27484. this.colors = data;
  27485. break;
  27486. case BABYLON.VertexBuffer.MatricesIndicesKind:
  27487. this.matricesIndices = data;
  27488. break;
  27489. case BABYLON.VertexBuffer.MatricesWeightsKind:
  27490. this.matricesWeights = data;
  27491. break;
  27492. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  27493. this.matricesIndicesExtra = data;
  27494. break;
  27495. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  27496. this.matricesWeightsExtra = data;
  27497. break;
  27498. }
  27499. };
  27500. /**
  27501. * Associates the vertexData to the passed Mesh.
  27502. * Sets it as updatable or not (default `false`).
  27503. * Returns the VertexData.
  27504. */
  27505. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  27506. this._applyTo(mesh, updatable);
  27507. return this;
  27508. };
  27509. /**
  27510. * Associates the vertexData to the passed Geometry.
  27511. * Sets it as updatable or not (default `false`).
  27512. * Returns the VertexData.
  27513. */
  27514. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  27515. this._applyTo(geometry, updatable);
  27516. return this;
  27517. };
  27518. /**
  27519. * Updates the associated mesh.
  27520. * Returns the VertexData.
  27521. */
  27522. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  27523. this._update(mesh);
  27524. return this;
  27525. };
  27526. /**
  27527. * Updates the associated geometry.
  27528. * Returns the VertexData.
  27529. */
  27530. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  27531. this._update(geometry);
  27532. return this;
  27533. };
  27534. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  27535. if (this.positions) {
  27536. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  27537. }
  27538. if (this.normals) {
  27539. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  27540. }
  27541. if (this.tangents) {
  27542. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  27543. }
  27544. if (this.uvs) {
  27545. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  27546. }
  27547. if (this.uvs2) {
  27548. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  27549. }
  27550. if (this.uvs3) {
  27551. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  27552. }
  27553. if (this.uvs4) {
  27554. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  27555. }
  27556. if (this.uvs5) {
  27557. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  27558. }
  27559. if (this.uvs6) {
  27560. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  27561. }
  27562. if (this.colors) {
  27563. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  27564. }
  27565. if (this.matricesIndices) {
  27566. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  27567. }
  27568. if (this.matricesWeights) {
  27569. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  27570. }
  27571. if (this.matricesIndicesExtra) {
  27572. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  27573. }
  27574. if (this.matricesWeightsExtra) {
  27575. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  27576. }
  27577. if (this.indices) {
  27578. meshOrGeometry.setIndices(this.indices, null, updatable);
  27579. }
  27580. return this;
  27581. };
  27582. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  27583. if (this.positions) {
  27584. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  27585. }
  27586. if (this.normals) {
  27587. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  27588. }
  27589. if (this.tangents) {
  27590. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  27591. }
  27592. if (this.uvs) {
  27593. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  27594. }
  27595. if (this.uvs2) {
  27596. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  27597. }
  27598. if (this.uvs3) {
  27599. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  27600. }
  27601. if (this.uvs4) {
  27602. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  27603. }
  27604. if (this.uvs5) {
  27605. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  27606. }
  27607. if (this.uvs6) {
  27608. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  27609. }
  27610. if (this.colors) {
  27611. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  27612. }
  27613. if (this.matricesIndices) {
  27614. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  27615. }
  27616. if (this.matricesWeights) {
  27617. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  27618. }
  27619. if (this.matricesIndicesExtra) {
  27620. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  27621. }
  27622. if (this.matricesWeightsExtra) {
  27623. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  27624. }
  27625. if (this.indices) {
  27626. meshOrGeometry.setIndices(this.indices, null);
  27627. }
  27628. return this;
  27629. };
  27630. /**
  27631. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  27632. * Returns the VertexData.
  27633. */
  27634. VertexData.prototype.transform = function (matrix) {
  27635. var transformed = BABYLON.Vector3.Zero();
  27636. var index;
  27637. if (this.positions) {
  27638. var position = BABYLON.Vector3.Zero();
  27639. for (index = 0; index < this.positions.length; index += 3) {
  27640. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  27641. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  27642. this.positions[index] = transformed.x;
  27643. this.positions[index + 1] = transformed.y;
  27644. this.positions[index + 2] = transformed.z;
  27645. }
  27646. }
  27647. if (this.normals) {
  27648. var normal = BABYLON.Vector3.Zero();
  27649. for (index = 0; index < this.normals.length; index += 3) {
  27650. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  27651. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  27652. this.normals[index] = transformed.x;
  27653. this.normals[index + 1] = transformed.y;
  27654. this.normals[index + 2] = transformed.z;
  27655. }
  27656. }
  27657. if (this.tangents) {
  27658. var tangent = BABYLON.Vector4.Zero();
  27659. var tangentTransformed = BABYLON.Vector4.Zero();
  27660. for (index = 0; index < this.tangents.length; index += 4) {
  27661. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  27662. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  27663. this.tangents[index] = tangentTransformed.x;
  27664. this.tangents[index + 1] = tangentTransformed.y;
  27665. this.tangents[index + 2] = tangentTransformed.z;
  27666. this.tangents[index + 3] = tangentTransformed.w;
  27667. }
  27668. }
  27669. return this;
  27670. };
  27671. /**
  27672. * Merges the passed VertexData into the current one.
  27673. * Returns the modified VertexData.
  27674. */
  27675. VertexData.prototype.merge = function (other, options) {
  27676. options = options || {};
  27677. if (other.indices) {
  27678. if (!this.indices) {
  27679. this.indices = [];
  27680. }
  27681. var offset = this.positions ? this.positions.length / 3 : 0;
  27682. for (var index = 0; index < other.indices.length; index++) {
  27683. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  27684. this.indices.push(other.indices[index] + offset);
  27685. }
  27686. }
  27687. this.positions = this._mergeElement(this.positions, other.positions);
  27688. var count = this.positions.length / 3;
  27689. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  27690. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  27691. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  27692. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  27693. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  27694. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  27695. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  27696. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  27697. this.colors = this._mergeElement(this.colors, other.colors, count * 4);
  27698. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  27699. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  27700. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  27701. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  27702. return this;
  27703. };
  27704. VertexData.prototype._mergeElement = function (source, other, length) {
  27705. if (length === void 0) { length = 0; }
  27706. if (!other && !source) {
  27707. return null;
  27708. }
  27709. if (!other) {
  27710. return this._mergeElement(source, new Float32Array(source.length), length);
  27711. }
  27712. if (!source) {
  27713. if (length === 0 || length === other.length) {
  27714. return other;
  27715. }
  27716. return this._mergeElement(new Float32Array(length - other.length), other, length);
  27717. }
  27718. var len = other.length + source.length;
  27719. var isSrcTypedArray = source instanceof Float32Array;
  27720. var isOthTypedArray = other instanceof Float32Array;
  27721. // use non-loop method when the source is Float32Array
  27722. if (isSrcTypedArray) {
  27723. var ret32 = new Float32Array(len);
  27724. ret32.set(source);
  27725. ret32.set(other, source.length);
  27726. return ret32;
  27727. // source is number[], when other is also use concat
  27728. }
  27729. else if (!isOthTypedArray) {
  27730. return source.concat(other);
  27731. // source is a number[], but other is a Float32Array, loop required
  27732. }
  27733. else {
  27734. var ret = source.slice(0); // copy source to a separate array
  27735. for (var i = 0, len = other.length; i < len; i++) {
  27736. ret.push(other[i]);
  27737. }
  27738. return ret;
  27739. }
  27740. };
  27741. /**
  27742. * Serializes the VertexData.
  27743. * Returns a serialized object.
  27744. */
  27745. VertexData.prototype.serialize = function () {
  27746. var serializationObject = this.serialize();
  27747. if (this.positions) {
  27748. serializationObject.positions = this.positions;
  27749. }
  27750. if (this.normals) {
  27751. serializationObject.normals = this.normals;
  27752. }
  27753. if (this.tangents) {
  27754. serializationObject.tangents = this.tangents;
  27755. }
  27756. if (this.uvs) {
  27757. serializationObject.uvs = this.uvs;
  27758. }
  27759. if (this.uvs2) {
  27760. serializationObject.uvs2 = this.uvs2;
  27761. }
  27762. if (this.uvs3) {
  27763. serializationObject.uvs3 = this.uvs3;
  27764. }
  27765. if (this.uvs4) {
  27766. serializationObject.uvs4 = this.uvs4;
  27767. }
  27768. if (this.uvs5) {
  27769. serializationObject.uvs5 = this.uvs5;
  27770. }
  27771. if (this.uvs6) {
  27772. serializationObject.uvs6 = this.uvs6;
  27773. }
  27774. if (this.colors) {
  27775. serializationObject.colors = this.colors;
  27776. }
  27777. if (this.matricesIndices) {
  27778. serializationObject.matricesIndices = this.matricesIndices;
  27779. serializationObject.matricesIndices._isExpanded = true;
  27780. }
  27781. if (this.matricesWeights) {
  27782. serializationObject.matricesWeights = this.matricesWeights;
  27783. }
  27784. if (this.matricesIndicesExtra) {
  27785. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  27786. serializationObject.matricesIndicesExtra._isExpanded = true;
  27787. }
  27788. if (this.matricesWeightsExtra) {
  27789. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  27790. }
  27791. serializationObject.indices = this.indices;
  27792. return serializationObject;
  27793. };
  27794. // Statics
  27795. /**
  27796. * Returns the object VertexData associated to the passed mesh.
  27797. */
  27798. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  27799. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  27800. };
  27801. /**
  27802. * Returns the object VertexData associated to the passed geometry.
  27803. */
  27804. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  27805. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  27806. };
  27807. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  27808. var result = new VertexData();
  27809. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27810. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  27811. }
  27812. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27813. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  27814. }
  27815. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  27816. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  27817. }
  27818. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27819. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  27820. }
  27821. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27822. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  27823. }
  27824. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27825. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  27826. }
  27827. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27828. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  27829. }
  27830. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27831. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  27832. }
  27833. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27834. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  27835. }
  27836. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27837. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  27838. }
  27839. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27840. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  27841. }
  27842. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27843. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  27844. }
  27845. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  27846. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  27847. }
  27848. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  27849. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  27850. }
  27851. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  27852. return result;
  27853. };
  27854. /**
  27855. * Creates the vertexData of the Ribbon.
  27856. */
  27857. VertexData.CreateRibbon = function (options) {
  27858. var pathArray = options.pathArray;
  27859. var closeArray = options.closeArray || false;
  27860. var closePath = options.closePath || false;
  27861. var invertUV = options.invertUV || false;
  27862. var defaultOffset = Math.floor(pathArray[0].length / 2);
  27863. var offset = options.offset || defaultOffset;
  27864. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  27865. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27866. var customUV = options.uvs;
  27867. var customColors = options.colors;
  27868. var positions = [];
  27869. var indices = [];
  27870. var normals = [];
  27871. var uvs = [];
  27872. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  27873. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  27874. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  27875. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  27876. var minlg; // minimal length among all paths from pathArray
  27877. var lg = []; // array of path lengths : nb of vertex per path
  27878. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  27879. var p; // path iterator
  27880. var i; // point iterator
  27881. var j; // point iterator
  27882. // if single path in pathArray
  27883. if (pathArray.length < 2) {
  27884. var ar1 = [];
  27885. var ar2 = [];
  27886. for (i = 0; i < pathArray[0].length - offset; i++) {
  27887. ar1.push(pathArray[0][i]);
  27888. ar2.push(pathArray[0][i + offset]);
  27889. }
  27890. pathArray = [ar1, ar2];
  27891. }
  27892. // positions and horizontal distances (u)
  27893. var idc = 0;
  27894. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  27895. var path;
  27896. var l;
  27897. minlg = pathArray[0].length;
  27898. var vectlg;
  27899. var dist;
  27900. for (p = 0; p < pathArray.length; p++) {
  27901. uTotalDistance[p] = 0;
  27902. us[p] = [0];
  27903. path = pathArray[p];
  27904. l = path.length;
  27905. minlg = (minlg < l) ? minlg : l;
  27906. j = 0;
  27907. while (j < l) {
  27908. positions.push(path[j].x, path[j].y, path[j].z);
  27909. if (j > 0) {
  27910. vectlg = path[j].subtract(path[j - 1]).length();
  27911. dist = vectlg + uTotalDistance[p];
  27912. us[p].push(dist);
  27913. uTotalDistance[p] = dist;
  27914. }
  27915. j++;
  27916. }
  27917. if (closePath) {
  27918. j--;
  27919. positions.push(path[0].x, path[0].y, path[0].z);
  27920. vectlg = path[j].subtract(path[0]).length();
  27921. dist = vectlg + uTotalDistance[p];
  27922. us[p].push(dist);
  27923. uTotalDistance[p] = dist;
  27924. }
  27925. lg[p] = l + closePathCorr;
  27926. idx[p] = idc;
  27927. idc += (l + closePathCorr);
  27928. }
  27929. // vertical distances (v)
  27930. var path1;
  27931. var path2;
  27932. var vertex1;
  27933. var vertex2;
  27934. for (i = 0; i < minlg + closePathCorr; i++) {
  27935. vTotalDistance[i] = 0;
  27936. vs[i] = [0];
  27937. for (p = 0; p < pathArray.length - 1; p++) {
  27938. path1 = pathArray[p];
  27939. path2 = pathArray[p + 1];
  27940. if (i === minlg) {
  27941. vertex1 = path1[0];
  27942. vertex2 = path2[0];
  27943. }
  27944. else {
  27945. vertex1 = path1[i];
  27946. vertex2 = path2[i];
  27947. }
  27948. vectlg = vertex2.subtract(vertex1).length();
  27949. dist = vectlg + vTotalDistance[i];
  27950. vs[i].push(dist);
  27951. vTotalDistance[i] = dist;
  27952. }
  27953. if (closeArray) {
  27954. path1 = pathArray[p];
  27955. path2 = pathArray[0];
  27956. if (i === minlg) {
  27957. vertex2 = path2[0];
  27958. }
  27959. vectlg = vertex2.subtract(vertex1).length();
  27960. dist = vectlg + vTotalDistance[i];
  27961. vTotalDistance[i] = dist;
  27962. }
  27963. }
  27964. // uvs
  27965. var u;
  27966. var v;
  27967. if (customUV) {
  27968. for (p = 0; p < customUV.length; p++) {
  27969. uvs.push(customUV[p].x, customUV[p].y);
  27970. }
  27971. }
  27972. else {
  27973. for (p = 0; p < pathArray.length; p++) {
  27974. for (i = 0; i < minlg + closePathCorr; i++) {
  27975. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  27976. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  27977. if (invertUV) {
  27978. uvs.push(v, u);
  27979. }
  27980. else {
  27981. uvs.push(u, v);
  27982. }
  27983. }
  27984. }
  27985. }
  27986. // indices
  27987. p = 0; // path index
  27988. var pi = 0; // positions array index
  27989. var l1 = lg[p] - 1; // path1 length
  27990. var l2 = lg[p + 1] - 1; // path2 length
  27991. var min = (l1 < l2) ? l1 : l2; // current path stop index
  27992. var shft = idx[1] - idx[0]; // shift
  27993. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  27994. while (pi <= min && p < path1nb) {
  27995. // 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
  27996. indices.push(pi, pi + shft, pi + 1);
  27997. indices.push(pi + shft + 1, pi + 1, pi + shft);
  27998. pi += 1;
  27999. if (pi === min) {
  28000. p++;
  28001. if (p === lg.length - 1) {
  28002. shft = idx[0] - idx[p];
  28003. l1 = lg[p] - 1;
  28004. l2 = lg[0] - 1;
  28005. }
  28006. else {
  28007. shft = idx[p + 1] - idx[p];
  28008. l1 = lg[p] - 1;
  28009. l2 = lg[p + 1] - 1;
  28010. }
  28011. pi = idx[p];
  28012. min = (l1 < l2) ? l1 + pi : l2 + pi;
  28013. }
  28014. }
  28015. // normals
  28016. VertexData.ComputeNormals(positions, indices, normals);
  28017. if (closePath) {
  28018. var indexFirst = 0;
  28019. var indexLast = 0;
  28020. for (p = 0; p < pathArray.length; p++) {
  28021. indexFirst = idx[p] * 3;
  28022. if (p + 1 < pathArray.length) {
  28023. indexLast = (idx[p + 1] - 1) * 3;
  28024. }
  28025. else {
  28026. indexLast = normals.length - 3;
  28027. }
  28028. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  28029. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  28030. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  28031. normals[indexLast] = normals[indexFirst];
  28032. normals[indexLast + 1] = normals[indexFirst + 1];
  28033. normals[indexLast + 2] = normals[indexFirst + 2];
  28034. }
  28035. }
  28036. // sides
  28037. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28038. // Colors
  28039. if (customColors) {
  28040. var colors = new Float32Array(customColors.length * 4);
  28041. for (var c = 0; c < customColors.length; c++) {
  28042. colors[c * 4] = customColors[c].r;
  28043. colors[c * 4 + 1] = customColors[c].g;
  28044. colors[c * 4 + 2] = customColors[c].b;
  28045. colors[c * 4 + 3] = customColors[c].a;
  28046. }
  28047. }
  28048. // Result
  28049. var vertexData = new VertexData();
  28050. var positions32 = new Float32Array(positions);
  28051. var normals32 = new Float32Array(normals);
  28052. var uvs32 = new Float32Array(uvs);
  28053. vertexData.indices = indices;
  28054. vertexData.positions = positions32;
  28055. vertexData.normals = normals32;
  28056. vertexData.uvs = uvs32;
  28057. if (customColors) {
  28058. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  28059. }
  28060. if (closePath) {
  28061. vertexData._idx = idx;
  28062. }
  28063. return vertexData;
  28064. };
  28065. /**
  28066. * Creates the VertexData of the Box.
  28067. */
  28068. VertexData.CreateBox = function (options) {
  28069. var normalsSource = [
  28070. new BABYLON.Vector3(0, 0, 1),
  28071. new BABYLON.Vector3(0, 0, -1),
  28072. new BABYLON.Vector3(1, 0, 0),
  28073. new BABYLON.Vector3(-1, 0, 0),
  28074. new BABYLON.Vector3(0, 1, 0),
  28075. new BABYLON.Vector3(0, -1, 0)
  28076. ];
  28077. var indices = [];
  28078. var positions = [];
  28079. var normals = [];
  28080. var uvs = [];
  28081. var width = options.width || options.size || 1;
  28082. var height = options.height || options.size || 1;
  28083. var depth = options.depth || options.size || 1;
  28084. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28085. var faceUV = options.faceUV || new Array(6);
  28086. var faceColors = options.faceColors;
  28087. var colors = [];
  28088. // default face colors and UV if undefined
  28089. for (var f = 0; f < 6; f++) {
  28090. if (faceUV[f] === undefined) {
  28091. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28092. }
  28093. if (faceColors && faceColors[f] === undefined) {
  28094. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28095. }
  28096. }
  28097. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  28098. // Create each face in turn.
  28099. for (var index = 0; index < normalsSource.length; index++) {
  28100. var normal = normalsSource[index];
  28101. // Get two vectors perpendicular to the face normal and to each other.
  28102. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  28103. var side2 = BABYLON.Vector3.Cross(normal, side1);
  28104. // Six indices (two triangles) per face.
  28105. var verticesLength = positions.length / 3;
  28106. indices.push(verticesLength);
  28107. indices.push(verticesLength + 1);
  28108. indices.push(verticesLength + 2);
  28109. indices.push(verticesLength);
  28110. indices.push(verticesLength + 2);
  28111. indices.push(verticesLength + 3);
  28112. // Four vertices per face.
  28113. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  28114. positions.push(vertex.x, vertex.y, vertex.z);
  28115. normals.push(normal.x, normal.y, normal.z);
  28116. uvs.push(faceUV[index].z, faceUV[index].w);
  28117. if (faceColors) {
  28118. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28119. }
  28120. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  28121. positions.push(vertex.x, vertex.y, vertex.z);
  28122. normals.push(normal.x, normal.y, normal.z);
  28123. uvs.push(faceUV[index].x, faceUV[index].w);
  28124. if (faceColors) {
  28125. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28126. }
  28127. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  28128. positions.push(vertex.x, vertex.y, vertex.z);
  28129. normals.push(normal.x, normal.y, normal.z);
  28130. uvs.push(faceUV[index].x, faceUV[index].y);
  28131. if (faceColors) {
  28132. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28133. }
  28134. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  28135. positions.push(vertex.x, vertex.y, vertex.z);
  28136. normals.push(normal.x, normal.y, normal.z);
  28137. uvs.push(faceUV[index].z, faceUV[index].y);
  28138. if (faceColors) {
  28139. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28140. }
  28141. }
  28142. // sides
  28143. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28144. // Result
  28145. var vertexData = new VertexData();
  28146. vertexData.indices = indices;
  28147. vertexData.positions = positions;
  28148. vertexData.normals = normals;
  28149. vertexData.uvs = uvs;
  28150. if (faceColors) {
  28151. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  28152. vertexData.colors = totalColors;
  28153. }
  28154. return vertexData;
  28155. };
  28156. /**
  28157. * Creates the VertexData of the Sphere.
  28158. */
  28159. VertexData.CreateSphere = function (options) {
  28160. var segments = options.segments || 32;
  28161. var diameterX = options.diameterX || options.diameter || 1;
  28162. var diameterY = options.diameterY || options.diameter || 1;
  28163. var diameterZ = options.diameterZ || options.diameter || 1;
  28164. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28165. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  28166. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28167. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  28168. var totalZRotationSteps = 2 + segments;
  28169. var totalYRotationSteps = 2 * totalZRotationSteps;
  28170. var indices = [];
  28171. var positions = [];
  28172. var normals = [];
  28173. var uvs = [];
  28174. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  28175. var normalizedZ = zRotationStep / totalZRotationSteps;
  28176. var angleZ = normalizedZ * Math.PI * slice;
  28177. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  28178. var normalizedY = yRotationStep / totalYRotationSteps;
  28179. var angleY = normalizedY * Math.PI * 2 * arc;
  28180. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  28181. var rotationY = BABYLON.Matrix.RotationY(angleY);
  28182. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  28183. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  28184. var vertex = complete.multiply(radius);
  28185. var normal = complete.divide(radius).normalize();
  28186. positions.push(vertex.x, vertex.y, vertex.z);
  28187. normals.push(normal.x, normal.y, normal.z);
  28188. uvs.push(normalizedY, normalizedZ);
  28189. }
  28190. if (zRotationStep > 0) {
  28191. var verticesCount = positions.length / 3;
  28192. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  28193. indices.push((firstIndex));
  28194. indices.push((firstIndex + 1));
  28195. indices.push(firstIndex + totalYRotationSteps + 1);
  28196. indices.push((firstIndex + totalYRotationSteps + 1));
  28197. indices.push((firstIndex + 1));
  28198. indices.push((firstIndex + totalYRotationSteps + 2));
  28199. }
  28200. }
  28201. }
  28202. // Sides
  28203. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28204. // Result
  28205. var vertexData = new VertexData();
  28206. vertexData.indices = indices;
  28207. vertexData.positions = positions;
  28208. vertexData.normals = normals;
  28209. vertexData.uvs = uvs;
  28210. return vertexData;
  28211. };
  28212. /**
  28213. * Creates the VertexData of the Cylinder or Cone.
  28214. */
  28215. VertexData.CreateCylinder = function (options) {
  28216. var height = options.height || 2;
  28217. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  28218. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  28219. var tessellation = options.tessellation || 24;
  28220. var subdivisions = options.subdivisions || 1;
  28221. var hasRings = options.hasRings;
  28222. var enclose = options.enclose;
  28223. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28224. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28225. var faceUV = options.faceUV || new Array(3);
  28226. var faceColors = options.faceColors;
  28227. // default face colors and UV if undefined
  28228. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  28229. var ringNb = (hasRings) ? subdivisions : 1;
  28230. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  28231. var f;
  28232. for (f = 0; f < surfaceNb; f++) {
  28233. if (faceColors && faceColors[f] === undefined) {
  28234. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28235. }
  28236. }
  28237. for (f = 0; f < surfaceNb; f++) {
  28238. if (faceUV && faceUV[f] === undefined) {
  28239. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28240. }
  28241. }
  28242. var indices = new Array();
  28243. var positions = new Array();
  28244. var normals = new Array();
  28245. var uvs = new Array();
  28246. var colors = new Array();
  28247. var angle_step = Math.PI * 2 * arc / tessellation;
  28248. var angle;
  28249. var h;
  28250. var radius;
  28251. var tan = (diameterBottom - diameterTop) / 2 / height;
  28252. var ringVertex = BABYLON.Vector3.Zero();
  28253. var ringNormal = BABYLON.Vector3.Zero();
  28254. var ringFirstVertex = BABYLON.Vector3.Zero();
  28255. var ringFirstNormal = BABYLON.Vector3.Zero();
  28256. var quadNormal = BABYLON.Vector3.Zero();
  28257. var Y = BABYLON.Axis.Y;
  28258. // positions, normals, uvs
  28259. var i;
  28260. var j;
  28261. var r;
  28262. var ringIdx = 1;
  28263. var s = 1; // surface index
  28264. var cs = 0;
  28265. var v = 0;
  28266. for (i = 0; i <= subdivisions; i++) {
  28267. h = i / subdivisions;
  28268. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  28269. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  28270. for (r = 0; r < ringIdx; r++) {
  28271. if (hasRings) {
  28272. s += r;
  28273. }
  28274. if (enclose) {
  28275. s += 2 * r;
  28276. }
  28277. for (j = 0; j <= tessellation; j++) {
  28278. angle = j * angle_step;
  28279. // position
  28280. ringVertex.x = Math.cos(-angle) * radius;
  28281. ringVertex.y = -height / 2 + h * height;
  28282. ringVertex.z = Math.sin(-angle) * radius;
  28283. // normal
  28284. if (diameterTop === 0 && i === subdivisions) {
  28285. // if no top cap, reuse former normals
  28286. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  28287. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  28288. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  28289. }
  28290. else {
  28291. ringNormal.x = ringVertex.x;
  28292. ringNormal.z = ringVertex.z;
  28293. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  28294. ringNormal.normalize();
  28295. }
  28296. // keep first ring vertex values for enclose
  28297. if (j === 0) {
  28298. ringFirstVertex.copyFrom(ringVertex);
  28299. ringFirstNormal.copyFrom(ringNormal);
  28300. }
  28301. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28302. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  28303. if (hasRings) {
  28304. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  28305. }
  28306. else {
  28307. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  28308. }
  28309. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  28310. if (faceColors) {
  28311. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  28312. }
  28313. }
  28314. // if enclose, add four vertices and their dedicated normals
  28315. if (arc !== 1 && enclose) {
  28316. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28317. positions.push(0, ringVertex.y, 0);
  28318. positions.push(0, ringVertex.y, 0);
  28319. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  28320. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  28321. quadNormal.normalize();
  28322. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28323. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  28324. quadNormal.normalize();
  28325. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28326. if (hasRings) {
  28327. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  28328. }
  28329. else {
  28330. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  28331. }
  28332. uvs.push(faceUV[s + 1].x, v);
  28333. uvs.push(faceUV[s + 1].z, v);
  28334. if (hasRings) {
  28335. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  28336. }
  28337. else {
  28338. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  28339. }
  28340. uvs.push(faceUV[s + 2].x, v);
  28341. uvs.push(faceUV[s + 2].z, v);
  28342. if (faceColors) {
  28343. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28344. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28345. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28346. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28347. }
  28348. }
  28349. if (cs !== s) {
  28350. cs = s;
  28351. }
  28352. }
  28353. }
  28354. // indices
  28355. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  28356. var s;
  28357. i = 0;
  28358. for (s = 0; s < subdivisions; s++) {
  28359. for (j = 0; j < tessellation; j++) {
  28360. var i0 = i * (e + 1) + j;
  28361. var i1 = (i + 1) * (e + 1) + j;
  28362. var i2 = i * (e + 1) + (j + 1);
  28363. var i3 = (i + 1) * (e + 1) + (j + 1);
  28364. indices.push(i0, i1, i2);
  28365. indices.push(i3, i2, i1);
  28366. }
  28367. if (arc !== 1 && enclose) {
  28368. indices.push(i0 + 2, i1 + 2, i2 + 2);
  28369. indices.push(i3 + 2, i2 + 2, i1 + 2);
  28370. indices.push(i0 + 4, i1 + 4, i2 + 4);
  28371. indices.push(i3 + 4, i2 + 4, i1 + 4);
  28372. }
  28373. i = (hasRings) ? (i + 2) : (i + 1);
  28374. }
  28375. // Caps
  28376. var createCylinderCap = function (isTop) {
  28377. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  28378. if (radius === 0) {
  28379. return;
  28380. }
  28381. // Cap positions, normals & uvs
  28382. var angle;
  28383. var circleVector;
  28384. var i;
  28385. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  28386. var c;
  28387. if (faceColors) {
  28388. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  28389. }
  28390. // cap center
  28391. var vbase = positions.length / 3;
  28392. var offset = isTop ? height / 2 : -height / 2;
  28393. var center = new BABYLON.Vector3(0, offset, 0);
  28394. positions.push(center.x, center.y, center.z);
  28395. normals.push(0, isTop ? 1 : -1, 0);
  28396. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  28397. if (faceColors) {
  28398. colors.push(c.r, c.g, c.b, c.a);
  28399. }
  28400. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  28401. for (i = 0; i <= tessellation; i++) {
  28402. angle = Math.PI * 2 * i * arc / tessellation;
  28403. var cos = Math.cos(-angle);
  28404. var sin = Math.sin(-angle);
  28405. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  28406. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  28407. positions.push(circleVector.x, circleVector.y, circleVector.z);
  28408. normals.push(0, isTop ? 1 : -1, 0);
  28409. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  28410. if (faceColors) {
  28411. colors.push(c.r, c.g, c.b, c.a);
  28412. }
  28413. }
  28414. // Cap indices
  28415. for (i = 0; i < tessellation; i++) {
  28416. if (!isTop) {
  28417. indices.push(vbase);
  28418. indices.push(vbase + (i + 1));
  28419. indices.push(vbase + (i + 2));
  28420. }
  28421. else {
  28422. indices.push(vbase);
  28423. indices.push(vbase + (i + 2));
  28424. indices.push(vbase + (i + 1));
  28425. }
  28426. }
  28427. };
  28428. // add caps to geometry
  28429. createCylinderCap(false);
  28430. createCylinderCap(true);
  28431. // Sides
  28432. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28433. var vertexData = new VertexData();
  28434. vertexData.indices = indices;
  28435. vertexData.positions = positions;
  28436. vertexData.normals = normals;
  28437. vertexData.uvs = uvs;
  28438. if (faceColors) {
  28439. vertexData.colors = colors;
  28440. }
  28441. return vertexData;
  28442. };
  28443. /**
  28444. * Creates the VertexData of the Torus.
  28445. */
  28446. VertexData.CreateTorus = function (options) {
  28447. var indices = [];
  28448. var positions = [];
  28449. var normals = [];
  28450. var uvs = [];
  28451. var diameter = options.diameter || 1;
  28452. var thickness = options.thickness || 0.5;
  28453. var tessellation = options.tessellation || 16;
  28454. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28455. var stride = tessellation + 1;
  28456. for (var i = 0; i <= tessellation; i++) {
  28457. var u = i / tessellation;
  28458. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  28459. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  28460. for (var j = 0; j <= tessellation; j++) {
  28461. var v = 1 - j / tessellation;
  28462. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  28463. var dx = Math.cos(innerAngle);
  28464. var dy = Math.sin(innerAngle);
  28465. // Create a vertex.
  28466. var normal = new BABYLON.Vector3(dx, dy, 0);
  28467. var position = normal.scale(thickness / 2);
  28468. var textureCoordinate = new BABYLON.Vector2(u, v);
  28469. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  28470. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  28471. positions.push(position.x, position.y, position.z);
  28472. normals.push(normal.x, normal.y, normal.z);
  28473. uvs.push(textureCoordinate.x, textureCoordinate.y);
  28474. // And create indices for two triangles.
  28475. var nextI = (i + 1) % stride;
  28476. var nextJ = (j + 1) % stride;
  28477. indices.push(i * stride + j);
  28478. indices.push(i * stride + nextJ);
  28479. indices.push(nextI * stride + j);
  28480. indices.push(i * stride + nextJ);
  28481. indices.push(nextI * stride + nextJ);
  28482. indices.push(nextI * stride + j);
  28483. }
  28484. }
  28485. // Sides
  28486. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28487. // Result
  28488. var vertexData = new VertexData();
  28489. vertexData.indices = indices;
  28490. vertexData.positions = positions;
  28491. vertexData.normals = normals;
  28492. vertexData.uvs = uvs;
  28493. return vertexData;
  28494. };
  28495. /**
  28496. * Creates the VertexData of the LineSystem.
  28497. */
  28498. VertexData.CreateLineSystem = function (options) {
  28499. var indices = [];
  28500. var positions = [];
  28501. var lines = options.lines;
  28502. var idx = 0;
  28503. for (var l = 0; l < lines.length; l++) {
  28504. var points = lines[l];
  28505. for (var index = 0; index < points.length; index++) {
  28506. positions.push(points[index].x, points[index].y, points[index].z);
  28507. if (index > 0) {
  28508. indices.push(idx - 1);
  28509. indices.push(idx);
  28510. }
  28511. idx++;
  28512. }
  28513. }
  28514. var vertexData = new VertexData();
  28515. vertexData.indices = indices;
  28516. vertexData.positions = positions;
  28517. return vertexData;
  28518. };
  28519. /**
  28520. * Create the VertexData of the DashedLines.
  28521. */
  28522. VertexData.CreateDashedLines = function (options) {
  28523. var dashSize = options.dashSize || 3;
  28524. var gapSize = options.gapSize || 1;
  28525. var dashNb = options.dashNb || 200;
  28526. var points = options.points;
  28527. var positions = new Array();
  28528. var indices = new Array();
  28529. var curvect = BABYLON.Vector3.Zero();
  28530. var lg = 0;
  28531. var nb = 0;
  28532. var shft = 0;
  28533. var dashshft = 0;
  28534. var curshft = 0;
  28535. var idx = 0;
  28536. var i = 0;
  28537. for (i = 0; i < points.length - 1; i++) {
  28538. points[i + 1].subtractToRef(points[i], curvect);
  28539. lg += curvect.length();
  28540. }
  28541. shft = lg / dashNb;
  28542. dashshft = dashSize * shft / (dashSize + gapSize);
  28543. for (i = 0; i < points.length - 1; i++) {
  28544. points[i + 1].subtractToRef(points[i], curvect);
  28545. nb = Math.floor(curvect.length() / shft);
  28546. curvect.normalize();
  28547. for (var j = 0; j < nb; j++) {
  28548. curshft = shft * j;
  28549. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  28550. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  28551. indices.push(idx, idx + 1);
  28552. idx += 2;
  28553. }
  28554. }
  28555. // Result
  28556. var vertexData = new VertexData();
  28557. vertexData.positions = positions;
  28558. vertexData.indices = indices;
  28559. return vertexData;
  28560. };
  28561. /**
  28562. * Creates the VertexData of the Ground.
  28563. */
  28564. VertexData.CreateGround = function (options) {
  28565. var indices = [];
  28566. var positions = [];
  28567. var normals = [];
  28568. var uvs = [];
  28569. var row, col;
  28570. var width = options.width || 1;
  28571. var height = options.height || 1;
  28572. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  28573. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  28574. for (row = 0; row <= subdivisionsY; row++) {
  28575. for (col = 0; col <= subdivisionsX; col++) {
  28576. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  28577. var normal = new BABYLON.Vector3(0, 1.0, 0);
  28578. positions.push(position.x, position.y, position.z);
  28579. normals.push(normal.x, normal.y, normal.z);
  28580. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  28581. }
  28582. }
  28583. for (row = 0; row < subdivisionsY; row++) {
  28584. for (col = 0; col < subdivisionsX; col++) {
  28585. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  28586. indices.push(col + 1 + row * (subdivisionsX + 1));
  28587. indices.push(col + row * (subdivisionsX + 1));
  28588. indices.push(col + (row + 1) * (subdivisionsX + 1));
  28589. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  28590. indices.push(col + row * (subdivisionsX + 1));
  28591. }
  28592. }
  28593. // Result
  28594. var vertexData = new VertexData();
  28595. vertexData.indices = indices;
  28596. vertexData.positions = positions;
  28597. vertexData.normals = normals;
  28598. vertexData.uvs = uvs;
  28599. return vertexData;
  28600. };
  28601. /**
  28602. * Creates the VertexData of the TiledGround.
  28603. */
  28604. VertexData.CreateTiledGround = function (options) {
  28605. var xmin = options.xmin || -1.0;
  28606. var zmin = options.zmin || -1.0;
  28607. var xmax = options.xmax || 1.0;
  28608. var zmax = options.zmax || 1.0;
  28609. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  28610. var precision = options.precision || { w: 1, h: 1 };
  28611. var indices = new Array();
  28612. var positions = new Array();
  28613. var normals = new Array();
  28614. var uvs = new Array();
  28615. var row, col, tileRow, tileCol;
  28616. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  28617. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  28618. precision.w = (precision.w < 1) ? 1 : precision.w;
  28619. precision.h = (precision.h < 1) ? 1 : precision.h;
  28620. var tileSize = {
  28621. 'w': (xmax - xmin) / subdivisions.w,
  28622. 'h': (zmax - zmin) / subdivisions.h
  28623. };
  28624. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  28625. // Indices
  28626. var base = positions.length / 3;
  28627. var rowLength = precision.w + 1;
  28628. for (row = 0; row < precision.h; row++) {
  28629. for (col = 0; col < precision.w; col++) {
  28630. var square = [
  28631. base + col + row * rowLength,
  28632. base + (col + 1) + row * rowLength,
  28633. base + (col + 1) + (row + 1) * rowLength,
  28634. base + col + (row + 1) * rowLength
  28635. ];
  28636. indices.push(square[1]);
  28637. indices.push(square[2]);
  28638. indices.push(square[3]);
  28639. indices.push(square[0]);
  28640. indices.push(square[1]);
  28641. indices.push(square[3]);
  28642. }
  28643. }
  28644. // Position, normals and uvs
  28645. var position = BABYLON.Vector3.Zero();
  28646. var normal = new BABYLON.Vector3(0, 1.0, 0);
  28647. for (row = 0; row <= precision.h; row++) {
  28648. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  28649. for (col = 0; col <= precision.w; col++) {
  28650. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  28651. position.y = 0;
  28652. positions.push(position.x, position.y, position.z);
  28653. normals.push(normal.x, normal.y, normal.z);
  28654. uvs.push(col / precision.w, row / precision.h);
  28655. }
  28656. }
  28657. }
  28658. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  28659. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  28660. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  28661. }
  28662. }
  28663. // Result
  28664. var vertexData = new VertexData();
  28665. vertexData.indices = indices;
  28666. vertexData.positions = positions;
  28667. vertexData.normals = normals;
  28668. vertexData.uvs = uvs;
  28669. return vertexData;
  28670. };
  28671. /**
  28672. * Creates the VertexData of the Ground designed from a heightmap.
  28673. */
  28674. VertexData.CreateGroundFromHeightMap = function (options) {
  28675. var indices = [];
  28676. var positions = [];
  28677. var normals = [];
  28678. var uvs = [];
  28679. var row, col;
  28680. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  28681. // Vertices
  28682. for (row = 0; row <= options.subdivisions; row++) {
  28683. for (col = 0; col <= options.subdivisions; col++) {
  28684. 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));
  28685. // Compute height
  28686. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  28687. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  28688. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  28689. var r = options.buffer[pos] / 255.0;
  28690. var g = options.buffer[pos + 1] / 255.0;
  28691. var b = options.buffer[pos + 2] / 255.0;
  28692. var gradient = r * filter.r + g * filter.g + b * filter.b;
  28693. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  28694. // Add vertex
  28695. positions.push(position.x, position.y, position.z);
  28696. normals.push(0, 0, 0);
  28697. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  28698. }
  28699. }
  28700. // Indices
  28701. for (row = 0; row < options.subdivisions; row++) {
  28702. for (col = 0; col < options.subdivisions; col++) {
  28703. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  28704. indices.push(col + 1 + row * (options.subdivisions + 1));
  28705. indices.push(col + row * (options.subdivisions + 1));
  28706. indices.push(col + (row + 1) * (options.subdivisions + 1));
  28707. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  28708. indices.push(col + row * (options.subdivisions + 1));
  28709. }
  28710. }
  28711. // Normals
  28712. VertexData.ComputeNormals(positions, indices, normals);
  28713. // Result
  28714. var vertexData = new VertexData();
  28715. vertexData.indices = indices;
  28716. vertexData.positions = positions;
  28717. vertexData.normals = normals;
  28718. vertexData.uvs = uvs;
  28719. return vertexData;
  28720. };
  28721. /**
  28722. * Creates the VertexData of the Plane.
  28723. */
  28724. VertexData.CreatePlane = function (options) {
  28725. var indices = [];
  28726. var positions = [];
  28727. var normals = [];
  28728. var uvs = [];
  28729. var width = options.width || options.size || 1;
  28730. var height = options.height || options.size || 1;
  28731. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28732. // Vertices
  28733. var halfWidth = width / 2.0;
  28734. var halfHeight = height / 2.0;
  28735. positions.push(-halfWidth, -halfHeight, 0);
  28736. normals.push(0, 0, -1.0);
  28737. uvs.push(0.0, 0.0);
  28738. positions.push(halfWidth, -halfHeight, 0);
  28739. normals.push(0, 0, -1.0);
  28740. uvs.push(1.0, 0.0);
  28741. positions.push(halfWidth, halfHeight, 0);
  28742. normals.push(0, 0, -1.0);
  28743. uvs.push(1.0, 1.0);
  28744. positions.push(-halfWidth, halfHeight, 0);
  28745. normals.push(0, 0, -1.0);
  28746. uvs.push(0.0, 1.0);
  28747. // Indices
  28748. indices.push(0);
  28749. indices.push(1);
  28750. indices.push(2);
  28751. indices.push(0);
  28752. indices.push(2);
  28753. indices.push(3);
  28754. // Sides
  28755. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28756. // Result
  28757. var vertexData = new VertexData();
  28758. vertexData.indices = indices;
  28759. vertexData.positions = positions;
  28760. vertexData.normals = normals;
  28761. vertexData.uvs = uvs;
  28762. return vertexData;
  28763. };
  28764. /**
  28765. * Creates the VertexData of the Disc or regular Polygon.
  28766. */
  28767. VertexData.CreateDisc = function (options) {
  28768. var positions = new Array();
  28769. var indices = new Array();
  28770. var normals = new Array();
  28771. var uvs = new Array();
  28772. var radius = options.radius || 0.5;
  28773. var tessellation = options.tessellation || 64;
  28774. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28775. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28776. // positions and uvs
  28777. positions.push(0, 0, 0); // disc center first
  28778. uvs.push(0.5, 0.5);
  28779. var theta = Math.PI * 2 * arc;
  28780. var step = theta / tessellation;
  28781. for (var a = 0; a < theta; a += step) {
  28782. var x = Math.cos(a);
  28783. var y = Math.sin(a);
  28784. var u = (x + 1) / 2;
  28785. var v = (1 - y) / 2;
  28786. positions.push(radius * x, radius * y, 0);
  28787. uvs.push(u, v);
  28788. }
  28789. if (arc === 1) {
  28790. positions.push(positions[3], positions[4], positions[5]); // close the circle
  28791. uvs.push(uvs[2], uvs[3]);
  28792. }
  28793. //indices
  28794. var vertexNb = positions.length / 3;
  28795. for (var i = 1; i < vertexNb - 1; i++) {
  28796. indices.push(i + 1, 0, i);
  28797. }
  28798. // result
  28799. VertexData.ComputeNormals(positions, indices, normals);
  28800. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28801. var vertexData = new VertexData();
  28802. vertexData.indices = indices;
  28803. vertexData.positions = positions;
  28804. vertexData.normals = normals;
  28805. vertexData.uvs = uvs;
  28806. return vertexData;
  28807. };
  28808. /**
  28809. * Re-creates the VertexData of the Polygon for sideOrientation.
  28810. */
  28811. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  28812. var faceUV = fUV || new Array(3);
  28813. var faceColors = fColors;
  28814. var colors = [];
  28815. // default face colors and UV if undefined
  28816. for (var f = 0; f < 3; f++) {
  28817. if (faceUV[f] === undefined) {
  28818. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28819. }
  28820. if (faceColors && faceColors[f] === undefined) {
  28821. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28822. }
  28823. }
  28824. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28825. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28826. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28827. var indices = polygon.getIndices();
  28828. // set face colours and textures
  28829. var idx = 0;
  28830. var face = 0;
  28831. for (var index = 0; index < normals.length; index += 3) {
  28832. //Edge Face no. 1
  28833. if (Math.abs(normals[index + 1]) < 0.001) {
  28834. face = 1;
  28835. }
  28836. //Top Face no. 0
  28837. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  28838. face = 0;
  28839. }
  28840. //Bottom Face no. 2
  28841. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  28842. face = 2;
  28843. }
  28844. idx = index / 3;
  28845. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  28846. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  28847. if (faceColors) {
  28848. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  28849. }
  28850. }
  28851. // sides
  28852. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  28853. // Result
  28854. var vertexData = new VertexData();
  28855. vertexData.indices = indices;
  28856. vertexData.positions = positions;
  28857. vertexData.normals = normals;
  28858. vertexData.uvs = uvs;
  28859. if (faceColors) {
  28860. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  28861. vertexData.colors = totalColors;
  28862. }
  28863. return vertexData;
  28864. };
  28865. /**
  28866. * Creates the VertexData of the IcoSphere.
  28867. */
  28868. VertexData.CreateIcoSphere = function (options) {
  28869. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28870. var radius = options.radius || 1;
  28871. var flat = (options.flat === undefined) ? true : options.flat;
  28872. var subdivisions = options.subdivisions || 4;
  28873. var radiusX = options.radiusX || radius;
  28874. var radiusY = options.radiusY || radius;
  28875. var radiusZ = options.radiusZ || radius;
  28876. var t = (1 + Math.sqrt(5)) / 2;
  28877. // 12 vertex x,y,z
  28878. var ico_vertices = [
  28879. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  28880. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  28881. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  28882. ];
  28883. // index of 3 vertex makes a face of icopshere
  28884. var ico_indices = [
  28885. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  28886. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  28887. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  28888. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  28889. ];
  28890. // vertex for uv have aliased position, not for UV
  28891. var vertices_unalias_id = [
  28892. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  28893. // vertex alias
  28894. 0,
  28895. 2,
  28896. 3,
  28897. 3,
  28898. 3,
  28899. 4,
  28900. 7,
  28901. 8,
  28902. 9,
  28903. 9,
  28904. 10,
  28905. 11 // 23: B + 12
  28906. ];
  28907. // uv as integer step (not pixels !)
  28908. var ico_vertexuv = [
  28909. 5, 1, 3, 1, 6, 4, 0, 0,
  28910. 5, 3, 4, 2, 2, 2, 4, 0,
  28911. 2, 0, 1, 1, 6, 0, 6, 2,
  28912. // vertex alias (for same vertex on different faces)
  28913. 0, 4,
  28914. 3, 3,
  28915. 4, 4,
  28916. 3, 1,
  28917. 4, 2,
  28918. 4, 4,
  28919. 0, 2,
  28920. 1, 1,
  28921. 2, 2,
  28922. 3, 3,
  28923. 1, 3,
  28924. 2, 4 // 23: B + 12
  28925. ];
  28926. // Vertices[0, 1, ...9, A, B] : position on UV plane
  28927. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  28928. // First island of uv mapping
  28929. // v = 4h 3+ 2
  28930. // v = 3h 9+ 4
  28931. // v = 2h 9+ 5 B
  28932. // v = 1h 9 1 0
  28933. // v = 0h 3 8 7 A
  28934. // u = 0 1 2 3 4 5 6 *a
  28935. // Second island of uv mapping
  28936. // v = 4h 0+ B+ 4+
  28937. // v = 3h A+ 2+
  28938. // v = 2h 7+ 6 3+
  28939. // v = 1h 8+ 3+
  28940. // v = 0h
  28941. // u = 0 1 2 3 4 5 6 *a
  28942. // Face layout on texture UV mapping
  28943. // ============
  28944. // \ 4 /\ 16 / ======
  28945. // \ / \ / /\ 11 /
  28946. // \/ 7 \/ / \ /
  28947. // ======= / 10 \/
  28948. // /\ 17 /\ =======
  28949. // / \ / \ \ 15 /\
  28950. // / 8 \/ 12 \ \ / \
  28951. // ============ \/ 6 \
  28952. // \ 18 /\ ============
  28953. // \ / \ \ 5 /\ 0 /
  28954. // \/ 13 \ \ / \ /
  28955. // ======= \/ 1 \/
  28956. // =============
  28957. // /\ 19 /\ 2 /\
  28958. // / \ / \ / \
  28959. // / 14 \/ 9 \/ 3 \
  28960. // ===================
  28961. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  28962. var ustep = 138 / 1024;
  28963. var vstep = 239 / 1024;
  28964. var uoffset = 60 / 1024;
  28965. var voffset = 26 / 1024;
  28966. // Second island should have margin, not to touch the first island
  28967. // avoid any borderline artefact in pixel rounding
  28968. var island_u_offset = -40 / 1024;
  28969. var island_v_offset = +20 / 1024;
  28970. // face is either island 0 or 1 :
  28971. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  28972. var island = [
  28973. 0, 0, 0, 0, 1,
  28974. 0, 0, 1, 1, 0,
  28975. 0, 0, 1, 1, 0,
  28976. 0, 1, 1, 1, 0 // 15 - 19
  28977. ];
  28978. var indices = new Array();
  28979. var positions = new Array();
  28980. var normals = new Array();
  28981. var uvs = new Array();
  28982. var current_indice = 0;
  28983. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  28984. var face_vertex_pos = new Array(3);
  28985. var face_vertex_uv = new Array(3);
  28986. var v012;
  28987. for (v012 = 0; v012 < 3; v012++) {
  28988. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  28989. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  28990. }
  28991. // create all with normals
  28992. for (var face = 0; face < 20; face++) {
  28993. // 3 vertex per face
  28994. for (v012 = 0; v012 < 3; v012++) {
  28995. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  28996. var v_id = ico_indices[3 * face + v012];
  28997. // vertex have 3D position (x,y,z)
  28998. 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]);
  28999. // Normalize to get normal, then scale to radius
  29000. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  29001. // uv Coordinates from vertex ID
  29002. 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);
  29003. }
  29004. // Subdivide the face (interpolate pos, norm, uv)
  29005. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  29006. // - norm is linear interpolation of vertex corner normal
  29007. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  29008. // - uv is linear interpolation
  29009. //
  29010. // Topology is as below for sub-divide by 2
  29011. // vertex shown as v0,v1,v2
  29012. // interp index is i1 to progress in range [v0,v1[
  29013. // interp index is i2 to progress in range [v0,v2[
  29014. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  29015. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29016. //
  29017. //
  29018. // i2 v2
  29019. // ^ ^
  29020. // / / \
  29021. // / / \
  29022. // / / \
  29023. // / / (0,1) \
  29024. // / #---------\
  29025. // / / \ (0,0)'/ \
  29026. // / / \ / \
  29027. // / / \ / \
  29028. // / / (0,0) \ / (1,0) \
  29029. // / #---------#---------\
  29030. // v0 v1
  29031. //
  29032. // --------------------> i1
  29033. //
  29034. // interp of (i1,i2):
  29035. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  29036. // along i1 : lerp(x0,x1, i1/(S-i2))
  29037. //
  29038. // centroid of triangle is needed to get help normal computation
  29039. // (c1,c2) are used for centroid location
  29040. var interp_vertex = function (i1, i2, c1, c2) {
  29041. // vertex is interpolated from
  29042. // - face_vertex_pos[0..2]
  29043. // - face_vertex_uv[0..2]
  29044. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  29045. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  29046. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  29047. pos_interp.normalize();
  29048. var vertex_normal;
  29049. if (flat) {
  29050. // in flat mode, recalculate normal as face centroid normal
  29051. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  29052. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  29053. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  29054. }
  29055. else {
  29056. // in smooth mode, recalculate normal from each single vertex position
  29057. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  29058. }
  29059. // Vertex normal need correction due to X,Y,Z radius scaling
  29060. vertex_normal.x /= radiusX;
  29061. vertex_normal.y /= radiusY;
  29062. vertex_normal.z /= radiusZ;
  29063. vertex_normal.normalize();
  29064. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  29065. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  29066. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  29067. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  29068. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  29069. uvs.push(uv_interp.x, uv_interp.y);
  29070. // push each vertex has member of a face
  29071. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  29072. indices.push(current_indice);
  29073. current_indice++;
  29074. };
  29075. for (var i2 = 0; i2 < subdivisions; i2++) {
  29076. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  29077. // face : (i1,i2) for /\ :
  29078. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  29079. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29080. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29081. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29082. if (i1 + i2 + 1 < subdivisions) {
  29083. // face : (i1,i2)' for \/ :
  29084. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29085. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29086. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29087. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29088. }
  29089. }
  29090. }
  29091. }
  29092. // Sides
  29093. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29094. // Result
  29095. var vertexData = new VertexData();
  29096. vertexData.indices = indices;
  29097. vertexData.positions = positions;
  29098. vertexData.normals = normals;
  29099. vertexData.uvs = uvs;
  29100. return vertexData;
  29101. };
  29102. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  29103. /**
  29104. * Creates the VertexData of the Polyhedron.
  29105. */
  29106. VertexData.CreatePolyhedron = function (options) {
  29107. // provided polyhedron types :
  29108. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  29109. // 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)
  29110. var polyhedra = [];
  29111. 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]] };
  29112. 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]] };
  29113. polyhedra[2] = {
  29114. 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]],
  29115. 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]]
  29116. };
  29117. polyhedra[3] = {
  29118. 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]],
  29119. 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]]
  29120. };
  29121. polyhedra[4] = {
  29122. 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]],
  29123. 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]]
  29124. };
  29125. 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]] };
  29126. 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]] };
  29127. 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]] };
  29128. 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]] };
  29129. 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]] };
  29130. 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]] };
  29131. 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]] };
  29132. 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]] };
  29133. 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]] };
  29134. polyhedra[14] = {
  29135. 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]],
  29136. 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]]
  29137. };
  29138. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  29139. var size = options.size;
  29140. var sizeX = options.sizeX || size || 1;
  29141. var sizeY = options.sizeY || size || 1;
  29142. var sizeZ = options.sizeZ || size || 1;
  29143. var data = options.custom || polyhedra[type];
  29144. var nbfaces = data.face.length;
  29145. var faceUV = options.faceUV || new Array(nbfaces);
  29146. var faceColors = options.faceColors;
  29147. var flat = (options.flat === undefined) ? true : options.flat;
  29148. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29149. var positions = new Array();
  29150. var indices = new Array();
  29151. var normals = new Array();
  29152. var uvs = new Array();
  29153. var colors = new Array();
  29154. var index = 0;
  29155. var faceIdx = 0; // face cursor in the array "indexes"
  29156. var indexes = new Array();
  29157. var i = 0;
  29158. var f = 0;
  29159. var u, v, ang, x, y, tmp;
  29160. // default face colors and UV if undefined
  29161. if (flat) {
  29162. for (f = 0; f < nbfaces; f++) {
  29163. if (faceColors && faceColors[f] === undefined) {
  29164. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29165. }
  29166. if (faceUV && faceUV[f] === undefined) {
  29167. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29168. }
  29169. }
  29170. }
  29171. if (!flat) {
  29172. for (i = 0; i < data.vertex.length; i++) {
  29173. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  29174. uvs.push(0, 0);
  29175. }
  29176. for (f = 0; f < nbfaces; f++) {
  29177. for (i = 0; i < data.face[f].length - 2; i++) {
  29178. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  29179. }
  29180. }
  29181. }
  29182. else {
  29183. for (f = 0; f < nbfaces; f++) {
  29184. var fl = data.face[f].length; // number of vertices of the current face
  29185. ang = 2 * Math.PI / fl;
  29186. x = 0.5 * Math.tan(ang / 2);
  29187. y = 0.5;
  29188. // positions, uvs, colors
  29189. for (i = 0; i < fl; i++) {
  29190. // positions
  29191. 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);
  29192. indexes.push(index);
  29193. index++;
  29194. // uvs
  29195. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  29196. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  29197. uvs.push(u, v);
  29198. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  29199. y = x * Math.sin(ang) + y * Math.cos(ang);
  29200. x = tmp;
  29201. // colors
  29202. if (faceColors) {
  29203. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  29204. }
  29205. }
  29206. // indices from indexes
  29207. for (i = 0; i < fl - 2; i++) {
  29208. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  29209. }
  29210. faceIdx += fl;
  29211. }
  29212. }
  29213. VertexData.ComputeNormals(positions, indices, normals);
  29214. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29215. var vertexData = new VertexData();
  29216. vertexData.positions = positions;
  29217. vertexData.indices = indices;
  29218. vertexData.normals = normals;
  29219. vertexData.uvs = uvs;
  29220. if (faceColors && flat) {
  29221. vertexData.colors = colors;
  29222. }
  29223. return vertexData;
  29224. };
  29225. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  29226. /**
  29227. * Creates the VertexData of the Torus Knot.
  29228. */
  29229. VertexData.CreateTorusKnot = function (options) {
  29230. var indices = new Array();
  29231. var positions = new Array();
  29232. var normals = new Array();
  29233. var uvs = new Array();
  29234. var radius = options.radius || 2;
  29235. var tube = options.tube || 0.5;
  29236. var radialSegments = options.radialSegments || 32;
  29237. var tubularSegments = options.tubularSegments || 32;
  29238. var p = options.p || 2;
  29239. var q = options.q || 3;
  29240. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29241. // Helper
  29242. var getPos = function (angle) {
  29243. var cu = Math.cos(angle);
  29244. var su = Math.sin(angle);
  29245. var quOverP = q / p * angle;
  29246. var cs = Math.cos(quOverP);
  29247. var tx = radius * (2 + cs) * 0.5 * cu;
  29248. var ty = radius * (2 + cs) * su * 0.5;
  29249. var tz = radius * Math.sin(quOverP) * 0.5;
  29250. return new BABYLON.Vector3(tx, ty, tz);
  29251. };
  29252. // Vertices
  29253. var i;
  29254. var j;
  29255. for (i = 0; i <= radialSegments; i++) {
  29256. var modI = i % radialSegments;
  29257. var u = modI / radialSegments * 2 * p * Math.PI;
  29258. var p1 = getPos(u);
  29259. var p2 = getPos(u + 0.01);
  29260. var tang = p2.subtract(p1);
  29261. var n = p2.add(p1);
  29262. var bitan = BABYLON.Vector3.Cross(tang, n);
  29263. n = BABYLON.Vector3.Cross(bitan, tang);
  29264. bitan.normalize();
  29265. n.normalize();
  29266. for (j = 0; j < tubularSegments; j++) {
  29267. var modJ = j % tubularSegments;
  29268. var v = modJ / tubularSegments * 2 * Math.PI;
  29269. var cx = -tube * Math.cos(v);
  29270. var cy = tube * Math.sin(v);
  29271. positions.push(p1.x + cx * n.x + cy * bitan.x);
  29272. positions.push(p1.y + cx * n.y + cy * bitan.y);
  29273. positions.push(p1.z + cx * n.z + cy * bitan.z);
  29274. uvs.push(i / radialSegments);
  29275. uvs.push(j / tubularSegments);
  29276. }
  29277. }
  29278. for (i = 0; i < radialSegments; i++) {
  29279. for (j = 0; j < tubularSegments; j++) {
  29280. var jNext = (j + 1) % tubularSegments;
  29281. var a = i * tubularSegments + j;
  29282. var b = (i + 1) * tubularSegments + j;
  29283. var c = (i + 1) * tubularSegments + jNext;
  29284. var d = i * tubularSegments + jNext;
  29285. indices.push(d);
  29286. indices.push(b);
  29287. indices.push(a);
  29288. indices.push(d);
  29289. indices.push(c);
  29290. indices.push(b);
  29291. }
  29292. }
  29293. // Normals
  29294. VertexData.ComputeNormals(positions, indices, normals);
  29295. // Sides
  29296. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29297. // Result
  29298. var vertexData = new VertexData();
  29299. vertexData.indices = indices;
  29300. vertexData.positions = positions;
  29301. vertexData.normals = normals;
  29302. vertexData.uvs = uvs;
  29303. return vertexData;
  29304. };
  29305. // Tools
  29306. /**
  29307. * @param {any} - positions (number[] or Float32Array)
  29308. * @param {any} - indices (number[] or Uint16Array)
  29309. * @param {any} - normals (number[] or Float32Array)
  29310. * options (optional) :
  29311. * facetPositions : optional array of facet positions (vector3)
  29312. * facetNormals : optional array of facet normals (vector3)
  29313. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  29314. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  29315. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  29316. * bbSize : optional bounding box size data, required for facetPartitioning computation
  29317. * bInfo : optional bounding info, required for facetPartitioning computation
  29318. */
  29319. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  29320. // temporary scalar variables
  29321. var index = 0; // facet index
  29322. var p1p2x = 0.0; // p1p2 vector x coordinate
  29323. var p1p2y = 0.0; // p1p2 vector y coordinate
  29324. var p1p2z = 0.0; // p1p2 vector z coordinate
  29325. var p3p2x = 0.0; // p3p2 vector x coordinate
  29326. var p3p2y = 0.0; // p3p2 vector y coordinate
  29327. var p3p2z = 0.0; // p3p2 vector z coordinate
  29328. var faceNormalx = 0.0; // facet normal x coordinate
  29329. var faceNormaly = 0.0; // facet normal y coordinate
  29330. var faceNormalz = 0.0; // facet normal z coordinate
  29331. var length = 0.0; // facet normal length before normalization
  29332. var v1x = 0; // vector1 x index in the positions array
  29333. var v1y = 0; // vector1 y index in the positions array
  29334. var v1z = 0; // vector1 z index in the positions array
  29335. var v2x = 0; // vector2 x index in the positions array
  29336. var v2y = 0; // vector2 y index in the positions array
  29337. var v2z = 0; // vector2 z index in the positions array
  29338. var v3x = 0; // vector3 x index in the positions array
  29339. var v3y = 0; // vector3 y index in the positions array
  29340. var v3z = 0; // vector3 z index in the positions array
  29341. var computeFacetNormals = false;
  29342. var computeFacetPositions = false;
  29343. var computeFacetPartitioning = false;
  29344. var faceNormalSign = 1;
  29345. if (options) {
  29346. computeFacetNormals = (options.facetNormals) ? true : false;
  29347. computeFacetPositions = (options.facetPositions) ? true : false;
  29348. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  29349. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  29350. }
  29351. // facetPartitioning reinit if needed
  29352. if (computeFacetPartitioning) {
  29353. var ox = 0; // X partitioning index for facet position
  29354. var oy = 0; // Y partinioning index for facet position
  29355. var oz = 0; // Z partinioning index for facet position
  29356. var b1x = 0; // X partitioning index for facet v1 vertex
  29357. var b1y = 0; // Y partitioning index for facet v1 vertex
  29358. var b1z = 0; // z partitioning index for facet v1 vertex
  29359. var b2x = 0; // X partitioning index for facet v2 vertex
  29360. var b2y = 0; // Y partitioning index for facet v2 vertex
  29361. var b2z = 0; // Z partitioning index for facet v2 vertex
  29362. var b3x = 0; // X partitioning index for facet v3 vertex
  29363. var b3y = 0; // Y partitioning index for facet v3 vertex
  29364. var b3z = 0; // Z partitioning index for facet v3 vertex
  29365. var block_idx_o = 0; // facet barycenter block index
  29366. var block_idx_v1 = 0; // v1 vertex block index
  29367. var block_idx_v2 = 0; // v2 vertex block index
  29368. var block_idx_v3 = 0; // v3 vertex block index
  29369. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  29370. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  29371. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  29372. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  29373. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  29374. var subSq = options.subDiv.max * options.subDiv.max;
  29375. options.facetPartitioning.length = 0;
  29376. }
  29377. // reset the normals
  29378. for (index = 0; index < positions.length; index++) {
  29379. normals[index] = 0.0;
  29380. }
  29381. // Loop : 1 indice triplet = 1 facet
  29382. var nbFaces = indices.length / 3;
  29383. for (index = 0; index < nbFaces; index++) {
  29384. // get the indexes of the coordinates of each vertex of the facet
  29385. v1x = indices[index * 3] * 3;
  29386. v1y = v1x + 1;
  29387. v1z = v1x + 2;
  29388. v2x = indices[index * 3 + 1] * 3;
  29389. v2y = v2x + 1;
  29390. v2z = v2x + 2;
  29391. v3x = indices[index * 3 + 2] * 3;
  29392. v3y = v3x + 1;
  29393. v3z = v3x + 2;
  29394. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  29395. p1p2y = positions[v1y] - positions[v2y];
  29396. p1p2z = positions[v1z] - positions[v2z];
  29397. p3p2x = positions[v3x] - positions[v2x];
  29398. p3p2y = positions[v3y] - positions[v2y];
  29399. p3p2z = positions[v3z] - positions[v2z];
  29400. // compute the face normal with the cross product
  29401. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  29402. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  29403. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  29404. // normalize this normal and store it in the array facetData
  29405. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  29406. length = (length === 0) ? 1.0 : length;
  29407. faceNormalx /= length;
  29408. faceNormaly /= length;
  29409. faceNormalz /= length;
  29410. if (computeFacetNormals) {
  29411. options.facetNormals[index].x = faceNormalx;
  29412. options.facetNormals[index].y = faceNormaly;
  29413. options.facetNormals[index].z = faceNormalz;
  29414. }
  29415. if (computeFacetPositions) {
  29416. // compute and the facet barycenter coordinates in the array facetPositions
  29417. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  29418. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  29419. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  29420. }
  29421. if (computeFacetPartitioning) {
  29422. // store the facet indexes in arrays in the main facetPartitioning array :
  29423. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  29424. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  29425. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  29426. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  29427. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  29428. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  29429. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  29430. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  29431. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  29432. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  29433. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  29434. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  29435. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  29436. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  29437. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  29438. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  29439. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  29440. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  29441. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  29442. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  29443. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  29444. // push each facet index in each block containing the vertex
  29445. options.facetPartitioning[block_idx_v1].push(index);
  29446. if (block_idx_v2 != block_idx_v1) {
  29447. options.facetPartitioning[block_idx_v2].push(index);
  29448. }
  29449. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  29450. options.facetPartitioning[block_idx_v3].push(index);
  29451. }
  29452. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  29453. options.facetPartitioning[block_idx_o].push(index);
  29454. }
  29455. }
  29456. // compute the normals anyway
  29457. normals[v1x] += faceNormalx; // accumulate all the normals per face
  29458. normals[v1y] += faceNormaly;
  29459. normals[v1z] += faceNormalz;
  29460. normals[v2x] += faceNormalx;
  29461. normals[v2y] += faceNormaly;
  29462. normals[v2z] += faceNormalz;
  29463. normals[v3x] += faceNormalx;
  29464. normals[v3y] += faceNormaly;
  29465. normals[v3z] += faceNormalz;
  29466. }
  29467. // last normalization of each normal
  29468. for (index = 0; index < normals.length / 3; index++) {
  29469. faceNormalx = normals[index * 3];
  29470. faceNormaly = normals[index * 3 + 1];
  29471. faceNormalz = normals[index * 3 + 2];
  29472. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  29473. length = (length === 0) ? 1.0 : length;
  29474. faceNormalx /= length;
  29475. faceNormaly /= length;
  29476. faceNormalz /= length;
  29477. normals[index * 3] = faceNormalx;
  29478. normals[index * 3 + 1] = faceNormaly;
  29479. normals[index * 3 + 2] = faceNormalz;
  29480. }
  29481. };
  29482. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  29483. var li = indices.length;
  29484. var ln = normals.length;
  29485. var i;
  29486. var n;
  29487. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29488. switch (sideOrientation) {
  29489. case BABYLON.Mesh.FRONTSIDE:
  29490. // nothing changed
  29491. break;
  29492. case BABYLON.Mesh.BACKSIDE:
  29493. var tmp;
  29494. // indices
  29495. for (i = 0; i < li; i += 3) {
  29496. tmp = indices[i];
  29497. indices[i] = indices[i + 2];
  29498. indices[i + 2] = tmp;
  29499. }
  29500. // normals
  29501. for (n = 0; n < ln; n++) {
  29502. normals[n] = -normals[n];
  29503. }
  29504. break;
  29505. case BABYLON.Mesh.DOUBLESIDE:
  29506. // positions
  29507. var lp = positions.length;
  29508. var l = lp / 3;
  29509. for (var p = 0; p < lp; p++) {
  29510. positions[lp + p] = positions[p];
  29511. }
  29512. // indices
  29513. for (i = 0; i < li; i += 3) {
  29514. indices[i + li] = indices[i + 2] + l;
  29515. indices[i + 1 + li] = indices[i + 1] + l;
  29516. indices[i + 2 + li] = indices[i] + l;
  29517. }
  29518. // normals
  29519. for (n = 0; n < ln; n++) {
  29520. normals[ln + n] = -normals[n];
  29521. }
  29522. // uvs
  29523. var lu = uvs.length;
  29524. var u = 0;
  29525. for (u = 0; u < lu; u++) {
  29526. uvs[u + lu] = uvs[u];
  29527. }
  29528. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  29529. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  29530. u = 0;
  29531. for (i = 0; i < lu / 2; i++) {
  29532. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  29533. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  29534. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  29535. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  29536. u += 2;
  29537. }
  29538. break;
  29539. }
  29540. };
  29541. /**
  29542. * Creates a new VertexData from the imported parameters.
  29543. */
  29544. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  29545. var vertexData = new VertexData();
  29546. // positions
  29547. var positions = parsedVertexData.positions;
  29548. if (positions) {
  29549. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  29550. }
  29551. // normals
  29552. var normals = parsedVertexData.normals;
  29553. if (normals) {
  29554. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  29555. }
  29556. // tangents
  29557. var tangents = parsedVertexData.tangents;
  29558. if (tangents) {
  29559. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  29560. }
  29561. // uvs
  29562. var uvs = parsedVertexData.uvs;
  29563. if (uvs) {
  29564. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  29565. }
  29566. // uv2s
  29567. var uv2s = parsedVertexData.uv2s;
  29568. if (uv2s) {
  29569. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  29570. }
  29571. // uv3s
  29572. var uv3s = parsedVertexData.uv3s;
  29573. if (uv3s) {
  29574. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  29575. }
  29576. // uv4s
  29577. var uv4s = parsedVertexData.uv4s;
  29578. if (uv4s) {
  29579. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  29580. }
  29581. // uv5s
  29582. var uv5s = parsedVertexData.uv5s;
  29583. if (uv5s) {
  29584. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  29585. }
  29586. // uv6s
  29587. var uv6s = parsedVertexData.uv6s;
  29588. if (uv6s) {
  29589. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  29590. }
  29591. // colors
  29592. var colors = parsedVertexData.colors;
  29593. if (colors) {
  29594. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  29595. }
  29596. // matricesIndices
  29597. var matricesIndices = parsedVertexData.matricesIndices;
  29598. if (matricesIndices) {
  29599. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  29600. }
  29601. // matricesWeights
  29602. var matricesWeights = parsedVertexData.matricesWeights;
  29603. if (matricesWeights) {
  29604. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  29605. }
  29606. // indices
  29607. var indices = parsedVertexData.indices;
  29608. if (indices) {
  29609. vertexData.indices = indices;
  29610. }
  29611. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  29612. };
  29613. return VertexData;
  29614. }());
  29615. BABYLON.VertexData = VertexData;
  29616. })(BABYLON || (BABYLON = {}));
  29617. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  29618. var BABYLON;
  29619. (function (BABYLON) {
  29620. var Geometry = /** @class */ (function () {
  29621. function Geometry(id, scene, vertexData, updatable, mesh) {
  29622. if (updatable === void 0) { updatable = false; }
  29623. if (mesh === void 0) { mesh = null; }
  29624. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29625. this._totalVertices = 0;
  29626. this._isDisposed = false;
  29627. this._indexBufferIsUpdatable = false;
  29628. this.id = id;
  29629. this._engine = scene.getEngine();
  29630. this._meshes = [];
  29631. this._scene = scene;
  29632. //Init vertex buffer cache
  29633. this._vertexBuffers = {};
  29634. this._indices = [];
  29635. this._updatable = updatable;
  29636. // vertexData
  29637. if (vertexData) {
  29638. this.setAllVerticesData(vertexData, updatable);
  29639. }
  29640. else {
  29641. this._totalVertices = 0;
  29642. this._indices = [];
  29643. }
  29644. if (this._engine.getCaps().vertexArrayObject) {
  29645. this._vertexArrayObjects = {};
  29646. }
  29647. // applyToMesh
  29648. if (mesh) {
  29649. if (mesh.getClassName() === "LinesMesh") {
  29650. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  29651. this.updateExtend();
  29652. }
  29653. this.applyToMesh(mesh);
  29654. mesh.computeWorldMatrix(true);
  29655. }
  29656. }
  29657. Object.defineProperty(Geometry.prototype, "boundingBias", {
  29658. /**
  29659. * 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
  29660. * @returns The Bias Vector
  29661. */
  29662. get: function () {
  29663. return this._boundingBias;
  29664. },
  29665. set: function (value) {
  29666. if (this._boundingBias && this._boundingBias.equals(value)) {
  29667. return;
  29668. }
  29669. this._boundingBias = value.clone();
  29670. this.updateBoundingInfo(true, null);
  29671. },
  29672. enumerable: true,
  29673. configurable: true
  29674. });
  29675. Object.defineProperty(Geometry.prototype, "extend", {
  29676. get: function () {
  29677. return this._extend;
  29678. },
  29679. enumerable: true,
  29680. configurable: true
  29681. });
  29682. Geometry.prototype.getScene = function () {
  29683. return this._scene;
  29684. };
  29685. Geometry.prototype.getEngine = function () {
  29686. return this._engine;
  29687. };
  29688. Geometry.prototype.isReady = function () {
  29689. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  29690. };
  29691. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  29692. get: function () {
  29693. for (var index = 0; index < this._meshes.length; index++) {
  29694. if (!this._meshes[index].doNotSerialize) {
  29695. return false;
  29696. }
  29697. }
  29698. return true;
  29699. },
  29700. enumerable: true,
  29701. configurable: true
  29702. });
  29703. Geometry.prototype._rebuild = function () {
  29704. if (this._vertexArrayObjects) {
  29705. this._vertexArrayObjects = {};
  29706. }
  29707. // Index buffer
  29708. if (this._meshes.length !== 0 && this._indices) {
  29709. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29710. }
  29711. // Vertex buffers
  29712. for (var key in this._vertexBuffers) {
  29713. var vertexBuffer = this._vertexBuffers[key];
  29714. vertexBuffer._rebuild();
  29715. }
  29716. };
  29717. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  29718. vertexData.applyToGeometry(this, updatable);
  29719. this.notifyUpdate();
  29720. };
  29721. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  29722. if (updatable === void 0) { updatable = false; }
  29723. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  29724. this.setVerticesBuffer(buffer);
  29725. };
  29726. Geometry.prototype.removeVerticesData = function (kind) {
  29727. if (this._vertexBuffers[kind]) {
  29728. this._vertexBuffers[kind].dispose();
  29729. delete this._vertexBuffers[kind];
  29730. }
  29731. };
  29732. Geometry.prototype.setVerticesBuffer = function (buffer) {
  29733. var kind = buffer.getKind();
  29734. if (this._vertexBuffers[kind]) {
  29735. this._vertexBuffers[kind].dispose();
  29736. }
  29737. this._vertexBuffers[kind] = buffer;
  29738. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29739. var data = buffer.getData();
  29740. var stride = buffer.getStrideSize();
  29741. this._totalVertices = data.length / stride;
  29742. this.updateExtend(data, stride);
  29743. this._resetPointsArrayCache();
  29744. var meshes = this._meshes;
  29745. var numOfMeshes = meshes.length;
  29746. for (var index = 0; index < numOfMeshes; index++) {
  29747. var mesh = meshes[index];
  29748. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29749. mesh._createGlobalSubMesh(false);
  29750. mesh.computeWorldMatrix(true);
  29751. }
  29752. }
  29753. this.notifyUpdate(kind);
  29754. if (this._vertexArrayObjects) {
  29755. this._disposeVertexArrayObjects();
  29756. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  29757. }
  29758. };
  29759. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  29760. var vertexBuffer = this.getVertexBuffer(kind);
  29761. if (!vertexBuffer) {
  29762. return;
  29763. }
  29764. vertexBuffer.updateDirectly(data, offset);
  29765. this.notifyUpdate(kind);
  29766. };
  29767. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  29768. if (updateExtends === void 0) { updateExtends = false; }
  29769. var vertexBuffer = this.getVertexBuffer(kind);
  29770. if (!vertexBuffer) {
  29771. return;
  29772. }
  29773. vertexBuffer.update(data);
  29774. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29775. var stride = vertexBuffer.getStrideSize();
  29776. this._totalVertices = data.length / stride;
  29777. this.updateBoundingInfo(updateExtends, data);
  29778. }
  29779. this.notifyUpdate(kind);
  29780. };
  29781. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  29782. if (updateExtends) {
  29783. this.updateExtend(data);
  29784. }
  29785. var meshes = this._meshes;
  29786. var numOfMeshes = meshes.length;
  29787. this._resetPointsArrayCache();
  29788. for (var index = 0; index < numOfMeshes; index++) {
  29789. var mesh = meshes[index];
  29790. if (updateExtends) {
  29791. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29792. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  29793. var subMesh = mesh.subMeshes[subIndex];
  29794. subMesh.refreshBoundingInfo();
  29795. }
  29796. }
  29797. }
  29798. };
  29799. Geometry.prototype._bind = function (effect, indexToBind) {
  29800. if (indexToBind === undefined) {
  29801. indexToBind = this._indexBuffer;
  29802. }
  29803. var vbs = this.getVertexBuffers();
  29804. if (!vbs) {
  29805. return;
  29806. }
  29807. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  29808. this._engine.bindBuffers(vbs, indexToBind, effect);
  29809. return;
  29810. }
  29811. // Using VAO
  29812. if (!this._vertexArrayObjects[effect.key]) {
  29813. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  29814. }
  29815. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  29816. };
  29817. Geometry.prototype.getTotalVertices = function () {
  29818. if (!this.isReady()) {
  29819. return 0;
  29820. }
  29821. return this._totalVertices;
  29822. };
  29823. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  29824. var vertexBuffer = this.getVertexBuffer(kind);
  29825. if (!vertexBuffer) {
  29826. return null;
  29827. }
  29828. var orig = vertexBuffer.getData();
  29829. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  29830. return orig;
  29831. }
  29832. else {
  29833. var len = orig.length;
  29834. var copy = [];
  29835. for (var i = 0; i < len; i++) {
  29836. copy.push(orig[i]);
  29837. }
  29838. return copy;
  29839. }
  29840. };
  29841. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  29842. var vb = this._vertexBuffers[kind];
  29843. if (!vb) {
  29844. return false;
  29845. }
  29846. return vb.isUpdatable();
  29847. };
  29848. Geometry.prototype.getVertexBuffer = function (kind) {
  29849. if (!this.isReady()) {
  29850. return null;
  29851. }
  29852. return this._vertexBuffers[kind];
  29853. };
  29854. Geometry.prototype.getVertexBuffers = function () {
  29855. if (!this.isReady()) {
  29856. return null;
  29857. }
  29858. return this._vertexBuffers;
  29859. };
  29860. Geometry.prototype.isVerticesDataPresent = function (kind) {
  29861. if (!this._vertexBuffers) {
  29862. if (this._delayInfo) {
  29863. return this._delayInfo.indexOf(kind) !== -1;
  29864. }
  29865. return false;
  29866. }
  29867. return this._vertexBuffers[kind] !== undefined;
  29868. };
  29869. Geometry.prototype.getVerticesDataKinds = function () {
  29870. var result = [];
  29871. var kind;
  29872. if (!this._vertexBuffers && this._delayInfo) {
  29873. for (kind in this._delayInfo) {
  29874. result.push(kind);
  29875. }
  29876. }
  29877. else {
  29878. for (kind in this._vertexBuffers) {
  29879. result.push(kind);
  29880. }
  29881. }
  29882. return result;
  29883. };
  29884. Geometry.prototype.updateIndices = function (indices, offset) {
  29885. if (!this._indexBuffer) {
  29886. return;
  29887. }
  29888. if (!this._indexBufferIsUpdatable) {
  29889. this.setIndices(indices, null, true);
  29890. }
  29891. else {
  29892. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  29893. }
  29894. };
  29895. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  29896. if (totalVertices === void 0) { totalVertices = null; }
  29897. if (updatable === void 0) { updatable = false; }
  29898. if (this._indexBuffer) {
  29899. this._engine._releaseBuffer(this._indexBuffer);
  29900. }
  29901. this._disposeVertexArrayObjects();
  29902. this._indices = indices;
  29903. this._indexBufferIsUpdatable = updatable;
  29904. if (this._meshes.length !== 0 && this._indices) {
  29905. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  29906. }
  29907. if (totalVertices != undefined) {
  29908. this._totalVertices = totalVertices;
  29909. }
  29910. var meshes = this._meshes;
  29911. var numOfMeshes = meshes.length;
  29912. for (var index = 0; index < numOfMeshes; index++) {
  29913. meshes[index]._createGlobalSubMesh(true);
  29914. }
  29915. this.notifyUpdate();
  29916. };
  29917. Geometry.prototype.getTotalIndices = function () {
  29918. if (!this.isReady()) {
  29919. return 0;
  29920. }
  29921. return this._indices.length;
  29922. };
  29923. Geometry.prototype.getIndices = function (copyWhenShared) {
  29924. if (!this.isReady()) {
  29925. return null;
  29926. }
  29927. var orig = this._indices;
  29928. if (!copyWhenShared || this._meshes.length === 1) {
  29929. return orig;
  29930. }
  29931. else {
  29932. var len = orig.length;
  29933. var copy = [];
  29934. for (var i = 0; i < len; i++) {
  29935. copy.push(orig[i]);
  29936. }
  29937. return copy;
  29938. }
  29939. };
  29940. Geometry.prototype.getIndexBuffer = function () {
  29941. if (!this.isReady()) {
  29942. return null;
  29943. }
  29944. return this._indexBuffer;
  29945. };
  29946. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  29947. if (!effect || !this._vertexArrayObjects) {
  29948. return;
  29949. }
  29950. if (this._vertexArrayObjects[effect.key]) {
  29951. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  29952. delete this._vertexArrayObjects[effect.key];
  29953. }
  29954. };
  29955. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  29956. var meshes = this._meshes;
  29957. var index = meshes.indexOf(mesh);
  29958. if (index === -1) {
  29959. return;
  29960. }
  29961. meshes.splice(index, 1);
  29962. mesh._geometry = null;
  29963. if (meshes.length === 0 && shouldDispose) {
  29964. this.dispose();
  29965. }
  29966. };
  29967. Geometry.prototype.applyToMesh = function (mesh) {
  29968. if (mesh._geometry === this) {
  29969. return;
  29970. }
  29971. var previousGeometry = mesh._geometry;
  29972. if (previousGeometry) {
  29973. previousGeometry.releaseForMesh(mesh);
  29974. }
  29975. var meshes = this._meshes;
  29976. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  29977. mesh._geometry = this;
  29978. this._scene.pushGeometry(this);
  29979. meshes.push(mesh);
  29980. if (this.isReady()) {
  29981. this._applyToMesh(mesh);
  29982. }
  29983. else {
  29984. mesh._boundingInfo = this._boundingInfo;
  29985. }
  29986. };
  29987. Geometry.prototype.updateExtend = function (data, stride) {
  29988. if (data === void 0) { data = null; }
  29989. if (!data) {
  29990. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  29991. }
  29992. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  29993. };
  29994. Geometry.prototype._applyToMesh = function (mesh) {
  29995. var numOfMeshes = this._meshes.length;
  29996. // vertexBuffers
  29997. for (var kind in this._vertexBuffers) {
  29998. if (numOfMeshes === 1) {
  29999. this._vertexBuffers[kind].create();
  30000. }
  30001. var buffer = this._vertexBuffers[kind].getBuffer();
  30002. if (buffer)
  30003. buffer.references = numOfMeshes;
  30004. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30005. if (!this._extend) {
  30006. this.updateExtend(this._vertexBuffers[kind].getData());
  30007. }
  30008. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30009. mesh._createGlobalSubMesh(false);
  30010. //bounding info was just created again, world matrix should be applied again.
  30011. mesh._updateBoundingInfo();
  30012. }
  30013. }
  30014. // indexBuffer
  30015. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  30016. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  30017. }
  30018. if (this._indexBuffer) {
  30019. this._indexBuffer.references = numOfMeshes;
  30020. }
  30021. };
  30022. Geometry.prototype.notifyUpdate = function (kind) {
  30023. if (this.onGeometryUpdated) {
  30024. this.onGeometryUpdated(this, kind);
  30025. }
  30026. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  30027. var mesh = _a[_i];
  30028. mesh._markSubMeshesAsAttributesDirty();
  30029. }
  30030. };
  30031. Geometry.prototype.load = function (scene, onLoaded) {
  30032. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  30033. return;
  30034. }
  30035. if (this.isReady()) {
  30036. if (onLoaded) {
  30037. onLoaded();
  30038. }
  30039. return;
  30040. }
  30041. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  30042. this._queueLoad(scene, onLoaded);
  30043. };
  30044. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  30045. var _this = this;
  30046. if (!this.delayLoadingFile) {
  30047. return;
  30048. }
  30049. scene._addPendingData(this);
  30050. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  30051. if (!_this._delayLoadingFunction) {
  30052. return;
  30053. }
  30054. _this._delayLoadingFunction(JSON.parse(data), _this);
  30055. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30056. _this._delayInfo = [];
  30057. scene._removePendingData(_this);
  30058. var meshes = _this._meshes;
  30059. var numOfMeshes = meshes.length;
  30060. for (var index = 0; index < numOfMeshes; index++) {
  30061. _this._applyToMesh(meshes[index]);
  30062. }
  30063. if (onLoaded) {
  30064. onLoaded();
  30065. }
  30066. }, function () { }, scene.database);
  30067. };
  30068. /**
  30069. * Invert the geometry to move from a right handed system to a left handed one.
  30070. */
  30071. Geometry.prototype.toLeftHanded = function () {
  30072. // Flip faces
  30073. var tIndices = this.getIndices(false);
  30074. if (tIndices != null && tIndices.length > 0) {
  30075. for (var i = 0; i < tIndices.length; i += 3) {
  30076. var tTemp = tIndices[i + 0];
  30077. tIndices[i + 0] = tIndices[i + 2];
  30078. tIndices[i + 2] = tTemp;
  30079. }
  30080. this.setIndices(tIndices);
  30081. }
  30082. // Negate position.z
  30083. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  30084. if (tPositions != null && tPositions.length > 0) {
  30085. for (var i = 0; i < tPositions.length; i += 3) {
  30086. tPositions[i + 2] = -tPositions[i + 2];
  30087. }
  30088. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  30089. }
  30090. // Negate normal.z
  30091. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  30092. if (tNormals != null && tNormals.length > 0) {
  30093. for (var i = 0; i < tNormals.length; i += 3) {
  30094. tNormals[i + 2] = -tNormals[i + 2];
  30095. }
  30096. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  30097. }
  30098. };
  30099. // Cache
  30100. Geometry.prototype._resetPointsArrayCache = function () {
  30101. this._positions = null;
  30102. };
  30103. Geometry.prototype._generatePointsArray = function () {
  30104. if (this._positions)
  30105. return true;
  30106. this._positions = [];
  30107. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30108. if (!data) {
  30109. return false;
  30110. }
  30111. for (var index = 0; index < data.length; index += 3) {
  30112. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  30113. }
  30114. return true;
  30115. };
  30116. Geometry.prototype.isDisposed = function () {
  30117. return this._isDisposed;
  30118. };
  30119. Geometry.prototype._disposeVertexArrayObjects = function () {
  30120. if (this._vertexArrayObjects) {
  30121. for (var kind in this._vertexArrayObjects) {
  30122. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  30123. }
  30124. this._vertexArrayObjects = {};
  30125. }
  30126. };
  30127. Geometry.prototype.dispose = function () {
  30128. var meshes = this._meshes;
  30129. var numOfMeshes = meshes.length;
  30130. var index;
  30131. for (index = 0; index < numOfMeshes; index++) {
  30132. this.releaseForMesh(meshes[index]);
  30133. }
  30134. this._meshes = [];
  30135. this._disposeVertexArrayObjects();
  30136. for (var kind in this._vertexBuffers) {
  30137. this._vertexBuffers[kind].dispose();
  30138. }
  30139. this._vertexBuffers = {};
  30140. this._totalVertices = 0;
  30141. if (this._indexBuffer) {
  30142. this._engine._releaseBuffer(this._indexBuffer);
  30143. }
  30144. this._indexBuffer = null;
  30145. this._indices = [];
  30146. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30147. this.delayLoadingFile = null;
  30148. this._delayLoadingFunction = null;
  30149. this._delayInfo = [];
  30150. this._boundingInfo = null;
  30151. this._scene.removeGeometry(this);
  30152. this._isDisposed = true;
  30153. };
  30154. Geometry.prototype.copy = function (id) {
  30155. var vertexData = new BABYLON.VertexData();
  30156. vertexData.indices = [];
  30157. var indices = this.getIndices();
  30158. if (indices) {
  30159. for (var index = 0; index < indices.length; index++) {
  30160. vertexData.indices.push(indices[index]);
  30161. }
  30162. }
  30163. var updatable = false;
  30164. var stopChecking = false;
  30165. var kind;
  30166. for (kind in this._vertexBuffers) {
  30167. // using slice() to make a copy of the array and not just reference it
  30168. var data = this.getVerticesData(kind);
  30169. if (data instanceof Float32Array) {
  30170. vertexData.set(new Float32Array(data), kind);
  30171. }
  30172. else {
  30173. vertexData.set(data.slice(0), kind);
  30174. }
  30175. if (!stopChecking) {
  30176. var vb = this.getVertexBuffer(kind);
  30177. if (vb) {
  30178. updatable = vb.isUpdatable();
  30179. stopChecking = !updatable;
  30180. }
  30181. }
  30182. }
  30183. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  30184. geometry.delayLoadState = this.delayLoadState;
  30185. geometry.delayLoadingFile = this.delayLoadingFile;
  30186. geometry._delayLoadingFunction = this._delayLoadingFunction;
  30187. for (kind in this._delayInfo) {
  30188. geometry._delayInfo = geometry._delayInfo || [];
  30189. geometry._delayInfo.push(kind);
  30190. }
  30191. // Bounding info
  30192. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30193. return geometry;
  30194. };
  30195. Geometry.prototype.serialize = function () {
  30196. var serializationObject = {};
  30197. serializationObject.id = this.id;
  30198. serializationObject.updatable = this._updatable;
  30199. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  30200. serializationObject.tags = BABYLON.Tags.GetTags(this);
  30201. }
  30202. return serializationObject;
  30203. };
  30204. Geometry.prototype.toNumberArray = function (origin) {
  30205. if (Array.isArray(origin)) {
  30206. return origin;
  30207. }
  30208. else {
  30209. return Array.prototype.slice.call(origin);
  30210. }
  30211. };
  30212. Geometry.prototype.serializeVerticeData = function () {
  30213. var serializationObject = this.serialize();
  30214. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30215. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  30216. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30217. serializationObject.positions._updatable = true;
  30218. }
  30219. }
  30220. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30221. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  30222. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30223. serializationObject.normals._updatable = true;
  30224. }
  30225. }
  30226. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30227. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  30228. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  30229. serializationObject.uvs._updatable = true;
  30230. }
  30231. }
  30232. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30233. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  30234. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  30235. serializationObject.uv2s._updatable = true;
  30236. }
  30237. }
  30238. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30239. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  30240. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  30241. serializationObject.uv3s._updatable = true;
  30242. }
  30243. }
  30244. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30245. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  30246. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  30247. serializationObject.uv4s._updatable = true;
  30248. }
  30249. }
  30250. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30251. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  30252. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  30253. serializationObject.uv5s._updatable = true;
  30254. }
  30255. }
  30256. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30257. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  30258. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  30259. serializationObject.uv6s._updatable = true;
  30260. }
  30261. }
  30262. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30263. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  30264. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  30265. serializationObject.colors._updatable = true;
  30266. }
  30267. }
  30268. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30269. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  30270. serializationObject.matricesIndices._isExpanded = true;
  30271. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30272. serializationObject.matricesIndices._updatable = true;
  30273. }
  30274. }
  30275. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30276. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  30277. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30278. serializationObject.matricesWeights._updatable = true;
  30279. }
  30280. }
  30281. serializationObject.indices = this.toNumberArray(this.getIndices());
  30282. return serializationObject;
  30283. };
  30284. // Statics
  30285. Geometry.ExtractFromMesh = function (mesh, id) {
  30286. var geometry = mesh._geometry;
  30287. if (!geometry) {
  30288. return null;
  30289. }
  30290. return geometry.copy(id);
  30291. };
  30292. /**
  30293. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  30294. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  30295. * Be aware Math.random() could cause collisions, but:
  30296. * "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"
  30297. */
  30298. Geometry.RandomId = function () {
  30299. return BABYLON.Tools.RandomId();
  30300. };
  30301. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  30302. var scene = mesh.getScene();
  30303. // Geometry
  30304. var geometryId = parsedGeometry.geometryId;
  30305. if (geometryId) {
  30306. var geometry = scene.getGeometryByID(geometryId);
  30307. if (geometry) {
  30308. geometry.applyToMesh(mesh);
  30309. }
  30310. }
  30311. else if (parsedGeometry instanceof ArrayBuffer) {
  30312. var binaryInfo = mesh._binaryInfo;
  30313. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  30314. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  30315. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  30316. }
  30317. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  30318. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  30319. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  30320. }
  30321. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  30322. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  30323. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  30324. }
  30325. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  30326. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  30327. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  30328. }
  30329. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  30330. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  30331. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  30332. }
  30333. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  30334. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  30335. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  30336. }
  30337. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  30338. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  30339. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  30340. }
  30341. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  30342. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  30343. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  30344. }
  30345. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  30346. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  30347. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  30348. }
  30349. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  30350. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  30351. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  30352. }
  30353. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  30354. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  30355. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  30356. }
  30357. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  30358. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  30359. mesh.setIndices(indicesData, null);
  30360. }
  30361. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  30362. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  30363. mesh.subMeshes = [];
  30364. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  30365. var materialIndex = subMeshesData[(i * 5) + 0];
  30366. var verticesStart = subMeshesData[(i * 5) + 1];
  30367. var verticesCount = subMeshesData[(i * 5) + 2];
  30368. var indexStart = subMeshesData[(i * 5) + 3];
  30369. var indexCount = subMeshesData[(i * 5) + 4];
  30370. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  30371. }
  30372. }
  30373. }
  30374. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  30375. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  30376. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  30377. if (parsedGeometry.uvs) {
  30378. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  30379. }
  30380. if (parsedGeometry.uvs2) {
  30381. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  30382. }
  30383. if (parsedGeometry.uvs3) {
  30384. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  30385. }
  30386. if (parsedGeometry.uvs4) {
  30387. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  30388. }
  30389. if (parsedGeometry.uvs5) {
  30390. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  30391. }
  30392. if (parsedGeometry.uvs6) {
  30393. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  30394. }
  30395. if (parsedGeometry.colors) {
  30396. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  30397. }
  30398. if (parsedGeometry.matricesIndices) {
  30399. if (!parsedGeometry.matricesIndices._isExpanded) {
  30400. var floatIndices = [];
  30401. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  30402. var matricesIndex = parsedGeometry.matricesIndices[i];
  30403. floatIndices.push(matricesIndex & 0x000000FF);
  30404. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  30405. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  30406. floatIndices.push(matricesIndex >> 24);
  30407. }
  30408. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  30409. }
  30410. else {
  30411. delete parsedGeometry.matricesIndices._isExpanded;
  30412. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  30413. }
  30414. }
  30415. if (parsedGeometry.matricesIndicesExtra) {
  30416. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  30417. var floatIndices = [];
  30418. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  30419. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  30420. floatIndices.push(matricesIndex & 0x000000FF);
  30421. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  30422. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  30423. floatIndices.push(matricesIndex >> 24);
  30424. }
  30425. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  30426. }
  30427. else {
  30428. delete parsedGeometry.matricesIndices._isExpanded;
  30429. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  30430. }
  30431. }
  30432. if (parsedGeometry.matricesWeights) {
  30433. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  30434. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  30435. }
  30436. if (parsedGeometry.matricesWeightsExtra) {
  30437. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  30438. }
  30439. mesh.setIndices(parsedGeometry.indices, null);
  30440. }
  30441. // SubMeshes
  30442. if (parsedGeometry.subMeshes) {
  30443. mesh.subMeshes = [];
  30444. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  30445. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  30446. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  30447. }
  30448. }
  30449. // Flat shading
  30450. if (mesh._shouldGenerateFlatShading) {
  30451. mesh.convertToFlatShadedMesh();
  30452. delete mesh._shouldGenerateFlatShading;
  30453. }
  30454. // Update
  30455. mesh.computeWorldMatrix(true);
  30456. // Octree
  30457. if (scene['_selectionOctree']) {
  30458. scene['_selectionOctree'].addMesh(mesh);
  30459. }
  30460. };
  30461. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  30462. var epsilon = 1e-3;
  30463. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  30464. return;
  30465. }
  30466. var noInfluenceBoneIndex = 0.0;
  30467. if (parsedGeometry.skeletonId > -1) {
  30468. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  30469. if (!skeleton) {
  30470. return;
  30471. }
  30472. noInfluenceBoneIndex = skeleton.bones.length;
  30473. }
  30474. else {
  30475. return;
  30476. }
  30477. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30478. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  30479. var matricesWeights = parsedGeometry.matricesWeights;
  30480. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  30481. var influencers = parsedGeometry.numBoneInfluencer;
  30482. var size = matricesWeights.length;
  30483. for (var i = 0; i < size; i += 4) {
  30484. var weight = 0.0;
  30485. var firstZeroWeight = -1;
  30486. for (var j = 0; j < 4; j++) {
  30487. var w = matricesWeights[i + j];
  30488. weight += w;
  30489. if (w < epsilon && firstZeroWeight < 0) {
  30490. firstZeroWeight = j;
  30491. }
  30492. }
  30493. if (matricesWeightsExtra) {
  30494. for (var j = 0; j < 4; j++) {
  30495. var w = matricesWeightsExtra[i + j];
  30496. weight += w;
  30497. if (w < epsilon && firstZeroWeight < 0) {
  30498. firstZeroWeight = j + 4;
  30499. }
  30500. }
  30501. }
  30502. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  30503. firstZeroWeight = influencers - 1;
  30504. }
  30505. if (weight > epsilon) {
  30506. var mweight = 1.0 / weight;
  30507. for (var j = 0; j < 4; j++) {
  30508. matricesWeights[i + j] *= mweight;
  30509. }
  30510. if (matricesWeightsExtra) {
  30511. for (var j = 0; j < 4; j++) {
  30512. matricesWeightsExtra[i + j] *= mweight;
  30513. }
  30514. }
  30515. }
  30516. else {
  30517. if (firstZeroWeight >= 4) {
  30518. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  30519. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  30520. }
  30521. else {
  30522. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  30523. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  30524. }
  30525. }
  30526. }
  30527. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  30528. if (parsedGeometry.matricesWeightsExtra) {
  30529. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  30530. }
  30531. };
  30532. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  30533. if (scene.getGeometryByID(parsedVertexData.id)) {
  30534. return null; // null since geometry could be something else than a box...
  30535. }
  30536. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  30537. if (BABYLON.Tags) {
  30538. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  30539. }
  30540. if (parsedVertexData.delayLoadingFile) {
  30541. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30542. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  30543. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  30544. geometry._delayInfo = [];
  30545. if (parsedVertexData.hasUVs) {
  30546. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  30547. }
  30548. if (parsedVertexData.hasUVs2) {
  30549. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  30550. }
  30551. if (parsedVertexData.hasUVs3) {
  30552. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  30553. }
  30554. if (parsedVertexData.hasUVs4) {
  30555. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  30556. }
  30557. if (parsedVertexData.hasUVs5) {
  30558. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  30559. }
  30560. if (parsedVertexData.hasUVs6) {
  30561. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  30562. }
  30563. if (parsedVertexData.hasColors) {
  30564. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  30565. }
  30566. if (parsedVertexData.hasMatricesIndices) {
  30567. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  30568. }
  30569. if (parsedVertexData.hasMatricesWeights) {
  30570. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  30571. }
  30572. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  30573. }
  30574. else {
  30575. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  30576. }
  30577. scene.pushGeometry(geometry, true);
  30578. return geometry;
  30579. };
  30580. return Geometry;
  30581. }());
  30582. BABYLON.Geometry = Geometry;
  30583. /////// Primitives //////////////////////////////////////////////
  30584. (function (Geometry) {
  30585. var Primitives;
  30586. (function (Primitives) {
  30587. /// Abstract class
  30588. var _Primitive = /** @class */ (function (_super) {
  30589. __extends(_Primitive, _super);
  30590. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  30591. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  30592. if (mesh === void 0) { mesh = null; }
  30593. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  30594. _this._canBeRegenerated = _canBeRegenerated;
  30595. _this._beingRegenerated = true;
  30596. _this.regenerate();
  30597. _this._beingRegenerated = false;
  30598. return _this;
  30599. }
  30600. _Primitive.prototype.canBeRegenerated = function () {
  30601. return this._canBeRegenerated;
  30602. };
  30603. _Primitive.prototype.regenerate = function () {
  30604. if (!this._canBeRegenerated) {
  30605. return;
  30606. }
  30607. this._beingRegenerated = true;
  30608. this.setAllVerticesData(this._regenerateVertexData(), false);
  30609. this._beingRegenerated = false;
  30610. };
  30611. _Primitive.prototype.asNewGeometry = function (id) {
  30612. return _super.prototype.copy.call(this, id);
  30613. };
  30614. // overrides
  30615. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  30616. if (!this._beingRegenerated) {
  30617. return;
  30618. }
  30619. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  30620. };
  30621. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  30622. if (!this._beingRegenerated) {
  30623. return;
  30624. }
  30625. _super.prototype.setVerticesData.call(this, kind, data, false);
  30626. };
  30627. // to override
  30628. // protected
  30629. _Primitive.prototype._regenerateVertexData = function () {
  30630. throw new Error("Abstract method");
  30631. };
  30632. _Primitive.prototype.copy = function (id) {
  30633. throw new Error("Must be overriden in sub-classes.");
  30634. };
  30635. _Primitive.prototype.serialize = function () {
  30636. var serializationObject = _super.prototype.serialize.call(this);
  30637. serializationObject.canBeRegenerated = this.canBeRegenerated();
  30638. return serializationObject;
  30639. };
  30640. return _Primitive;
  30641. }(Geometry));
  30642. Primitives._Primitive = _Primitive;
  30643. var Ribbon = /** @class */ (function (_super) {
  30644. __extends(Ribbon, _super);
  30645. // Members
  30646. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  30647. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30648. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30649. _this.pathArray = pathArray;
  30650. _this.closeArray = closeArray;
  30651. _this.closePath = closePath;
  30652. _this.offset = offset;
  30653. _this.side = side;
  30654. return _this;
  30655. }
  30656. Ribbon.prototype._regenerateVertexData = function () {
  30657. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  30658. };
  30659. Ribbon.prototype.copy = function (id) {
  30660. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  30661. };
  30662. return Ribbon;
  30663. }(_Primitive));
  30664. Primitives.Ribbon = Ribbon;
  30665. var Box = /** @class */ (function (_super) {
  30666. __extends(Box, _super);
  30667. // Members
  30668. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  30669. if (mesh === void 0) { mesh = null; }
  30670. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30671. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30672. _this.size = size;
  30673. _this.side = side;
  30674. return _this;
  30675. }
  30676. Box.prototype._regenerateVertexData = function () {
  30677. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  30678. };
  30679. Box.prototype.copy = function (id) {
  30680. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  30681. };
  30682. Box.prototype.serialize = function () {
  30683. var serializationObject = _super.prototype.serialize.call(this);
  30684. serializationObject.size = this.size;
  30685. return serializationObject;
  30686. };
  30687. Box.Parse = function (parsedBox, scene) {
  30688. if (scene.getGeometryByID(parsedBox.id)) {
  30689. return null; // null since geometry could be something else than a box...
  30690. }
  30691. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  30692. if (BABYLON.Tags) {
  30693. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  30694. }
  30695. scene.pushGeometry(box, true);
  30696. return box;
  30697. };
  30698. return Box;
  30699. }(_Primitive));
  30700. Primitives.Box = Box;
  30701. var Sphere = /** @class */ (function (_super) {
  30702. __extends(Sphere, _super);
  30703. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  30704. if (mesh === void 0) { mesh = null; }
  30705. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30706. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30707. _this.segments = segments;
  30708. _this.diameter = diameter;
  30709. _this.side = side;
  30710. return _this;
  30711. }
  30712. Sphere.prototype._regenerateVertexData = function () {
  30713. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  30714. };
  30715. Sphere.prototype.copy = function (id) {
  30716. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  30717. };
  30718. Sphere.prototype.serialize = function () {
  30719. var serializationObject = _super.prototype.serialize.call(this);
  30720. serializationObject.segments = this.segments;
  30721. serializationObject.diameter = this.diameter;
  30722. return serializationObject;
  30723. };
  30724. Sphere.Parse = function (parsedSphere, scene) {
  30725. if (scene.getGeometryByID(parsedSphere.id)) {
  30726. return null; // null since geometry could be something else than a sphere...
  30727. }
  30728. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  30729. if (BABYLON.Tags) {
  30730. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  30731. }
  30732. scene.pushGeometry(sphere, true);
  30733. return sphere;
  30734. };
  30735. return Sphere;
  30736. }(_Primitive));
  30737. Primitives.Sphere = Sphere;
  30738. var Disc = /** @class */ (function (_super) {
  30739. __extends(Disc, _super);
  30740. // Members
  30741. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  30742. if (mesh === void 0) { mesh = null; }
  30743. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30744. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30745. _this.radius = radius;
  30746. _this.tessellation = tessellation;
  30747. _this.side = side;
  30748. return _this;
  30749. }
  30750. Disc.prototype._regenerateVertexData = function () {
  30751. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  30752. };
  30753. Disc.prototype.copy = function (id) {
  30754. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  30755. };
  30756. return Disc;
  30757. }(_Primitive));
  30758. Primitives.Disc = Disc;
  30759. var Cylinder = /** @class */ (function (_super) {
  30760. __extends(Cylinder, _super);
  30761. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  30762. if (subdivisions === void 0) { subdivisions = 1; }
  30763. if (mesh === void 0) { mesh = null; }
  30764. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30765. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30766. _this.height = height;
  30767. _this.diameterTop = diameterTop;
  30768. _this.diameterBottom = diameterBottom;
  30769. _this.tessellation = tessellation;
  30770. _this.subdivisions = subdivisions;
  30771. _this.side = side;
  30772. return _this;
  30773. }
  30774. Cylinder.prototype._regenerateVertexData = function () {
  30775. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  30776. };
  30777. Cylinder.prototype.copy = function (id) {
  30778. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  30779. };
  30780. Cylinder.prototype.serialize = function () {
  30781. var serializationObject = _super.prototype.serialize.call(this);
  30782. serializationObject.height = this.height;
  30783. serializationObject.diameterTop = this.diameterTop;
  30784. serializationObject.diameterBottom = this.diameterBottom;
  30785. serializationObject.tessellation = this.tessellation;
  30786. return serializationObject;
  30787. };
  30788. Cylinder.Parse = function (parsedCylinder, scene) {
  30789. if (scene.getGeometryByID(parsedCylinder.id)) {
  30790. return null; // null since geometry could be something else than a cylinder...
  30791. }
  30792. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  30793. if (BABYLON.Tags) {
  30794. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  30795. }
  30796. scene.pushGeometry(cylinder, true);
  30797. return cylinder;
  30798. };
  30799. return Cylinder;
  30800. }(_Primitive));
  30801. Primitives.Cylinder = Cylinder;
  30802. var Torus = /** @class */ (function (_super) {
  30803. __extends(Torus, _super);
  30804. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  30805. if (mesh === void 0) { mesh = null; }
  30806. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30807. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30808. _this.diameter = diameter;
  30809. _this.thickness = thickness;
  30810. _this.tessellation = tessellation;
  30811. _this.side = side;
  30812. return _this;
  30813. }
  30814. Torus.prototype._regenerateVertexData = function () {
  30815. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  30816. };
  30817. Torus.prototype.copy = function (id) {
  30818. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  30819. };
  30820. Torus.prototype.serialize = function () {
  30821. var serializationObject = _super.prototype.serialize.call(this);
  30822. serializationObject.diameter = this.diameter;
  30823. serializationObject.thickness = this.thickness;
  30824. serializationObject.tessellation = this.tessellation;
  30825. return serializationObject;
  30826. };
  30827. Torus.Parse = function (parsedTorus, scene) {
  30828. if (scene.getGeometryByID(parsedTorus.id)) {
  30829. return null; // null since geometry could be something else than a torus...
  30830. }
  30831. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  30832. if (BABYLON.Tags) {
  30833. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  30834. }
  30835. scene.pushGeometry(torus, true);
  30836. return torus;
  30837. };
  30838. return Torus;
  30839. }(_Primitive));
  30840. Primitives.Torus = Torus;
  30841. var Ground = /** @class */ (function (_super) {
  30842. __extends(Ground, _super);
  30843. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  30844. if (mesh === void 0) { mesh = null; }
  30845. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30846. _this.width = width;
  30847. _this.height = height;
  30848. _this.subdivisions = subdivisions;
  30849. return _this;
  30850. }
  30851. Ground.prototype._regenerateVertexData = function () {
  30852. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  30853. };
  30854. Ground.prototype.copy = function (id) {
  30855. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  30856. };
  30857. Ground.prototype.serialize = function () {
  30858. var serializationObject = _super.prototype.serialize.call(this);
  30859. serializationObject.width = this.width;
  30860. serializationObject.height = this.height;
  30861. serializationObject.subdivisions = this.subdivisions;
  30862. return serializationObject;
  30863. };
  30864. Ground.Parse = function (parsedGround, scene) {
  30865. if (scene.getGeometryByID(parsedGround.id)) {
  30866. return null; // null since geometry could be something else than a ground...
  30867. }
  30868. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  30869. if (BABYLON.Tags) {
  30870. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  30871. }
  30872. scene.pushGeometry(ground, true);
  30873. return ground;
  30874. };
  30875. return Ground;
  30876. }(_Primitive));
  30877. Primitives.Ground = Ground;
  30878. var TiledGround = /** @class */ (function (_super) {
  30879. __extends(TiledGround, _super);
  30880. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  30881. if (mesh === void 0) { mesh = null; }
  30882. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30883. _this.xmin = xmin;
  30884. _this.zmin = zmin;
  30885. _this.xmax = xmax;
  30886. _this.zmax = zmax;
  30887. _this.subdivisions = subdivisions;
  30888. _this.precision = precision;
  30889. return _this;
  30890. }
  30891. TiledGround.prototype._regenerateVertexData = function () {
  30892. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  30893. };
  30894. TiledGround.prototype.copy = function (id) {
  30895. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  30896. };
  30897. return TiledGround;
  30898. }(_Primitive));
  30899. Primitives.TiledGround = TiledGround;
  30900. var Plane = /** @class */ (function (_super) {
  30901. __extends(Plane, _super);
  30902. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  30903. if (mesh === void 0) { mesh = null; }
  30904. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30905. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30906. _this.size = size;
  30907. _this.side = side;
  30908. return _this;
  30909. }
  30910. Plane.prototype._regenerateVertexData = function () {
  30911. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  30912. };
  30913. Plane.prototype.copy = function (id) {
  30914. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  30915. };
  30916. Plane.prototype.serialize = function () {
  30917. var serializationObject = _super.prototype.serialize.call(this);
  30918. serializationObject.size = this.size;
  30919. return serializationObject;
  30920. };
  30921. Plane.Parse = function (parsedPlane, scene) {
  30922. if (scene.getGeometryByID(parsedPlane.id)) {
  30923. return null; // null since geometry could be something else than a ground...
  30924. }
  30925. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  30926. if (BABYLON.Tags) {
  30927. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  30928. }
  30929. scene.pushGeometry(plane, true);
  30930. return plane;
  30931. };
  30932. return Plane;
  30933. }(_Primitive));
  30934. Primitives.Plane = Plane;
  30935. var TorusKnot = /** @class */ (function (_super) {
  30936. __extends(TorusKnot, _super);
  30937. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  30938. if (mesh === void 0) { mesh = null; }
  30939. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30940. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30941. _this.radius = radius;
  30942. _this.tube = tube;
  30943. _this.radialSegments = radialSegments;
  30944. _this.tubularSegments = tubularSegments;
  30945. _this.p = p;
  30946. _this.q = q;
  30947. _this.side = side;
  30948. return _this;
  30949. }
  30950. TorusKnot.prototype._regenerateVertexData = function () {
  30951. 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 });
  30952. };
  30953. TorusKnot.prototype.copy = function (id) {
  30954. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  30955. };
  30956. TorusKnot.prototype.serialize = function () {
  30957. var serializationObject = _super.prototype.serialize.call(this);
  30958. serializationObject.radius = this.radius;
  30959. serializationObject.tube = this.tube;
  30960. serializationObject.radialSegments = this.radialSegments;
  30961. serializationObject.tubularSegments = this.tubularSegments;
  30962. serializationObject.p = this.p;
  30963. serializationObject.q = this.q;
  30964. return serializationObject;
  30965. };
  30966. ;
  30967. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  30968. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  30969. return null; // null since geometry could be something else than a ground...
  30970. }
  30971. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  30972. if (BABYLON.Tags) {
  30973. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  30974. }
  30975. scene.pushGeometry(torusKnot, true);
  30976. return torusKnot;
  30977. };
  30978. return TorusKnot;
  30979. }(_Primitive));
  30980. Primitives.TorusKnot = TorusKnot;
  30981. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  30982. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  30983. })(BABYLON || (BABYLON = {}));
  30984. //# sourceMappingURL=babylon.geometry.js.map
  30985. var BABYLON;
  30986. (function (BABYLON) {
  30987. var PostProcessManager = /** @class */ (function () {
  30988. function PostProcessManager(scene) {
  30989. this._vertexBuffers = {};
  30990. this._scene = scene;
  30991. }
  30992. PostProcessManager.prototype._prepareBuffers = function () {
  30993. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  30994. return;
  30995. }
  30996. // VBO
  30997. var vertices = [];
  30998. vertices.push(1, 1);
  30999. vertices.push(-1, 1);
  31000. vertices.push(-1, -1);
  31001. vertices.push(1, -1);
  31002. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  31003. this._buildIndexBuffer();
  31004. };
  31005. PostProcessManager.prototype._buildIndexBuffer = function () {
  31006. // Indices
  31007. var indices = [];
  31008. indices.push(0);
  31009. indices.push(1);
  31010. indices.push(2);
  31011. indices.push(0);
  31012. indices.push(2);
  31013. indices.push(3);
  31014. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  31015. };
  31016. PostProcessManager.prototype._rebuild = function () {
  31017. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31018. if (!vb) {
  31019. return;
  31020. }
  31021. vb._rebuild();
  31022. this._buildIndexBuffer();
  31023. };
  31024. // Methods
  31025. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  31026. if (sourceTexture === void 0) { sourceTexture = null; }
  31027. if (postProcesses === void 0) { postProcesses = null; }
  31028. var camera = this._scene.activeCamera;
  31029. if (!camera) {
  31030. return false;
  31031. }
  31032. var postProcesses = postProcesses || camera._postProcesses;
  31033. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31034. return false;
  31035. }
  31036. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  31037. return true;
  31038. };
  31039. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  31040. if (targetTexture === void 0) { targetTexture = null; }
  31041. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  31042. if (!this._scene.activeCamera) {
  31043. return;
  31044. }
  31045. var engine = this._scene.getEngine();
  31046. for (var index = 0; index < postProcesses.length; index++) {
  31047. if (index < postProcesses.length - 1) {
  31048. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  31049. }
  31050. else {
  31051. if (targetTexture) {
  31052. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  31053. }
  31054. else {
  31055. engine.restoreDefaultFramebuffer();
  31056. }
  31057. }
  31058. var pp = postProcesses[index];
  31059. var effect = pp.apply();
  31060. if (effect) {
  31061. pp.onBeforeRenderObservable.notifyObservers(effect);
  31062. // VBOs
  31063. this._prepareBuffers();
  31064. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31065. // Draw order
  31066. engine.draw(true, 0, 6);
  31067. pp.onAfterRenderObservable.notifyObservers(effect);
  31068. }
  31069. }
  31070. // Restore depth buffer
  31071. engine.setDepthBuffer(true);
  31072. engine.setDepthWrite(true);
  31073. };
  31074. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  31075. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  31076. var camera = this._scene.activeCamera;
  31077. if (!camera) {
  31078. return;
  31079. }
  31080. postProcesses = postProcesses || camera._postProcesses;
  31081. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31082. return;
  31083. }
  31084. var engine = this._scene.getEngine();
  31085. for (var index = 0, len = postProcesses.length; index < len; index++) {
  31086. if (index < len - 1) {
  31087. postProcesses[index + 1].activate(camera, targetTexture);
  31088. }
  31089. else {
  31090. if (targetTexture) {
  31091. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  31092. }
  31093. else {
  31094. engine.restoreDefaultFramebuffer();
  31095. }
  31096. }
  31097. if (doNotPresent) {
  31098. break;
  31099. }
  31100. var pp = postProcesses[index];
  31101. var effect = pp.apply();
  31102. if (effect) {
  31103. pp.onBeforeRenderObservable.notifyObservers(effect);
  31104. // VBOs
  31105. this._prepareBuffers();
  31106. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31107. // Draw order
  31108. engine.draw(true, 0, 6);
  31109. pp.onAfterRenderObservable.notifyObservers(effect);
  31110. }
  31111. }
  31112. // Restore states
  31113. engine.setDepthBuffer(true);
  31114. engine.setDepthWrite(true);
  31115. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31116. };
  31117. PostProcessManager.prototype.dispose = function () {
  31118. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31119. if (buffer) {
  31120. buffer.dispose();
  31121. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  31122. }
  31123. if (this._indexBuffer) {
  31124. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31125. this._indexBuffer = null;
  31126. }
  31127. };
  31128. return PostProcessManager;
  31129. }());
  31130. BABYLON.PostProcessManager = PostProcessManager;
  31131. })(BABYLON || (BABYLON = {}));
  31132. //# sourceMappingURL=babylon.postProcessManager.js.map
  31133. var BABYLON;
  31134. (function (BABYLON) {
  31135. /**
  31136. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  31137. */
  31138. var PerformanceMonitor = /** @class */ (function () {
  31139. /**
  31140. * constructor
  31141. * @param frameSampleSize The number of samples required to saturate the sliding window
  31142. */
  31143. function PerformanceMonitor(frameSampleSize) {
  31144. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  31145. this._enabled = true;
  31146. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  31147. }
  31148. /**
  31149. * Samples current frame
  31150. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  31151. */
  31152. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  31153. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  31154. if (!this._enabled)
  31155. return;
  31156. if (this._lastFrameTimeMs != null) {
  31157. var dt = timeMs - this._lastFrameTimeMs;
  31158. this._rollingFrameTime.add(dt);
  31159. }
  31160. this._lastFrameTimeMs = timeMs;
  31161. };
  31162. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  31163. /**
  31164. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  31165. * @return Average frame time in milliseconds
  31166. */
  31167. get: function () {
  31168. return this._rollingFrameTime.average;
  31169. },
  31170. enumerable: true,
  31171. configurable: true
  31172. });
  31173. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  31174. /**
  31175. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  31176. * @return Frame time variance in milliseconds squared
  31177. */
  31178. get: function () {
  31179. return this._rollingFrameTime.variance;
  31180. },
  31181. enumerable: true,
  31182. configurable: true
  31183. });
  31184. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  31185. /**
  31186. * Returns the frame time of the most recent frame
  31187. * @return Frame time in milliseconds
  31188. */
  31189. get: function () {
  31190. return this._rollingFrameTime.history(0);
  31191. },
  31192. enumerable: true,
  31193. configurable: true
  31194. });
  31195. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  31196. /**
  31197. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  31198. * @return Framerate in frames per second
  31199. */
  31200. get: function () {
  31201. return 1000.0 / this._rollingFrameTime.average;
  31202. },
  31203. enumerable: true,
  31204. configurable: true
  31205. });
  31206. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  31207. /**
  31208. * Returns the average framerate in frames per second using the most recent frame time
  31209. * @return Framerate in frames per second
  31210. */
  31211. get: function () {
  31212. var history = this._rollingFrameTime.history(0);
  31213. if (history === 0) {
  31214. return 0;
  31215. }
  31216. return 1000.0 / history;
  31217. },
  31218. enumerable: true,
  31219. configurable: true
  31220. });
  31221. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  31222. /**
  31223. * Returns true if enough samples have been taken to completely fill the sliding window
  31224. * @return true if saturated
  31225. */
  31226. get: function () {
  31227. return this._rollingFrameTime.isSaturated();
  31228. },
  31229. enumerable: true,
  31230. configurable: true
  31231. });
  31232. /**
  31233. * Enables contributions to the sliding window sample set
  31234. */
  31235. PerformanceMonitor.prototype.enable = function () {
  31236. this._enabled = true;
  31237. };
  31238. /**
  31239. * Disables contributions to the sliding window sample set
  31240. * Samples will not be interpolated over the disabled period
  31241. */
  31242. PerformanceMonitor.prototype.disable = function () {
  31243. this._enabled = false;
  31244. //clear last sample to avoid interpolating over the disabled period when next enabled
  31245. this._lastFrameTimeMs = null;
  31246. this._lastChangeTimeMs = null;
  31247. };
  31248. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  31249. /**
  31250. * Returns true if sampling is enabled
  31251. * @return true if enabled
  31252. */
  31253. get: function () {
  31254. return this._enabled;
  31255. },
  31256. enumerable: true,
  31257. configurable: true
  31258. });
  31259. /**
  31260. * Resets performance monitor
  31261. */
  31262. PerformanceMonitor.prototype.reset = function () {
  31263. //clear last sample to avoid interpolating over the disabled period when next enabled
  31264. this._lastFrameTimeMs = null;
  31265. this._lastChangeTimeMs = null;
  31266. //wipe record
  31267. this._rollingFrameTime.reset();
  31268. };
  31269. return PerformanceMonitor;
  31270. }());
  31271. BABYLON.PerformanceMonitor = PerformanceMonitor;
  31272. /**
  31273. * RollingAverage
  31274. *
  31275. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  31276. */
  31277. var RollingAverage = /** @class */ (function () {
  31278. /**
  31279. * constructor
  31280. * @param length The number of samples required to saturate the sliding window
  31281. */
  31282. function RollingAverage(length) {
  31283. this._samples = new Array(length);
  31284. this.reset();
  31285. }
  31286. /**
  31287. * Adds a sample to the sample set
  31288. * @param v The sample value
  31289. */
  31290. RollingAverage.prototype.add = function (v) {
  31291. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  31292. var delta;
  31293. //we need to check if we've already wrapped round
  31294. if (this.isSaturated()) {
  31295. //remove bottom of stack from mean
  31296. var bottomValue = this._samples[this._pos];
  31297. delta = bottomValue - this.average;
  31298. this.average -= delta / (this._sampleCount - 1);
  31299. this._m2 -= delta * (bottomValue - this.average);
  31300. }
  31301. else {
  31302. this._sampleCount++;
  31303. }
  31304. //add new value to mean
  31305. delta = v - this.average;
  31306. this.average += delta / (this._sampleCount);
  31307. this._m2 += delta * (v - this.average);
  31308. //set the new variance
  31309. this.variance = this._m2 / (this._sampleCount - 1);
  31310. this._samples[this._pos] = v;
  31311. this._pos++;
  31312. this._pos %= this._samples.length; //positive wrap around
  31313. };
  31314. /**
  31315. * Returns previously added values or null if outside of history or outside the sliding window domain
  31316. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  31317. * @return Value previously recorded with add() or null if outside of range
  31318. */
  31319. RollingAverage.prototype.history = function (i) {
  31320. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  31321. return 0;
  31322. }
  31323. var i0 = this._wrapPosition(this._pos - 1.0);
  31324. return this._samples[this._wrapPosition(i0 - i)];
  31325. };
  31326. /**
  31327. * Returns true if enough samples have been taken to completely fill the sliding window
  31328. * @return true if sample-set saturated
  31329. */
  31330. RollingAverage.prototype.isSaturated = function () {
  31331. return this._sampleCount >= this._samples.length;
  31332. };
  31333. /**
  31334. * Resets the rolling average (equivalent to 0 samples taken so far)
  31335. */
  31336. RollingAverage.prototype.reset = function () {
  31337. this.average = 0;
  31338. this.variance = 0;
  31339. this._sampleCount = 0;
  31340. this._pos = 0;
  31341. this._m2 = 0;
  31342. };
  31343. /**
  31344. * Wraps a value around the sample range boundaries
  31345. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  31346. * @return Wrapped position in sample range
  31347. */
  31348. RollingAverage.prototype._wrapPosition = function (i) {
  31349. var max = this._samples.length;
  31350. return ((i % max) + max) % max;
  31351. };
  31352. return RollingAverage;
  31353. }());
  31354. BABYLON.RollingAverage = RollingAverage;
  31355. })(BABYLON || (BABYLON = {}));
  31356. //# sourceMappingURL=babylon.performanceMonitor.js.map
  31357. var BABYLON;
  31358. (function (BABYLON) {
  31359. /**
  31360. * This groups together the common properties used for image processing either in direct forward pass
  31361. * or through post processing effect depending on the use of the image processing pipeline in your scene
  31362. * or not.
  31363. */
  31364. var ImageProcessingConfiguration = /** @class */ (function () {
  31365. function ImageProcessingConfiguration() {
  31366. /**
  31367. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  31368. */
  31369. this.colorCurves = new BABYLON.ColorCurves();
  31370. this._colorCurvesEnabled = false;
  31371. this._colorGradingEnabled = false;
  31372. this._colorGradingWithGreenDepth = false;
  31373. this._colorGradingBGR = false;
  31374. this._exposure = 1.0;
  31375. this._toneMappingEnabled = false;
  31376. this._contrast = 1.0;
  31377. /**
  31378. * Vignette stretch size.
  31379. */
  31380. this.vignetteStretch = 0;
  31381. /**
  31382. * Vignette centre X Offset.
  31383. */
  31384. this.vignetteCentreX = 0;
  31385. /**
  31386. * Vignette centre Y Offset.
  31387. */
  31388. this.vignetteCentreY = 0;
  31389. /**
  31390. * Vignette weight or intensity of the vignette effect.
  31391. */
  31392. this.vignetteWeight = 1.5;
  31393. /**
  31394. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  31395. * if vignetteEnabled is set to true.
  31396. */
  31397. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  31398. /**
  31399. * Camera field of view used by the Vignette effect.
  31400. */
  31401. this.vignetteCameraFov = 0.5;
  31402. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  31403. this._vignetteEnabled = false;
  31404. this._applyByPostProcess = false;
  31405. /**
  31406. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  31407. * @type {BABYLON.Observable}
  31408. */
  31409. this.onUpdateParameters = new BABYLON.Observable();
  31410. }
  31411. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  31412. /**
  31413. * Gets wether the color curves effect is enabled.
  31414. */
  31415. get: function () {
  31416. return this._colorCurvesEnabled;
  31417. },
  31418. /**
  31419. * Sets wether the color curves effect is enabled.
  31420. */
  31421. set: function (value) {
  31422. if (this._colorCurvesEnabled === value) {
  31423. return;
  31424. }
  31425. this._colorCurvesEnabled = value;
  31426. this._updateParameters();
  31427. },
  31428. enumerable: true,
  31429. configurable: true
  31430. });
  31431. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  31432. /**
  31433. * Gets wether the color grading effect is enabled.
  31434. */
  31435. get: function () {
  31436. return this._colorGradingEnabled;
  31437. },
  31438. /**
  31439. * Sets wether the color grading effect is enabled.
  31440. */
  31441. set: function (value) {
  31442. if (this._colorGradingEnabled === value) {
  31443. return;
  31444. }
  31445. this._colorGradingEnabled = value;
  31446. this._updateParameters();
  31447. },
  31448. enumerable: true,
  31449. configurable: true
  31450. });
  31451. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  31452. /**
  31453. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  31454. */
  31455. get: function () {
  31456. return this._colorGradingWithGreenDepth;
  31457. },
  31458. /**
  31459. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  31460. */
  31461. set: function (value) {
  31462. if (this._colorGradingWithGreenDepth === value) {
  31463. return;
  31464. }
  31465. this._colorGradingWithGreenDepth = value;
  31466. this._updateParameters();
  31467. },
  31468. enumerable: true,
  31469. configurable: true
  31470. });
  31471. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  31472. /**
  31473. * Gets wether the color grading texture contains BGR values.
  31474. */
  31475. get: function () {
  31476. return this._colorGradingBGR;
  31477. },
  31478. /**
  31479. * Sets wether the color grading texture contains BGR values.
  31480. */
  31481. set: function (value) {
  31482. if (this._colorGradingBGR === value) {
  31483. return;
  31484. }
  31485. this._colorGradingBGR = value;
  31486. this._updateParameters();
  31487. },
  31488. enumerable: true,
  31489. configurable: true
  31490. });
  31491. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  31492. /**
  31493. * Gets the Exposure used in the effect.
  31494. */
  31495. get: function () {
  31496. return this._exposure;
  31497. },
  31498. /**
  31499. * Sets the Exposure used in the effect.
  31500. */
  31501. set: function (value) {
  31502. if (this._exposure === value) {
  31503. return;
  31504. }
  31505. this._exposure = value;
  31506. this._updateParameters();
  31507. },
  31508. enumerable: true,
  31509. configurable: true
  31510. });
  31511. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  31512. /**
  31513. * Gets wether the tone mapping effect is enabled.
  31514. */
  31515. get: function () {
  31516. return this._toneMappingEnabled;
  31517. },
  31518. /**
  31519. * Sets wether the tone mapping effect is enabled.
  31520. */
  31521. set: function (value) {
  31522. if (this._toneMappingEnabled === value) {
  31523. return;
  31524. }
  31525. this._toneMappingEnabled = value;
  31526. this._updateParameters();
  31527. },
  31528. enumerable: true,
  31529. configurable: true
  31530. });
  31531. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  31532. /**
  31533. * Gets the contrast used in the effect.
  31534. */
  31535. get: function () {
  31536. return this._contrast;
  31537. },
  31538. /**
  31539. * Sets the contrast used in the effect.
  31540. */
  31541. set: function (value) {
  31542. if (this._contrast === value) {
  31543. return;
  31544. }
  31545. this._contrast = value;
  31546. this._updateParameters();
  31547. },
  31548. enumerable: true,
  31549. configurable: true
  31550. });
  31551. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  31552. /**
  31553. * Gets the vignette blend mode allowing different kind of effect.
  31554. */
  31555. get: function () {
  31556. return this._vignetteBlendMode;
  31557. },
  31558. /**
  31559. * Sets the vignette blend mode allowing different kind of effect.
  31560. */
  31561. set: function (value) {
  31562. if (this._vignetteBlendMode === value) {
  31563. return;
  31564. }
  31565. this._vignetteBlendMode = value;
  31566. this._updateParameters();
  31567. },
  31568. enumerable: true,
  31569. configurable: true
  31570. });
  31571. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  31572. /**
  31573. * Gets wether the vignette effect is enabled.
  31574. */
  31575. get: function () {
  31576. return this._vignetteEnabled;
  31577. },
  31578. /**
  31579. * Sets wether the vignette effect is enabled.
  31580. */
  31581. set: function (value) {
  31582. if (this._vignetteEnabled === value) {
  31583. return;
  31584. }
  31585. this._vignetteEnabled = value;
  31586. this._updateParameters();
  31587. },
  31588. enumerable: true,
  31589. configurable: true
  31590. });
  31591. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  31592. /**
  31593. * Gets wether the image processing is applied through a post process or not.
  31594. */
  31595. get: function () {
  31596. return this._applyByPostProcess;
  31597. },
  31598. /**
  31599. * Sets wether the image processing is applied through a post process or not.
  31600. */
  31601. set: function (value) {
  31602. if (this._applyByPostProcess === value) {
  31603. return;
  31604. }
  31605. this._applyByPostProcess = value;
  31606. this._updateParameters();
  31607. },
  31608. enumerable: true,
  31609. configurable: true
  31610. });
  31611. /**
  31612. * Method called each time the image processing information changes requires to recompile the effect.
  31613. */
  31614. ImageProcessingConfiguration.prototype._updateParameters = function () {
  31615. this.onUpdateParameters.notifyObservers(this);
  31616. };
  31617. ImageProcessingConfiguration.prototype.getClassName = function () {
  31618. return "ImageProcessingConfiguration";
  31619. };
  31620. /**
  31621. * Prepare the list of uniforms associated with the Image Processing effects.
  31622. * @param uniformsList The list of uniforms used in the effect
  31623. * @param defines the list of defines currently in use
  31624. */
  31625. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  31626. if (defines.EXPOSURE) {
  31627. uniforms.push("exposureLinear");
  31628. }
  31629. if (defines.CONTRAST) {
  31630. uniforms.push("contrast");
  31631. }
  31632. if (defines.COLORGRADING) {
  31633. uniforms.push("colorTransformSettings");
  31634. }
  31635. if (defines.VIGNETTE) {
  31636. uniforms.push("vInverseScreenSize");
  31637. uniforms.push("vignetteSettings1");
  31638. uniforms.push("vignetteSettings2");
  31639. }
  31640. if (defines.COLORCURVES) {
  31641. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  31642. }
  31643. };
  31644. /**
  31645. * Prepare the list of samplers associated with the Image Processing effects.
  31646. * @param uniformsList The list of uniforms used in the effect
  31647. * @param defines the list of defines currently in use
  31648. */
  31649. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  31650. if (defines.COLORGRADING) {
  31651. samplersList.push("txColorTransform");
  31652. }
  31653. };
  31654. /**
  31655. * Prepare the list of defines associated to the shader.
  31656. * @param defines the list of defines to complete
  31657. */
  31658. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  31659. if (forPostProcess === void 0) { forPostProcess = false; }
  31660. if (forPostProcess !== this.applyByPostProcess) {
  31661. defines.VIGNETTE = false;
  31662. defines.TONEMAPPING = false;
  31663. defines.CONTRAST = false;
  31664. defines.EXPOSURE = false;
  31665. defines.COLORCURVES = false;
  31666. defines.COLORGRADING = false;
  31667. defines.IMAGEPROCESSING = false;
  31668. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  31669. return;
  31670. }
  31671. defines.VIGNETTE = this.vignetteEnabled;
  31672. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  31673. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  31674. defines.TONEMAPPING = this.toneMappingEnabled;
  31675. defines.CONTRAST = (this.contrast !== 1.0);
  31676. defines.EXPOSURE = (this.exposure !== 1.0);
  31677. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  31678. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  31679. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  31680. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  31681. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  31682. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  31683. };
  31684. /**
  31685. * Returns true if all the image processing information are ready.
  31686. */
  31687. ImageProcessingConfiguration.prototype.isReady = function () {
  31688. // Color Grading texure can not be none blocking.
  31689. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  31690. };
  31691. /**
  31692. * Binds the image processing to the shader.
  31693. * @param effect The effect to bind to
  31694. */
  31695. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  31696. if (aspectRatio === void 0) { aspectRatio = 1; }
  31697. // Color Curves
  31698. if (this._colorCurvesEnabled) {
  31699. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  31700. }
  31701. // Vignette
  31702. if (this._vignetteEnabled) {
  31703. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  31704. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  31705. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  31706. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  31707. var vignetteScaleX = vignetteScaleY * aspectRatio;
  31708. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  31709. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  31710. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  31711. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  31712. var vignettePower = -2.0 * this.vignetteWeight;
  31713. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  31714. }
  31715. // Exposure
  31716. effect.setFloat("exposureLinear", this.exposure);
  31717. // Contrast
  31718. effect.setFloat("contrast", this.contrast);
  31719. // Color transform settings
  31720. if (this.colorGradingTexture) {
  31721. effect.setTexture("txColorTransform", this.colorGradingTexture);
  31722. var textureSize = this.colorGradingTexture.getSize().height;
  31723. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  31724. 0.5 / textureSize, // textureOffset
  31725. textureSize, // textureSize
  31726. this.colorGradingTexture.level // weight
  31727. );
  31728. }
  31729. };
  31730. /**
  31731. * Clones the current image processing instance.
  31732. * @return The cloned image processing
  31733. */
  31734. ImageProcessingConfiguration.prototype.clone = function () {
  31735. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  31736. };
  31737. /**
  31738. * Serializes the current image processing instance to a json representation.
  31739. * @return a JSON representation
  31740. */
  31741. ImageProcessingConfiguration.prototype.serialize = function () {
  31742. return BABYLON.SerializationHelper.Serialize(this);
  31743. };
  31744. /**
  31745. * Parses the image processing from a json representation.
  31746. * @param source the JSON source to parse
  31747. * @return The parsed image processing
  31748. */
  31749. ImageProcessingConfiguration.Parse = function (source) {
  31750. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  31751. };
  31752. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  31753. /**
  31754. * Used to apply the vignette as a mix with the pixel color.
  31755. */
  31756. get: function () {
  31757. return this._VIGNETTEMODE_MULTIPLY;
  31758. },
  31759. enumerable: true,
  31760. configurable: true
  31761. });
  31762. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  31763. /**
  31764. * Used to apply the vignette as a replacement of the pixel color.
  31765. */
  31766. get: function () {
  31767. return this._VIGNETTEMODE_OPAQUE;
  31768. },
  31769. enumerable: true,
  31770. configurable: true
  31771. });
  31772. // Static constants associated to the image processing.
  31773. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  31774. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  31775. __decorate([
  31776. BABYLON.serializeAsColorCurves()
  31777. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  31778. __decorate([
  31779. BABYLON.serialize()
  31780. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  31781. __decorate([
  31782. BABYLON.serializeAsTexture()
  31783. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  31784. __decorate([
  31785. BABYLON.serialize()
  31786. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  31787. __decorate([
  31788. BABYLON.serialize()
  31789. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  31790. __decorate([
  31791. BABYLON.serialize()
  31792. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  31793. __decorate([
  31794. BABYLON.serialize()
  31795. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  31796. __decorate([
  31797. BABYLON.serialize()
  31798. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  31799. __decorate([
  31800. BABYLON.serialize()
  31801. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  31802. __decorate([
  31803. BABYLON.serialize()
  31804. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  31805. __decorate([
  31806. BABYLON.serialize()
  31807. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  31808. __decorate([
  31809. BABYLON.serialize()
  31810. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  31811. __decorate([
  31812. BABYLON.serialize()
  31813. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  31814. __decorate([
  31815. BABYLON.serializeAsColor4()
  31816. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  31817. __decorate([
  31818. BABYLON.serialize()
  31819. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  31820. __decorate([
  31821. BABYLON.serialize()
  31822. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  31823. __decorate([
  31824. BABYLON.serialize()
  31825. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  31826. __decorate([
  31827. BABYLON.serialize()
  31828. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  31829. return ImageProcessingConfiguration;
  31830. }());
  31831. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  31832. })(BABYLON || (BABYLON = {}));
  31833. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  31834. var BABYLON;
  31835. (function (BABYLON) {
  31836. /**
  31837. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  31838. * It can help converting any input color in a desired output one. This can then be used to create effects
  31839. * from sepia, black and white to sixties or futuristic rendering...
  31840. *
  31841. * The only supported format is currently 3dl.
  31842. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  31843. */
  31844. var ColorGradingTexture = /** @class */ (function (_super) {
  31845. __extends(ColorGradingTexture, _super);
  31846. /**
  31847. * Instantiates a ColorGradingTexture from the following parameters.
  31848. *
  31849. * @param url The location of the color gradind data (currently only supporting 3dl)
  31850. * @param scene The scene the texture will be used in
  31851. */
  31852. function ColorGradingTexture(url, scene) {
  31853. var _this = _super.call(this, scene) || this;
  31854. if (!url) {
  31855. return _this;
  31856. }
  31857. _this._textureMatrix = BABYLON.Matrix.Identity();
  31858. _this.name = url;
  31859. _this.url = url;
  31860. _this.hasAlpha = false;
  31861. _this.isCube = false;
  31862. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31863. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31864. _this.anisotropicFilteringLevel = 1;
  31865. _this._texture = _this._getFromCache(url, true);
  31866. if (!_this._texture) {
  31867. if (!scene.useDelayedTextureLoading) {
  31868. _this.loadTexture();
  31869. }
  31870. else {
  31871. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31872. }
  31873. }
  31874. return _this;
  31875. }
  31876. /**
  31877. * Returns the texture matrix used in most of the material.
  31878. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  31879. */
  31880. ColorGradingTexture.prototype.getTextureMatrix = function () {
  31881. return this._textureMatrix;
  31882. };
  31883. /**
  31884. * Occurs when the file being loaded is a .3dl LUT file.
  31885. */
  31886. ColorGradingTexture.prototype.load3dlTexture = function () {
  31887. var _this = this;
  31888. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  31889. this._texture = texture;
  31890. var callback = function (text) {
  31891. var data;
  31892. var tempData;
  31893. var line;
  31894. var lines = text.split('\n');
  31895. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  31896. var maxColor = 0;
  31897. for (var i = 0; i < lines.length; i++) {
  31898. line = lines[i];
  31899. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  31900. continue;
  31901. if (line.indexOf('#') === 0)
  31902. continue;
  31903. var words = line.split(" ");
  31904. if (size === 0) {
  31905. // Number of space + one
  31906. size = words.length;
  31907. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  31908. tempData = new Float32Array(size * size * size * 4);
  31909. continue;
  31910. }
  31911. if (size != 0) {
  31912. var r = Math.max(parseInt(words[0]), 0);
  31913. var g = Math.max(parseInt(words[1]), 0);
  31914. var b = Math.max(parseInt(words[2]), 0);
  31915. maxColor = Math.max(r, maxColor);
  31916. maxColor = Math.max(g, maxColor);
  31917. maxColor = Math.max(b, maxColor);
  31918. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  31919. tempData[pixelStorageIndex + 0] = r;
  31920. tempData[pixelStorageIndex + 1] = g;
  31921. tempData[pixelStorageIndex + 2] = b;
  31922. pixelIndexSlice++;
  31923. if (pixelIndexSlice % size == 0) {
  31924. pixelIndexH++;
  31925. pixelIndexSlice = 0;
  31926. if (pixelIndexH % size == 0) {
  31927. pixelIndexW++;
  31928. pixelIndexH = 0;
  31929. }
  31930. }
  31931. }
  31932. }
  31933. for (var i = 0; i < tempData.length; i++) {
  31934. if (i > 0 && (i + 1) % 4 === 0) {
  31935. data[i] = 255;
  31936. }
  31937. else {
  31938. var value = tempData[i];
  31939. data[i] = (value / maxColor * 255);
  31940. }
  31941. }
  31942. texture.updateSize(size * size, size);
  31943. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  31944. };
  31945. BABYLON.Tools.LoadFile(this.url, callback);
  31946. return this._texture;
  31947. };
  31948. /**
  31949. * Starts the loading process of the texture.
  31950. */
  31951. ColorGradingTexture.prototype.loadTexture = function () {
  31952. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  31953. this.load3dlTexture();
  31954. }
  31955. };
  31956. /**
  31957. * Clones the color gradind texture.
  31958. */
  31959. ColorGradingTexture.prototype.clone = function () {
  31960. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  31961. // Base texture
  31962. newTexture.level = this.level;
  31963. return newTexture;
  31964. };
  31965. /**
  31966. * Called during delayed load for textures.
  31967. */
  31968. ColorGradingTexture.prototype.delayLoad = function () {
  31969. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31970. return;
  31971. }
  31972. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31973. this._texture = this._getFromCache(this.url, true);
  31974. if (!this._texture) {
  31975. this.loadTexture();
  31976. }
  31977. };
  31978. /**
  31979. * Parses a color grading texture serialized by Babylon.
  31980. * @param parsedTexture The texture information being parsedTexture
  31981. * @param scene The scene to load the texture in
  31982. * @param rootUrl The root url of the data assets to load
  31983. * @return A color gradind texture
  31984. */
  31985. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  31986. var texture = null;
  31987. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  31988. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  31989. texture.name = parsedTexture.name;
  31990. texture.level = parsedTexture.level;
  31991. }
  31992. return texture;
  31993. };
  31994. /**
  31995. * Serializes the LUT texture to json format.
  31996. */
  31997. ColorGradingTexture.prototype.serialize = function () {
  31998. if (!this.name) {
  31999. return null;
  32000. }
  32001. var serializationObject = {};
  32002. serializationObject.name = this.name;
  32003. serializationObject.level = this.level;
  32004. serializationObject.customType = "BABYLON.ColorGradingTexture";
  32005. return serializationObject;
  32006. };
  32007. /**
  32008. * Empty line regex stored for GC.
  32009. */
  32010. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  32011. return ColorGradingTexture;
  32012. }(BABYLON.BaseTexture));
  32013. BABYLON.ColorGradingTexture = ColorGradingTexture;
  32014. })(BABYLON || (BABYLON = {}));
  32015. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  32016. var BABYLON;
  32017. (function (BABYLON) {
  32018. /**
  32019. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  32020. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  32021. * 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;
  32022. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  32023. */
  32024. var ColorCurves = /** @class */ (function () {
  32025. function ColorCurves() {
  32026. this._dirty = true;
  32027. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  32028. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  32029. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  32030. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  32031. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  32032. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  32033. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  32034. this._globalHue = 30;
  32035. this._globalDensity = 0;
  32036. this._globalSaturation = 0;
  32037. this._globalExposure = 0;
  32038. this._highlightsHue = 30;
  32039. this._highlightsDensity = 0;
  32040. this._highlightsSaturation = 0;
  32041. this._highlightsExposure = 0;
  32042. this._midtonesHue = 30;
  32043. this._midtonesDensity = 0;
  32044. this._midtonesSaturation = 0;
  32045. this._midtonesExposure = 0;
  32046. this._shadowsHue = 30;
  32047. this._shadowsDensity = 0;
  32048. this._shadowsSaturation = 0;
  32049. this._shadowsExposure = 0;
  32050. }
  32051. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  32052. /**
  32053. * Gets the global Hue value.
  32054. * 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).
  32055. */
  32056. get: function () {
  32057. return this._globalHue;
  32058. },
  32059. /**
  32060. * Sets the global Hue value.
  32061. * 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).
  32062. */
  32063. set: function (value) {
  32064. this._globalHue = value;
  32065. this._dirty = true;
  32066. },
  32067. enumerable: true,
  32068. configurable: true
  32069. });
  32070. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  32071. /**
  32072. * Gets the global Density value.
  32073. * 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.
  32074. * Values less than zero provide a filter of opposite hue.
  32075. */
  32076. get: function () {
  32077. return this._globalDensity;
  32078. },
  32079. /**
  32080. * Sets the global Density value.
  32081. * 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.
  32082. * Values less than zero provide a filter of opposite hue.
  32083. */
  32084. set: function (value) {
  32085. this._globalDensity = value;
  32086. this._dirty = true;
  32087. },
  32088. enumerable: true,
  32089. configurable: true
  32090. });
  32091. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  32092. /**
  32093. * Gets the global Saturation value.
  32094. * 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.
  32095. */
  32096. get: function () {
  32097. return this._globalSaturation;
  32098. },
  32099. /**
  32100. * Sets the global Saturation value.
  32101. * 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.
  32102. */
  32103. set: function (value) {
  32104. this._globalSaturation = value;
  32105. this._dirty = true;
  32106. },
  32107. enumerable: true,
  32108. configurable: true
  32109. });
  32110. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  32111. /**
  32112. * Gets the highlights Hue value.
  32113. * 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).
  32114. */
  32115. get: function () {
  32116. return this._highlightsHue;
  32117. },
  32118. /**
  32119. * Sets the highlights Hue value.
  32120. * 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).
  32121. */
  32122. set: function (value) {
  32123. this._highlightsHue = value;
  32124. this._dirty = true;
  32125. },
  32126. enumerable: true,
  32127. configurable: true
  32128. });
  32129. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  32130. /**
  32131. * Gets the highlights Density value.
  32132. * 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.
  32133. * Values less than zero provide a filter of opposite hue.
  32134. */
  32135. get: function () {
  32136. return this._highlightsDensity;
  32137. },
  32138. /**
  32139. * Sets the highlights Density value.
  32140. * 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.
  32141. * Values less than zero provide a filter of opposite hue.
  32142. */
  32143. set: function (value) {
  32144. this._highlightsDensity = value;
  32145. this._dirty = true;
  32146. },
  32147. enumerable: true,
  32148. configurable: true
  32149. });
  32150. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  32151. /**
  32152. * Gets the highlights Saturation value.
  32153. * 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.
  32154. */
  32155. get: function () {
  32156. return this._highlightsSaturation;
  32157. },
  32158. /**
  32159. * Sets the highlights Saturation value.
  32160. * 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.
  32161. */
  32162. set: function (value) {
  32163. this._highlightsSaturation = value;
  32164. this._dirty = true;
  32165. },
  32166. enumerable: true,
  32167. configurable: true
  32168. });
  32169. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  32170. /**
  32171. * Gets the highlights Exposure value.
  32172. * 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.
  32173. */
  32174. get: function () {
  32175. return this._highlightsExposure;
  32176. },
  32177. /**
  32178. * Sets the highlights Exposure value.
  32179. * 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.
  32180. */
  32181. set: function (value) {
  32182. this._highlightsExposure = value;
  32183. this._dirty = true;
  32184. },
  32185. enumerable: true,
  32186. configurable: true
  32187. });
  32188. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  32189. /**
  32190. * Gets the midtones Hue value.
  32191. * 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).
  32192. */
  32193. get: function () {
  32194. return this._midtonesHue;
  32195. },
  32196. /**
  32197. * Sets the midtones Hue value.
  32198. * 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).
  32199. */
  32200. set: function (value) {
  32201. this._midtonesHue = value;
  32202. this._dirty = true;
  32203. },
  32204. enumerable: true,
  32205. configurable: true
  32206. });
  32207. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  32208. /**
  32209. * Gets the midtones Density value.
  32210. * 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.
  32211. * Values less than zero provide a filter of opposite hue.
  32212. */
  32213. get: function () {
  32214. return this._midtonesDensity;
  32215. },
  32216. /**
  32217. * Sets the midtones Density value.
  32218. * 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.
  32219. * Values less than zero provide a filter of opposite hue.
  32220. */
  32221. set: function (value) {
  32222. this._midtonesDensity = value;
  32223. this._dirty = true;
  32224. },
  32225. enumerable: true,
  32226. configurable: true
  32227. });
  32228. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  32229. /**
  32230. * Gets the midtones Saturation value.
  32231. * 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.
  32232. */
  32233. get: function () {
  32234. return this._midtonesSaturation;
  32235. },
  32236. /**
  32237. * Sets the midtones Saturation value.
  32238. * 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.
  32239. */
  32240. set: function (value) {
  32241. this._midtonesSaturation = value;
  32242. this._dirty = true;
  32243. },
  32244. enumerable: true,
  32245. configurable: true
  32246. });
  32247. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  32248. /**
  32249. * Gets the midtones Exposure value.
  32250. * 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.
  32251. */
  32252. get: function () {
  32253. return this._midtonesExposure;
  32254. },
  32255. /**
  32256. * Sets the midtones Exposure value.
  32257. * 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.
  32258. */
  32259. set: function (value) {
  32260. this._midtonesExposure = value;
  32261. this._dirty = true;
  32262. },
  32263. enumerable: true,
  32264. configurable: true
  32265. });
  32266. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  32267. /**
  32268. * Gets the shadows Hue value.
  32269. * 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).
  32270. */
  32271. get: function () {
  32272. return this._shadowsHue;
  32273. },
  32274. /**
  32275. * Sets the shadows Hue value.
  32276. * 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).
  32277. */
  32278. set: function (value) {
  32279. this._shadowsHue = value;
  32280. this._dirty = true;
  32281. },
  32282. enumerable: true,
  32283. configurable: true
  32284. });
  32285. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  32286. /**
  32287. * Gets the shadows Density value.
  32288. * 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.
  32289. * Values less than zero provide a filter of opposite hue.
  32290. */
  32291. get: function () {
  32292. return this._shadowsDensity;
  32293. },
  32294. /**
  32295. * Sets the shadows Density value.
  32296. * 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.
  32297. * Values less than zero provide a filter of opposite hue.
  32298. */
  32299. set: function (value) {
  32300. this._shadowsDensity = value;
  32301. this._dirty = true;
  32302. },
  32303. enumerable: true,
  32304. configurable: true
  32305. });
  32306. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  32307. /**
  32308. * Gets the shadows Saturation value.
  32309. * 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.
  32310. */
  32311. get: function () {
  32312. return this._shadowsSaturation;
  32313. },
  32314. /**
  32315. * Sets the shadows Saturation value.
  32316. * 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.
  32317. */
  32318. set: function (value) {
  32319. this._shadowsSaturation = value;
  32320. this._dirty = true;
  32321. },
  32322. enumerable: true,
  32323. configurable: true
  32324. });
  32325. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  32326. /**
  32327. * Gets the shadows Exposure value.
  32328. * 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.
  32329. */
  32330. get: function () {
  32331. return this._shadowsExposure;
  32332. },
  32333. /**
  32334. * Sets the shadows Exposure value.
  32335. * 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.
  32336. */
  32337. set: function (value) {
  32338. this._shadowsExposure = value;
  32339. this._dirty = true;
  32340. },
  32341. enumerable: true,
  32342. configurable: true
  32343. });
  32344. ColorCurves.prototype.getClassName = function () {
  32345. return "ColorCurves";
  32346. };
  32347. /**
  32348. * Binds the color curves to the shader.
  32349. * @param colorCurves The color curve to bind
  32350. * @param effect The effect to bind to
  32351. */
  32352. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  32353. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  32354. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  32355. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  32356. if (colorCurves._dirty) {
  32357. colorCurves._dirty = false;
  32358. // Fill in global info.
  32359. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  32360. // Compute highlights info.
  32361. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  32362. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  32363. // Compute midtones info.
  32364. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  32365. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  32366. // Compute shadows info.
  32367. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  32368. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  32369. // Compute deltas (neutral is midtones).
  32370. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  32371. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  32372. }
  32373. if (effect) {
  32374. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  32375. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  32376. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  32377. }
  32378. };
  32379. /**
  32380. * Prepare the list of uniforms associated with the ColorCurves effects.
  32381. * @param uniformsList The list of uniforms used in the effect
  32382. */
  32383. ColorCurves.PrepareUniforms = function (uniformsList) {
  32384. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  32385. };
  32386. /**
  32387. * Returns color grading data based on a hue, density, saturation and exposure value.
  32388. * @param filterHue The hue of the color filter.
  32389. * @param filterDensity The density of the color filter.
  32390. * @param saturation The saturation.
  32391. * @param exposure The exposure.
  32392. * @param result The result data container.
  32393. */
  32394. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  32395. if (hue == null) {
  32396. return;
  32397. }
  32398. hue = ColorCurves.clamp(hue, 0, 360);
  32399. density = ColorCurves.clamp(density, -100, 100);
  32400. saturation = ColorCurves.clamp(saturation, -100, 100);
  32401. exposure = ColorCurves.clamp(exposure, -100, 100);
  32402. // Remap the slider/config filter density with non-linear mapping and also scale by half
  32403. // so that the maximum filter density is only 50% control. This provides fine control
  32404. // for small values and reasonable range.
  32405. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  32406. density *= 0.5;
  32407. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  32408. if (density < 0) {
  32409. density *= -1;
  32410. hue = (hue + 180) % 360;
  32411. }
  32412. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  32413. result.scaleToRef(2, result);
  32414. result.a = 1 + 0.01 * saturation;
  32415. };
  32416. /**
  32417. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  32418. * @param value The input slider value in range [-100,100].
  32419. * @returns Adjusted value.
  32420. */
  32421. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  32422. value /= 100;
  32423. var x = Math.abs(value);
  32424. x = Math.pow(x, 2);
  32425. if (value < 0) {
  32426. x *= -1;
  32427. }
  32428. x *= 100;
  32429. return x;
  32430. };
  32431. /**
  32432. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  32433. * @param hue The hue (H) input.
  32434. * @param saturation The saturation (S) input.
  32435. * @param brightness The brightness (B) input.
  32436. * @result An RGBA color represented as Vector4.
  32437. */
  32438. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  32439. var h = ColorCurves.clamp(hue, 0, 360);
  32440. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  32441. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  32442. if (s === 0) {
  32443. result.r = v;
  32444. result.g = v;
  32445. result.b = v;
  32446. }
  32447. else {
  32448. // sector 0 to 5
  32449. h /= 60;
  32450. var i = Math.floor(h);
  32451. // fractional part of h
  32452. var f = h - i;
  32453. var p = v * (1 - s);
  32454. var q = v * (1 - s * f);
  32455. var t = v * (1 - s * (1 - f));
  32456. switch (i) {
  32457. case 0:
  32458. result.r = v;
  32459. result.g = t;
  32460. result.b = p;
  32461. break;
  32462. case 1:
  32463. result.r = q;
  32464. result.g = v;
  32465. result.b = p;
  32466. break;
  32467. case 2:
  32468. result.r = p;
  32469. result.g = v;
  32470. result.b = t;
  32471. break;
  32472. case 3:
  32473. result.r = p;
  32474. result.g = q;
  32475. result.b = v;
  32476. break;
  32477. case 4:
  32478. result.r = t;
  32479. result.g = p;
  32480. result.b = v;
  32481. break;
  32482. default:// case 5:
  32483. result.r = v;
  32484. result.g = p;
  32485. result.b = q;
  32486. break;
  32487. }
  32488. }
  32489. result.a = 1;
  32490. };
  32491. /**
  32492. * Returns a value clamped between min and max
  32493. * @param value The value to clamp
  32494. * @param min The minimum of value
  32495. * @param max The maximum of value
  32496. * @returns The clamped value.
  32497. */
  32498. ColorCurves.clamp = function (value, min, max) {
  32499. return Math.min(Math.max(value, min), max);
  32500. };
  32501. /**
  32502. * Clones the current color curve instance.
  32503. * @return The cloned curves
  32504. */
  32505. ColorCurves.prototype.clone = function () {
  32506. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  32507. };
  32508. /**
  32509. * Serializes the current color curve instance to a json representation.
  32510. * @return a JSON representation
  32511. */
  32512. ColorCurves.prototype.serialize = function () {
  32513. return BABYLON.SerializationHelper.Serialize(this);
  32514. };
  32515. /**
  32516. * Parses the color curve from a json representation.
  32517. * @param source the JSON source to parse
  32518. * @return The parsed curves
  32519. */
  32520. ColorCurves.Parse = function (source) {
  32521. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  32522. };
  32523. __decorate([
  32524. BABYLON.serialize()
  32525. ], ColorCurves.prototype, "_globalHue", void 0);
  32526. __decorate([
  32527. BABYLON.serialize()
  32528. ], ColorCurves.prototype, "_globalDensity", void 0);
  32529. __decorate([
  32530. BABYLON.serialize()
  32531. ], ColorCurves.prototype, "_globalSaturation", void 0);
  32532. __decorate([
  32533. BABYLON.serialize()
  32534. ], ColorCurves.prototype, "_globalExposure", void 0);
  32535. __decorate([
  32536. BABYLON.serialize()
  32537. ], ColorCurves.prototype, "_highlightsHue", void 0);
  32538. __decorate([
  32539. BABYLON.serialize()
  32540. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  32541. __decorate([
  32542. BABYLON.serialize()
  32543. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  32544. __decorate([
  32545. BABYLON.serialize()
  32546. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  32547. __decorate([
  32548. BABYLON.serialize()
  32549. ], ColorCurves.prototype, "_midtonesHue", void 0);
  32550. __decorate([
  32551. BABYLON.serialize()
  32552. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  32553. __decorate([
  32554. BABYLON.serialize()
  32555. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  32556. __decorate([
  32557. BABYLON.serialize()
  32558. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  32559. return ColorCurves;
  32560. }());
  32561. BABYLON.ColorCurves = ColorCurves;
  32562. })(BABYLON || (BABYLON = {}));
  32563. //# sourceMappingURL=babylon.colorCurves.js.map
  32564. var BABYLON;
  32565. (function (BABYLON) {
  32566. var StandardMaterialDefines = /** @class */ (function (_super) {
  32567. __extends(StandardMaterialDefines, _super);
  32568. function StandardMaterialDefines() {
  32569. var _this = _super.call(this) || this;
  32570. _this.MAINUV1 = false;
  32571. _this.MAINUV2 = false;
  32572. _this.DIFFUSE = false;
  32573. _this.DIFFUSEDIRECTUV = 0;
  32574. _this.AMBIENT = false;
  32575. _this.AMBIENTDIRECTUV = 0;
  32576. _this.OPACITY = false;
  32577. _this.OPACITYDIRECTUV = 0;
  32578. _this.OPACITYRGB = false;
  32579. _this.REFLECTION = false;
  32580. _this.EMISSIVE = false;
  32581. _this.EMISSIVEDIRECTUV = 0;
  32582. _this.SPECULAR = false;
  32583. _this.SPECULARDIRECTUV = 0;
  32584. _this.BUMP = false;
  32585. _this.BUMPDIRECTUV = 0;
  32586. _this.PARALLAX = false;
  32587. _this.PARALLAXOCCLUSION = false;
  32588. _this.SPECULAROVERALPHA = false;
  32589. _this.CLIPPLANE = false;
  32590. _this.ALPHATEST = false;
  32591. _this.DEPTHPREPASS = false;
  32592. _this.ALPHAFROMDIFFUSE = false;
  32593. _this.POINTSIZE = false;
  32594. _this.FOG = false;
  32595. _this.SPECULARTERM = false;
  32596. _this.DIFFUSEFRESNEL = false;
  32597. _this.OPACITYFRESNEL = false;
  32598. _this.REFLECTIONFRESNEL = false;
  32599. _this.REFRACTIONFRESNEL = false;
  32600. _this.EMISSIVEFRESNEL = false;
  32601. _this.FRESNEL = false;
  32602. _this.NORMAL = false;
  32603. _this.UV1 = false;
  32604. _this.UV2 = false;
  32605. _this.VERTEXCOLOR = false;
  32606. _this.VERTEXALPHA = false;
  32607. _this.NUM_BONE_INFLUENCERS = 0;
  32608. _this.BonesPerMesh = 0;
  32609. _this.INSTANCES = false;
  32610. _this.GLOSSINESS = false;
  32611. _this.ROUGHNESS = false;
  32612. _this.EMISSIVEASILLUMINATION = false;
  32613. _this.LINKEMISSIVEWITHDIFFUSE = false;
  32614. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  32615. _this.LIGHTMAP = false;
  32616. _this.LIGHTMAPDIRECTUV = 0;
  32617. _this.USELIGHTMAPASSHADOWMAP = false;
  32618. _this.REFLECTIONMAP_3D = false;
  32619. _this.REFLECTIONMAP_SPHERICAL = false;
  32620. _this.REFLECTIONMAP_PLANAR = false;
  32621. _this.REFLECTIONMAP_CUBIC = false;
  32622. _this.REFLECTIONMAP_PROJECTION = false;
  32623. _this.REFLECTIONMAP_SKYBOX = false;
  32624. _this.REFLECTIONMAP_EXPLICIT = false;
  32625. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  32626. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  32627. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  32628. _this.INVERTCUBICMAP = false;
  32629. _this.LOGARITHMICDEPTH = false;
  32630. _this.REFRACTION = false;
  32631. _this.REFRACTIONMAP_3D = false;
  32632. _this.REFLECTIONOVERALPHA = false;
  32633. _this.TWOSIDEDLIGHTING = false;
  32634. _this.SHADOWFLOAT = false;
  32635. _this.MORPHTARGETS = false;
  32636. _this.MORPHTARGETS_NORMAL = false;
  32637. _this.MORPHTARGETS_TANGENT = false;
  32638. _this.NUM_MORPH_INFLUENCERS = 0;
  32639. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  32640. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  32641. _this.IMAGEPROCESSING = false;
  32642. _this.VIGNETTE = false;
  32643. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  32644. _this.VIGNETTEBLENDMODEOPAQUE = false;
  32645. _this.TONEMAPPING = false;
  32646. _this.CONTRAST = false;
  32647. _this.COLORCURVES = false;
  32648. _this.COLORGRADING = false;
  32649. _this.SAMPLER3DGREENDEPTH = false;
  32650. _this.SAMPLER3DBGRMAP = false;
  32651. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  32652. _this.EXPOSURE = false;
  32653. _this.rebuild();
  32654. return _this;
  32655. }
  32656. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  32657. var modes = [
  32658. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  32659. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  32660. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  32661. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  32662. ];
  32663. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  32664. var mode = modes_1[_i];
  32665. this[mode] = (mode === modeToEnable);
  32666. }
  32667. };
  32668. return StandardMaterialDefines;
  32669. }(BABYLON.MaterialDefines));
  32670. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  32671. var StandardMaterial = /** @class */ (function (_super) {
  32672. __extends(StandardMaterial, _super);
  32673. function StandardMaterial(name, scene) {
  32674. var _this = _super.call(this, name, scene) || this;
  32675. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  32676. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  32677. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  32678. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  32679. _this.specularPower = 64;
  32680. _this._useAlphaFromDiffuseTexture = false;
  32681. _this._useEmissiveAsIllumination = false;
  32682. _this._linkEmissiveWithDiffuse = false;
  32683. _this._useSpecularOverAlpha = false;
  32684. _this._useReflectionOverAlpha = false;
  32685. _this._disableLighting = false;
  32686. _this._useParallax = false;
  32687. _this._useParallaxOcclusion = false;
  32688. _this.parallaxScaleBias = 0.05;
  32689. _this._roughness = 0;
  32690. _this.indexOfRefraction = 0.98;
  32691. _this.invertRefractionY = true;
  32692. _this._useLightmapAsShadowmap = false;
  32693. _this._useReflectionFresnelFromSpecular = false;
  32694. _this._useGlossinessFromSpecularMapAlpha = false;
  32695. _this._maxSimultaneousLights = 4;
  32696. /**
  32697. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  32698. */
  32699. _this._invertNormalMapX = false;
  32700. /**
  32701. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  32702. */
  32703. _this._invertNormalMapY = false;
  32704. /**
  32705. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  32706. */
  32707. _this._twoSidedLighting = false;
  32708. _this._renderTargets = new BABYLON.SmartArray(16);
  32709. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  32710. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  32711. // Setup the default processing configuration to the scene.
  32712. _this._attachImageProcessingConfiguration(null);
  32713. _this.getRenderTargetTextures = function () {
  32714. _this._renderTargets.reset();
  32715. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  32716. _this._renderTargets.push(_this._reflectionTexture);
  32717. }
  32718. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  32719. _this._renderTargets.push(_this._refractionTexture);
  32720. }
  32721. return _this._renderTargets;
  32722. };
  32723. return _this;
  32724. }
  32725. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  32726. /**
  32727. * Gets the image processing configuration used either in this material.
  32728. */
  32729. get: function () {
  32730. return this._imageProcessingConfiguration;
  32731. },
  32732. /**
  32733. * Sets the Default image processing configuration used either in the this material.
  32734. *
  32735. * If sets to null, the scene one is in use.
  32736. */
  32737. set: function (value) {
  32738. this._attachImageProcessingConfiguration(value);
  32739. // Ensure the effect will be rebuilt.
  32740. this._markAllSubMeshesAsTexturesDirty();
  32741. },
  32742. enumerable: true,
  32743. configurable: true
  32744. });
  32745. /**
  32746. * Attaches a new image processing configuration to the Standard Material.
  32747. * @param configuration
  32748. */
  32749. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  32750. var _this = this;
  32751. if (configuration === this._imageProcessingConfiguration) {
  32752. return;
  32753. }
  32754. // Detaches observer.
  32755. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  32756. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  32757. }
  32758. // Pick the scene configuration if needed.
  32759. if (!configuration) {
  32760. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  32761. }
  32762. else {
  32763. this._imageProcessingConfiguration = configuration;
  32764. }
  32765. // Attaches observer.
  32766. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  32767. _this._markAllSubMeshesAsImageProcessingDirty();
  32768. });
  32769. };
  32770. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  32771. /**
  32772. * Gets wether the color curves effect is enabled.
  32773. */
  32774. get: function () {
  32775. return this.imageProcessingConfiguration.colorCurvesEnabled;
  32776. },
  32777. /**
  32778. * Sets wether the color curves effect is enabled.
  32779. */
  32780. set: function (value) {
  32781. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  32782. },
  32783. enumerable: true,
  32784. configurable: true
  32785. });
  32786. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  32787. /**
  32788. * Gets wether the color grading effect is enabled.
  32789. */
  32790. get: function () {
  32791. return this.imageProcessingConfiguration.colorGradingEnabled;
  32792. },
  32793. /**
  32794. * Gets wether the color grading effect is enabled.
  32795. */
  32796. set: function (value) {
  32797. this.imageProcessingConfiguration.colorGradingEnabled = value;
  32798. },
  32799. enumerable: true,
  32800. configurable: true
  32801. });
  32802. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  32803. /**
  32804. * Gets wether tonemapping is enabled or not.
  32805. */
  32806. get: function () {
  32807. return this._imageProcessingConfiguration.toneMappingEnabled;
  32808. },
  32809. /**
  32810. * Sets wether tonemapping is enabled or not
  32811. */
  32812. set: function (value) {
  32813. this._imageProcessingConfiguration.toneMappingEnabled = value;
  32814. },
  32815. enumerable: true,
  32816. configurable: true
  32817. });
  32818. ;
  32819. ;
  32820. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  32821. /**
  32822. * The camera exposure used on this material.
  32823. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  32824. * This corresponds to a photographic exposure.
  32825. */
  32826. get: function () {
  32827. return this._imageProcessingConfiguration.exposure;
  32828. },
  32829. /**
  32830. * The camera exposure used on this material.
  32831. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  32832. * This corresponds to a photographic exposure.
  32833. */
  32834. set: function (value) {
  32835. this._imageProcessingConfiguration.exposure = value;
  32836. },
  32837. enumerable: true,
  32838. configurable: true
  32839. });
  32840. ;
  32841. ;
  32842. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  32843. /**
  32844. * Gets The camera contrast used on this material.
  32845. */
  32846. get: function () {
  32847. return this._imageProcessingConfiguration.contrast;
  32848. },
  32849. /**
  32850. * Sets The camera contrast used on this material.
  32851. */
  32852. set: function (value) {
  32853. this._imageProcessingConfiguration.contrast = value;
  32854. },
  32855. enumerable: true,
  32856. configurable: true
  32857. });
  32858. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  32859. /**
  32860. * Gets the Color Grading 2D Lookup Texture.
  32861. */
  32862. get: function () {
  32863. return this._imageProcessingConfiguration.colorGradingTexture;
  32864. },
  32865. /**
  32866. * Sets the Color Grading 2D Lookup Texture.
  32867. */
  32868. set: function (value) {
  32869. this._imageProcessingConfiguration.colorGradingTexture = value;
  32870. },
  32871. enumerable: true,
  32872. configurable: true
  32873. });
  32874. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  32875. /**
  32876. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  32877. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  32878. * 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;
  32879. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  32880. */
  32881. get: function () {
  32882. return this._imageProcessingConfiguration.colorCurves;
  32883. },
  32884. /**
  32885. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  32886. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  32887. * 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;
  32888. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  32889. */
  32890. set: function (value) {
  32891. this._imageProcessingConfiguration.colorCurves = value;
  32892. },
  32893. enumerable: true,
  32894. configurable: true
  32895. });
  32896. StandardMaterial.prototype.getClassName = function () {
  32897. return "StandardMaterial";
  32898. };
  32899. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  32900. get: function () {
  32901. return this._useLogarithmicDepth;
  32902. },
  32903. set: function (value) {
  32904. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  32905. this._markAllSubMeshesAsMiscDirty();
  32906. },
  32907. enumerable: true,
  32908. configurable: true
  32909. });
  32910. StandardMaterial.prototype.needAlphaBlending = function () {
  32911. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  32912. };
  32913. StandardMaterial.prototype.needAlphaTesting = function () {
  32914. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  32915. };
  32916. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  32917. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  32918. };
  32919. StandardMaterial.prototype.getAlphaTestTexture = function () {
  32920. return this._diffuseTexture;
  32921. };
  32922. /**
  32923. * Child classes can use it to update shaders
  32924. */
  32925. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  32926. if (useInstances === void 0) { useInstances = false; }
  32927. if (subMesh.effect && this.isFrozen) {
  32928. if (this._wasPreviouslyReady && subMesh.effect) {
  32929. return true;
  32930. }
  32931. }
  32932. if (!subMesh._materialDefines) {
  32933. subMesh._materialDefines = new StandardMaterialDefines();
  32934. }
  32935. var scene = this.getScene();
  32936. var defines = subMesh._materialDefines;
  32937. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  32938. if (defines._renderId === scene.getRenderId()) {
  32939. return true;
  32940. }
  32941. }
  32942. var engine = scene.getEngine();
  32943. // Lights
  32944. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  32945. // Textures
  32946. if (defines._areTexturesDirty) {
  32947. defines._needUVs = false;
  32948. defines.MAINUV1 = false;
  32949. defines.MAINUV2 = false;
  32950. if (scene.texturesEnabled) {
  32951. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  32952. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  32953. return false;
  32954. }
  32955. else {
  32956. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  32957. }
  32958. }
  32959. else {
  32960. defines.DIFFUSE = false;
  32961. }
  32962. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  32963. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  32964. return false;
  32965. }
  32966. else {
  32967. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  32968. }
  32969. }
  32970. else {
  32971. defines.AMBIENT = false;
  32972. }
  32973. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  32974. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  32975. return false;
  32976. }
  32977. else {
  32978. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  32979. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  32980. }
  32981. }
  32982. else {
  32983. defines.OPACITY = false;
  32984. }
  32985. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  32986. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  32987. return false;
  32988. }
  32989. else {
  32990. defines._needNormals = true;
  32991. defines.REFLECTION = true;
  32992. defines.ROUGHNESS = (this._roughness > 0);
  32993. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  32994. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  32995. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  32996. switch (this._reflectionTexture.coordinatesMode) {
  32997. case BABYLON.Texture.CUBIC_MODE:
  32998. case BABYLON.Texture.INVCUBIC_MODE:
  32999. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  33000. break;
  33001. case BABYLON.Texture.EXPLICIT_MODE:
  33002. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  33003. break;
  33004. case BABYLON.Texture.PLANAR_MODE:
  33005. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  33006. break;
  33007. case BABYLON.Texture.PROJECTION_MODE:
  33008. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  33009. break;
  33010. case BABYLON.Texture.SKYBOX_MODE:
  33011. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  33012. break;
  33013. case BABYLON.Texture.SPHERICAL_MODE:
  33014. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  33015. break;
  33016. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  33017. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  33018. break;
  33019. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  33020. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  33021. break;
  33022. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  33023. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  33024. break;
  33025. }
  33026. }
  33027. }
  33028. else {
  33029. defines.REFLECTION = false;
  33030. }
  33031. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  33032. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  33033. return false;
  33034. }
  33035. else {
  33036. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  33037. }
  33038. }
  33039. else {
  33040. defines.EMISSIVE = false;
  33041. }
  33042. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  33043. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  33044. return false;
  33045. }
  33046. else {
  33047. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  33048. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  33049. }
  33050. }
  33051. else {
  33052. defines.LIGHTMAP = false;
  33053. }
  33054. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  33055. if (!this._specularTexture.isReadyOrNotBlocking()) {
  33056. return false;
  33057. }
  33058. else {
  33059. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  33060. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  33061. }
  33062. }
  33063. else {
  33064. defines.SPECULAR = false;
  33065. }
  33066. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  33067. // Bump texure can not be not blocking.
  33068. if (!this._bumpTexture.isReady()) {
  33069. return false;
  33070. }
  33071. else {
  33072. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  33073. defines.PARALLAX = this._useParallax;
  33074. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  33075. }
  33076. }
  33077. else {
  33078. defines.BUMP = false;
  33079. }
  33080. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  33081. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  33082. return false;
  33083. }
  33084. else {
  33085. defines._needUVs = true;
  33086. defines.REFRACTION = true;
  33087. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  33088. }
  33089. }
  33090. else {
  33091. defines.REFRACTION = false;
  33092. }
  33093. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  33094. }
  33095. else {
  33096. defines.DIFFUSE = false;
  33097. defines.AMBIENT = false;
  33098. defines.OPACITY = false;
  33099. defines.REFLECTION = false;
  33100. defines.EMISSIVE = false;
  33101. defines.LIGHTMAP = false;
  33102. defines.BUMP = false;
  33103. defines.REFRACTION = false;
  33104. }
  33105. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  33106. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  33107. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  33108. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  33109. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  33110. }
  33111. if (defines._areImageProcessingDirty) {
  33112. if (!this._imageProcessingConfiguration.isReady()) {
  33113. return false;
  33114. }
  33115. this._imageProcessingConfiguration.prepareDefines(defines);
  33116. }
  33117. if (defines._areFresnelDirty) {
  33118. if (StandardMaterial.FresnelEnabled) {
  33119. // Fresnel
  33120. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  33121. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  33122. this._reflectionFresnelParameters) {
  33123. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  33124. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  33125. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  33126. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  33127. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  33128. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  33129. defines._needNormals = true;
  33130. defines.FRESNEL = true;
  33131. }
  33132. }
  33133. else {
  33134. defines.FRESNEL = false;
  33135. }
  33136. }
  33137. // Misc.
  33138. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  33139. // Attribs
  33140. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  33141. // Values that need to be evaluated on every frame
  33142. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  33143. // Get correct effect
  33144. if (defines.isDirty) {
  33145. defines.markAsProcessed();
  33146. scene.resetCachedMaterial();
  33147. // Fallbacks
  33148. var fallbacks = new BABYLON.EffectFallbacks();
  33149. if (defines.REFLECTION) {
  33150. fallbacks.addFallback(0, "REFLECTION");
  33151. }
  33152. if (defines.SPECULAR) {
  33153. fallbacks.addFallback(0, "SPECULAR");
  33154. }
  33155. if (defines.BUMP) {
  33156. fallbacks.addFallback(0, "BUMP");
  33157. }
  33158. if (defines.PARALLAX) {
  33159. fallbacks.addFallback(1, "PARALLAX");
  33160. }
  33161. if (defines.PARALLAXOCCLUSION) {
  33162. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  33163. }
  33164. if (defines.SPECULAROVERALPHA) {
  33165. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  33166. }
  33167. if (defines.FOG) {
  33168. fallbacks.addFallback(1, "FOG");
  33169. }
  33170. if (defines.POINTSIZE) {
  33171. fallbacks.addFallback(0, "POINTSIZE");
  33172. }
  33173. if (defines.LOGARITHMICDEPTH) {
  33174. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  33175. }
  33176. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  33177. if (defines.SPECULARTERM) {
  33178. fallbacks.addFallback(0, "SPECULARTERM");
  33179. }
  33180. if (defines.DIFFUSEFRESNEL) {
  33181. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  33182. }
  33183. if (defines.OPACITYFRESNEL) {
  33184. fallbacks.addFallback(2, "OPACITYFRESNEL");
  33185. }
  33186. if (defines.REFLECTIONFRESNEL) {
  33187. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  33188. }
  33189. if (defines.EMISSIVEFRESNEL) {
  33190. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  33191. }
  33192. if (defines.FRESNEL) {
  33193. fallbacks.addFallback(4, "FRESNEL");
  33194. }
  33195. //Attributes
  33196. var attribs = [BABYLON.VertexBuffer.PositionKind];
  33197. if (defines.NORMAL) {
  33198. attribs.push(BABYLON.VertexBuffer.NormalKind);
  33199. }
  33200. if (defines.UV1) {
  33201. attribs.push(BABYLON.VertexBuffer.UVKind);
  33202. }
  33203. if (defines.UV2) {
  33204. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33205. }
  33206. if (defines.VERTEXCOLOR) {
  33207. attribs.push(BABYLON.VertexBuffer.ColorKind);
  33208. }
  33209. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  33210. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  33211. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  33212. var shaderName = "default";
  33213. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  33214. "vFogInfos", "vFogColor", "pointSize",
  33215. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  33216. "mBones",
  33217. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  33218. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  33219. "logarithmicDepthConstant", "vTangentSpaceParams"
  33220. ];
  33221. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  33222. var uniformBuffers = ["Material", "Scene"];
  33223. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  33224. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  33225. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  33226. uniformsNames: uniforms,
  33227. uniformBuffersNames: uniformBuffers,
  33228. samplers: samplers,
  33229. defines: defines,
  33230. maxSimultaneousLights: this._maxSimultaneousLights
  33231. });
  33232. if (this.customShaderNameResolve) {
  33233. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  33234. }
  33235. var join = defines.toString();
  33236. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  33237. attributes: attribs,
  33238. uniformsNames: uniforms,
  33239. uniformBuffersNames: uniformBuffers,
  33240. samplers: samplers,
  33241. defines: join,
  33242. fallbacks: fallbacks,
  33243. onCompiled: this.onCompiled,
  33244. onError: this.onError,
  33245. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  33246. }, engine), defines);
  33247. this.buildUniformLayout();
  33248. }
  33249. if (!subMesh.effect.isReady()) {
  33250. return false;
  33251. }
  33252. defines._renderId = scene.getRenderId();
  33253. this._wasPreviouslyReady = true;
  33254. return true;
  33255. };
  33256. StandardMaterial.prototype.buildUniformLayout = function () {
  33257. // Order is important !
  33258. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  33259. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  33260. this._uniformBuffer.addUniform("opacityParts", 4);
  33261. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  33262. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  33263. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  33264. this._uniformBuffer.addUniform("refractionRightColor", 4);
  33265. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  33266. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  33267. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  33268. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  33269. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  33270. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  33271. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  33272. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  33273. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  33274. this._uniformBuffer.addUniform("vBumpInfos", 3);
  33275. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  33276. this._uniformBuffer.addUniform("ambientMatrix", 16);
  33277. this._uniformBuffer.addUniform("opacityMatrix", 16);
  33278. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  33279. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  33280. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  33281. this._uniformBuffer.addUniform("specularMatrix", 16);
  33282. this._uniformBuffer.addUniform("bumpMatrix", 16);
  33283. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  33284. this._uniformBuffer.addUniform("refractionMatrix", 16);
  33285. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  33286. this._uniformBuffer.addUniform("vSpecularColor", 4);
  33287. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  33288. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  33289. this._uniformBuffer.addUniform("pointSize", 1);
  33290. this._uniformBuffer.create();
  33291. };
  33292. StandardMaterial.prototype.unbind = function () {
  33293. if (this._activeEffect) {
  33294. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  33295. this._activeEffect.setTexture("reflection2DSampler", null);
  33296. }
  33297. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  33298. this._activeEffect.setTexture("refraction2DSampler", null);
  33299. }
  33300. }
  33301. _super.prototype.unbind.call(this);
  33302. };
  33303. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  33304. var scene = this.getScene();
  33305. var defines = subMesh._materialDefines;
  33306. if (!defines) {
  33307. return;
  33308. }
  33309. var effect = subMesh.effect;
  33310. this._activeEffect = effect;
  33311. // Matrices
  33312. this.bindOnlyWorldMatrix(world);
  33313. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  33314. // Bones
  33315. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  33316. if (mustRebind) {
  33317. this._uniformBuffer.bindToEffect(effect, "Material");
  33318. this.bindViewProjection(effect);
  33319. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  33320. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  33321. // Fresnel
  33322. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  33323. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  33324. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  33325. }
  33326. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  33327. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  33328. }
  33329. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  33330. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  33331. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  33332. }
  33333. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  33334. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  33335. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  33336. }
  33337. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  33338. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  33339. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  33340. }
  33341. }
  33342. // Textures
  33343. if (scene.texturesEnabled) {
  33344. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  33345. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  33346. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  33347. }
  33348. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  33349. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  33350. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  33351. }
  33352. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  33353. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  33354. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  33355. }
  33356. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  33357. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  33358. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  33359. }
  33360. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  33361. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  33362. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  33363. }
  33364. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  33365. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  33366. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  33367. }
  33368. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  33369. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  33370. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  33371. }
  33372. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  33373. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  33374. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  33375. if (scene._mirroredCameraPosition) {
  33376. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  33377. }
  33378. else {
  33379. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  33380. }
  33381. }
  33382. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  33383. var depth = 1.0;
  33384. if (!this._refractionTexture.isCube) {
  33385. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  33386. if (this._refractionTexture.depth) {
  33387. depth = this._refractionTexture.depth;
  33388. }
  33389. }
  33390. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  33391. }
  33392. }
  33393. // Point size
  33394. if (this.pointsCloud) {
  33395. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  33396. }
  33397. if (defines.SPECULARTERM) {
  33398. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  33399. }
  33400. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  33401. // Diffuse
  33402. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  33403. }
  33404. // Textures
  33405. if (scene.texturesEnabled) {
  33406. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  33407. effect.setTexture("diffuseSampler", this._diffuseTexture);
  33408. }
  33409. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  33410. effect.setTexture("ambientSampler", this._ambientTexture);
  33411. }
  33412. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  33413. effect.setTexture("opacitySampler", this._opacityTexture);
  33414. }
  33415. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  33416. if (this._reflectionTexture.isCube) {
  33417. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  33418. }
  33419. else {
  33420. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  33421. }
  33422. }
  33423. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  33424. effect.setTexture("emissiveSampler", this._emissiveTexture);
  33425. }
  33426. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  33427. effect.setTexture("lightmapSampler", this._lightmapTexture);
  33428. }
  33429. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  33430. effect.setTexture("specularSampler", this._specularTexture);
  33431. }
  33432. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  33433. effect.setTexture("bumpSampler", this._bumpTexture);
  33434. }
  33435. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  33436. var depth = 1.0;
  33437. if (this._refractionTexture.isCube) {
  33438. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  33439. }
  33440. else {
  33441. effect.setTexture("refraction2DSampler", this._refractionTexture);
  33442. }
  33443. }
  33444. }
  33445. // Clip plane
  33446. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  33447. // Colors
  33448. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  33449. if (scene.activeCamera) {
  33450. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  33451. }
  33452. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  33453. }
  33454. if (mustRebind || !this.isFrozen) {
  33455. // Lights
  33456. if (scene.lightsEnabled && !this._disableLighting) {
  33457. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  33458. }
  33459. // View
  33460. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  33461. this.bindView(effect);
  33462. }
  33463. // Fog
  33464. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  33465. // Morph targets
  33466. if (defines.NUM_MORPH_INFLUENCERS) {
  33467. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  33468. }
  33469. // Log. depth
  33470. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  33471. // image processing
  33472. this._imageProcessingConfiguration.bind(this._activeEffect);
  33473. }
  33474. this._uniformBuffer.update();
  33475. this._afterBind(mesh, this._activeEffect);
  33476. };
  33477. StandardMaterial.prototype.getAnimatables = function () {
  33478. var results = [];
  33479. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  33480. results.push(this._diffuseTexture);
  33481. }
  33482. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  33483. results.push(this._ambientTexture);
  33484. }
  33485. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  33486. results.push(this._opacityTexture);
  33487. }
  33488. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  33489. results.push(this._reflectionTexture);
  33490. }
  33491. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  33492. results.push(this._emissiveTexture);
  33493. }
  33494. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  33495. results.push(this._specularTexture);
  33496. }
  33497. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  33498. results.push(this._bumpTexture);
  33499. }
  33500. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  33501. results.push(this._lightmapTexture);
  33502. }
  33503. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  33504. results.push(this._refractionTexture);
  33505. }
  33506. return results;
  33507. };
  33508. StandardMaterial.prototype.getActiveTextures = function () {
  33509. var activeTextures = _super.prototype.getActiveTextures.call(this);
  33510. if (this._diffuseTexture) {
  33511. activeTextures.push(this._diffuseTexture);
  33512. }
  33513. if (this._ambientTexture) {
  33514. activeTextures.push(this._ambientTexture);
  33515. }
  33516. if (this._opacityTexture) {
  33517. activeTextures.push(this._opacityTexture);
  33518. }
  33519. if (this._reflectionTexture) {
  33520. activeTextures.push(this._reflectionTexture);
  33521. }
  33522. if (this._emissiveTexture) {
  33523. activeTextures.push(this._emissiveTexture);
  33524. }
  33525. if (this._specularTexture) {
  33526. activeTextures.push(this._specularTexture);
  33527. }
  33528. if (this._bumpTexture) {
  33529. activeTextures.push(this._bumpTexture);
  33530. }
  33531. if (this._lightmapTexture) {
  33532. activeTextures.push(this._lightmapTexture);
  33533. }
  33534. if (this._refractionTexture) {
  33535. activeTextures.push(this._refractionTexture);
  33536. }
  33537. return activeTextures;
  33538. };
  33539. StandardMaterial.prototype.hasTexture = function (texture) {
  33540. if (_super.prototype.hasTexture.call(this, texture)) {
  33541. return true;
  33542. }
  33543. if (this._diffuseTexture === texture) {
  33544. return true;
  33545. }
  33546. if (this._ambientTexture === texture) {
  33547. return true;
  33548. }
  33549. if (this._opacityTexture === texture) {
  33550. return true;
  33551. }
  33552. if (this._reflectionTexture === texture) {
  33553. return true;
  33554. }
  33555. if (this._emissiveTexture === texture) {
  33556. return true;
  33557. }
  33558. if (this._specularTexture === texture) {
  33559. return true;
  33560. }
  33561. if (this._bumpTexture === texture) {
  33562. return true;
  33563. }
  33564. if (this._lightmapTexture === texture) {
  33565. return true;
  33566. }
  33567. if (this._refractionTexture === texture) {
  33568. return true;
  33569. }
  33570. return false;
  33571. };
  33572. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  33573. if (forceDisposeTextures) {
  33574. if (this._diffuseTexture) {
  33575. this._diffuseTexture.dispose();
  33576. }
  33577. if (this._ambientTexture) {
  33578. this._ambientTexture.dispose();
  33579. }
  33580. if (this._opacityTexture) {
  33581. this._opacityTexture.dispose();
  33582. }
  33583. if (this._reflectionTexture) {
  33584. this._reflectionTexture.dispose();
  33585. }
  33586. if (this._emissiveTexture) {
  33587. this._emissiveTexture.dispose();
  33588. }
  33589. if (this._specularTexture) {
  33590. this._specularTexture.dispose();
  33591. }
  33592. if (this._bumpTexture) {
  33593. this._bumpTexture.dispose();
  33594. }
  33595. if (this._lightmapTexture) {
  33596. this._lightmapTexture.dispose();
  33597. }
  33598. if (this._refractionTexture) {
  33599. this._refractionTexture.dispose();
  33600. }
  33601. }
  33602. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  33603. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  33604. }
  33605. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  33606. };
  33607. StandardMaterial.prototype.clone = function (name) {
  33608. var _this = this;
  33609. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  33610. result.name = name;
  33611. result.id = name;
  33612. return result;
  33613. };
  33614. StandardMaterial.prototype.serialize = function () {
  33615. return BABYLON.SerializationHelper.Serialize(this);
  33616. };
  33617. // Statics
  33618. StandardMaterial.Parse = function (source, scene, rootUrl) {
  33619. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  33620. };
  33621. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  33622. get: function () {
  33623. return StandardMaterial._DiffuseTextureEnabled;
  33624. },
  33625. set: function (value) {
  33626. if (StandardMaterial._DiffuseTextureEnabled === value) {
  33627. return;
  33628. }
  33629. StandardMaterial._DiffuseTextureEnabled = value;
  33630. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33631. },
  33632. enumerable: true,
  33633. configurable: true
  33634. });
  33635. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  33636. get: function () {
  33637. return StandardMaterial._AmbientTextureEnabled;
  33638. },
  33639. set: function (value) {
  33640. if (StandardMaterial._AmbientTextureEnabled === value) {
  33641. return;
  33642. }
  33643. StandardMaterial._AmbientTextureEnabled = value;
  33644. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33645. },
  33646. enumerable: true,
  33647. configurable: true
  33648. });
  33649. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  33650. get: function () {
  33651. return StandardMaterial._OpacityTextureEnabled;
  33652. },
  33653. set: function (value) {
  33654. if (StandardMaterial._OpacityTextureEnabled === value) {
  33655. return;
  33656. }
  33657. StandardMaterial._OpacityTextureEnabled = value;
  33658. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33659. },
  33660. enumerable: true,
  33661. configurable: true
  33662. });
  33663. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  33664. get: function () {
  33665. return StandardMaterial._ReflectionTextureEnabled;
  33666. },
  33667. set: function (value) {
  33668. if (StandardMaterial._ReflectionTextureEnabled === value) {
  33669. return;
  33670. }
  33671. StandardMaterial._ReflectionTextureEnabled = value;
  33672. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33673. },
  33674. enumerable: true,
  33675. configurable: true
  33676. });
  33677. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  33678. get: function () {
  33679. return StandardMaterial._EmissiveTextureEnabled;
  33680. },
  33681. set: function (value) {
  33682. if (StandardMaterial._EmissiveTextureEnabled === value) {
  33683. return;
  33684. }
  33685. StandardMaterial._EmissiveTextureEnabled = value;
  33686. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33687. },
  33688. enumerable: true,
  33689. configurable: true
  33690. });
  33691. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  33692. get: function () {
  33693. return StandardMaterial._SpecularTextureEnabled;
  33694. },
  33695. set: function (value) {
  33696. if (StandardMaterial._SpecularTextureEnabled === value) {
  33697. return;
  33698. }
  33699. StandardMaterial._SpecularTextureEnabled = value;
  33700. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33701. },
  33702. enumerable: true,
  33703. configurable: true
  33704. });
  33705. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  33706. get: function () {
  33707. return StandardMaterial._BumpTextureEnabled;
  33708. },
  33709. set: function (value) {
  33710. if (StandardMaterial._BumpTextureEnabled === value) {
  33711. return;
  33712. }
  33713. StandardMaterial._BumpTextureEnabled = value;
  33714. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33715. },
  33716. enumerable: true,
  33717. configurable: true
  33718. });
  33719. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  33720. get: function () {
  33721. return StandardMaterial._LightmapTextureEnabled;
  33722. },
  33723. set: function (value) {
  33724. if (StandardMaterial._LightmapTextureEnabled === value) {
  33725. return;
  33726. }
  33727. StandardMaterial._LightmapTextureEnabled = value;
  33728. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33729. },
  33730. enumerable: true,
  33731. configurable: true
  33732. });
  33733. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  33734. get: function () {
  33735. return StandardMaterial._RefractionTextureEnabled;
  33736. },
  33737. set: function (value) {
  33738. if (StandardMaterial._RefractionTextureEnabled === value) {
  33739. return;
  33740. }
  33741. StandardMaterial._RefractionTextureEnabled = value;
  33742. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33743. },
  33744. enumerable: true,
  33745. configurable: true
  33746. });
  33747. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  33748. get: function () {
  33749. return StandardMaterial._ColorGradingTextureEnabled;
  33750. },
  33751. set: function (value) {
  33752. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  33753. return;
  33754. }
  33755. StandardMaterial._ColorGradingTextureEnabled = value;
  33756. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33757. },
  33758. enumerable: true,
  33759. configurable: true
  33760. });
  33761. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  33762. get: function () {
  33763. return StandardMaterial._FresnelEnabled;
  33764. },
  33765. set: function (value) {
  33766. if (StandardMaterial._FresnelEnabled === value) {
  33767. return;
  33768. }
  33769. StandardMaterial._FresnelEnabled = value;
  33770. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  33771. },
  33772. enumerable: true,
  33773. configurable: true
  33774. });
  33775. // Flags used to enable or disable a type of texture for all Standard Materials
  33776. StandardMaterial._DiffuseTextureEnabled = true;
  33777. StandardMaterial._AmbientTextureEnabled = true;
  33778. StandardMaterial._OpacityTextureEnabled = true;
  33779. StandardMaterial._ReflectionTextureEnabled = true;
  33780. StandardMaterial._EmissiveTextureEnabled = true;
  33781. StandardMaterial._SpecularTextureEnabled = true;
  33782. StandardMaterial._BumpTextureEnabled = true;
  33783. StandardMaterial._LightmapTextureEnabled = true;
  33784. StandardMaterial._RefractionTextureEnabled = true;
  33785. StandardMaterial._ColorGradingTextureEnabled = true;
  33786. StandardMaterial._FresnelEnabled = true;
  33787. __decorate([
  33788. BABYLON.serializeAsTexture("diffuseTexture")
  33789. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  33790. __decorate([
  33791. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33792. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  33793. __decorate([
  33794. BABYLON.serializeAsTexture("ambientTexture")
  33795. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  33796. __decorate([
  33797. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33798. ], StandardMaterial.prototype, "ambientTexture", void 0);
  33799. __decorate([
  33800. BABYLON.serializeAsTexture("opacityTexture")
  33801. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  33802. __decorate([
  33803. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33804. ], StandardMaterial.prototype, "opacityTexture", void 0);
  33805. __decorate([
  33806. BABYLON.serializeAsTexture("reflectionTexture")
  33807. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  33808. __decorate([
  33809. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33810. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  33811. __decorate([
  33812. BABYLON.serializeAsTexture("emissiveTexture")
  33813. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  33814. __decorate([
  33815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33816. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  33817. __decorate([
  33818. BABYLON.serializeAsTexture("specularTexture")
  33819. ], StandardMaterial.prototype, "_specularTexture", void 0);
  33820. __decorate([
  33821. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33822. ], StandardMaterial.prototype, "specularTexture", void 0);
  33823. __decorate([
  33824. BABYLON.serializeAsTexture("bumpTexture")
  33825. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  33826. __decorate([
  33827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33828. ], StandardMaterial.prototype, "bumpTexture", void 0);
  33829. __decorate([
  33830. BABYLON.serializeAsTexture("lightmapTexture")
  33831. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  33832. __decorate([
  33833. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33834. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  33835. __decorate([
  33836. BABYLON.serializeAsTexture("refractionTexture")
  33837. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  33838. __decorate([
  33839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33840. ], StandardMaterial.prototype, "refractionTexture", void 0);
  33841. __decorate([
  33842. BABYLON.serializeAsColor3("ambient")
  33843. ], StandardMaterial.prototype, "ambientColor", void 0);
  33844. __decorate([
  33845. BABYLON.serializeAsColor3("diffuse")
  33846. ], StandardMaterial.prototype, "diffuseColor", void 0);
  33847. __decorate([
  33848. BABYLON.serializeAsColor3("specular")
  33849. ], StandardMaterial.prototype, "specularColor", void 0);
  33850. __decorate([
  33851. BABYLON.serializeAsColor3("emissive")
  33852. ], StandardMaterial.prototype, "emissiveColor", void 0);
  33853. __decorate([
  33854. BABYLON.serialize()
  33855. ], StandardMaterial.prototype, "specularPower", void 0);
  33856. __decorate([
  33857. BABYLON.serialize("useAlphaFromDiffuseTexture")
  33858. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  33859. __decorate([
  33860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33861. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  33862. __decorate([
  33863. BABYLON.serialize("useEmissiveAsIllumination")
  33864. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  33865. __decorate([
  33866. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33867. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  33868. __decorate([
  33869. BABYLON.serialize("linkEmissiveWithDiffuse")
  33870. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  33871. __decorate([
  33872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33873. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  33874. __decorate([
  33875. BABYLON.serialize("useSpecularOverAlpha")
  33876. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  33877. __decorate([
  33878. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33879. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  33880. __decorate([
  33881. BABYLON.serialize("useReflectionOverAlpha")
  33882. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  33883. __decorate([
  33884. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33885. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  33886. __decorate([
  33887. BABYLON.serialize("disableLighting")
  33888. ], StandardMaterial.prototype, "_disableLighting", void 0);
  33889. __decorate([
  33890. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33891. ], StandardMaterial.prototype, "disableLighting", void 0);
  33892. __decorate([
  33893. BABYLON.serialize("useParallax")
  33894. ], StandardMaterial.prototype, "_useParallax", void 0);
  33895. __decorate([
  33896. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33897. ], StandardMaterial.prototype, "useParallax", void 0);
  33898. __decorate([
  33899. BABYLON.serialize("useParallaxOcclusion")
  33900. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  33901. __decorate([
  33902. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33903. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  33904. __decorate([
  33905. BABYLON.serialize()
  33906. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  33907. __decorate([
  33908. BABYLON.serialize("roughness")
  33909. ], StandardMaterial.prototype, "_roughness", void 0);
  33910. __decorate([
  33911. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33912. ], StandardMaterial.prototype, "roughness", void 0);
  33913. __decorate([
  33914. BABYLON.serialize()
  33915. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  33916. __decorate([
  33917. BABYLON.serialize()
  33918. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  33919. __decorate([
  33920. BABYLON.serialize("useLightmapAsShadowmap")
  33921. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  33922. __decorate([
  33923. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33924. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  33925. __decorate([
  33926. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  33927. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  33928. __decorate([
  33929. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  33930. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  33931. __decorate([
  33932. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  33933. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  33934. __decorate([
  33935. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  33936. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  33937. __decorate([
  33938. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  33939. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  33940. __decorate([
  33941. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  33942. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  33943. __decorate([
  33944. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  33945. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  33946. __decorate([
  33947. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  33948. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  33949. __decorate([
  33950. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  33951. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  33952. __decorate([
  33953. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  33954. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  33955. __decorate([
  33956. BABYLON.serialize("useReflectionFresnelFromSpecular")
  33957. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  33958. __decorate([
  33959. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  33960. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  33961. __decorate([
  33962. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  33963. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  33964. __decorate([
  33965. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33966. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  33967. __decorate([
  33968. BABYLON.serialize("maxSimultaneousLights")
  33969. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  33970. __decorate([
  33971. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33972. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  33973. __decorate([
  33974. BABYLON.serialize("invertNormalMapX")
  33975. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  33976. __decorate([
  33977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33978. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  33979. __decorate([
  33980. BABYLON.serialize("invertNormalMapY")
  33981. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  33982. __decorate([
  33983. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33984. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  33985. __decorate([
  33986. BABYLON.serialize("twoSidedLighting")
  33987. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  33988. __decorate([
  33989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33990. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  33991. __decorate([
  33992. BABYLON.serialize()
  33993. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  33994. return StandardMaterial;
  33995. }(BABYLON.PushMaterial));
  33996. BABYLON.StandardMaterial = StandardMaterial;
  33997. })(BABYLON || (BABYLON = {}));
  33998. //# sourceMappingURL=babylon.standardMaterial.js.map
  33999. var BABYLON;
  34000. (function (BABYLON) {
  34001. var PBRMaterialDefines = /** @class */ (function (_super) {
  34002. __extends(PBRMaterialDefines, _super);
  34003. function PBRMaterialDefines() {
  34004. var _this = _super.call(this) || this;
  34005. _this.PBR = true;
  34006. _this.MAINUV1 = false;
  34007. _this.MAINUV2 = false;
  34008. _this.UV1 = false;
  34009. _this.UV2 = false;
  34010. _this.ALBEDO = false;
  34011. _this.ALBEDODIRECTUV = 0;
  34012. _this.VERTEXCOLOR = false;
  34013. _this.AMBIENT = false;
  34014. _this.AMBIENTDIRECTUV = 0;
  34015. _this.AMBIENTINGRAYSCALE = false;
  34016. _this.OPACITY = false;
  34017. _this.VERTEXALPHA = false;
  34018. _this.OPACITYDIRECTUV = 0;
  34019. _this.OPACITYRGB = false;
  34020. _this.ALPHATEST = false;
  34021. _this.DEPTHPREPASS = false;
  34022. _this.ALPHABLEND = false;
  34023. _this.ALPHAFROMALBEDO = false;
  34024. _this.ALPHATESTVALUE = 0.5;
  34025. _this.SPECULAROVERALPHA = false;
  34026. _this.RADIANCEOVERALPHA = false;
  34027. _this.ALPHAFRESNEL = false;
  34028. _this.PREMULTIPLYALPHA = false;
  34029. _this.EMISSIVE = false;
  34030. _this.EMISSIVEDIRECTUV = 0;
  34031. _this.REFLECTIVITY = false;
  34032. _this.REFLECTIVITYDIRECTUV = 0;
  34033. _this.SPECULARTERM = false;
  34034. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  34035. _this.MICROSURFACEAUTOMATIC = false;
  34036. _this.LODBASEDMICROSFURACE = false;
  34037. _this.MICROSURFACEMAP = false;
  34038. _this.MICROSURFACEMAPDIRECTUV = 0;
  34039. _this.METALLICWORKFLOW = false;
  34040. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  34041. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  34042. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  34043. _this.AOSTOREINMETALMAPRED = false;
  34044. _this.ENVIRONMENTBRDF = false;
  34045. _this.NORMAL = false;
  34046. _this.TANGENT = false;
  34047. _this.BUMP = false;
  34048. _this.BUMPDIRECTUV = 0;
  34049. _this.PARALLAX = false;
  34050. _this.PARALLAXOCCLUSION = false;
  34051. _this.NORMALXYSCALE = true;
  34052. _this.LIGHTMAP = false;
  34053. _this.LIGHTMAPDIRECTUV = 0;
  34054. _this.USELIGHTMAPASSHADOWMAP = false;
  34055. _this.REFLECTION = false;
  34056. _this.REFLECTIONMAP_3D = false;
  34057. _this.REFLECTIONMAP_SPHERICAL = false;
  34058. _this.REFLECTIONMAP_PLANAR = false;
  34059. _this.REFLECTIONMAP_CUBIC = false;
  34060. _this.REFLECTIONMAP_PROJECTION = false;
  34061. _this.REFLECTIONMAP_SKYBOX = false;
  34062. _this.REFLECTIONMAP_EXPLICIT = false;
  34063. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34064. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34065. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34066. _this.INVERTCUBICMAP = false;
  34067. _this.USESPHERICALFROMREFLECTIONMAP = false;
  34068. _this.USESPHERICALINFRAGMENT = false;
  34069. _this.REFLECTIONMAP_OPPOSITEZ = false;
  34070. _this.LODINREFLECTIONALPHA = false;
  34071. _this.GAMMAREFLECTION = false;
  34072. _this.REFRACTION = false;
  34073. _this.REFRACTIONMAP_3D = false;
  34074. _this.REFRACTIONMAP_OPPOSITEZ = false;
  34075. _this.LODINREFRACTIONALPHA = false;
  34076. _this.GAMMAREFRACTION = false;
  34077. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  34078. _this.INSTANCES = false;
  34079. _this.NUM_BONE_INFLUENCERS = 0;
  34080. _this.BonesPerMesh = 0;
  34081. _this.NONUNIFORMSCALING = false;
  34082. _this.MORPHTARGETS = false;
  34083. _this.MORPHTARGETS_NORMAL = false;
  34084. _this.MORPHTARGETS_TANGENT = false;
  34085. _this.NUM_MORPH_INFLUENCERS = 0;
  34086. _this.IMAGEPROCESSING = false;
  34087. _this.VIGNETTE = false;
  34088. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  34089. _this.VIGNETTEBLENDMODEOPAQUE = false;
  34090. _this.TONEMAPPING = false;
  34091. _this.CONTRAST = false;
  34092. _this.COLORCURVES = false;
  34093. _this.COLORGRADING = false;
  34094. _this.SAMPLER3DGREENDEPTH = false;
  34095. _this.SAMPLER3DBGRMAP = false;
  34096. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  34097. _this.EXPOSURE = false;
  34098. _this.USEPHYSICALLIGHTFALLOFF = false;
  34099. _this.TWOSIDEDLIGHTING = false;
  34100. _this.SHADOWFLOAT = false;
  34101. _this.CLIPPLANE = false;
  34102. _this.POINTSIZE = false;
  34103. _this.FOG = false;
  34104. _this.LOGARITHMICDEPTH = false;
  34105. _this.FORCENORMALFORWARD = false;
  34106. _this.rebuild();
  34107. return _this;
  34108. }
  34109. PBRMaterialDefines.prototype.reset = function () {
  34110. _super.prototype.reset.call(this);
  34111. this.ALPHATESTVALUE = 0.5;
  34112. this.PBR = true;
  34113. };
  34114. return PBRMaterialDefines;
  34115. }(BABYLON.MaterialDefines));
  34116. /**
  34117. * The Physically based material base class of BJS.
  34118. *
  34119. * This offers the main features of a standard PBR material.
  34120. * For more information, please refer to the documentation :
  34121. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  34122. */
  34123. var PBRBaseMaterial = /** @class */ (function (_super) {
  34124. __extends(PBRBaseMaterial, _super);
  34125. /**
  34126. * Instantiates a new PBRMaterial instance.
  34127. *
  34128. * @param name The material name
  34129. * @param scene The scene the material will be use in.
  34130. */
  34131. function PBRBaseMaterial(name, scene) {
  34132. var _this = _super.call(this, name, scene) || this;
  34133. /**
  34134. * Intensity of the direct lights e.g. the four lights available in your scene.
  34135. * This impacts both the direct diffuse and specular highlights.
  34136. */
  34137. _this._directIntensity = 1.0;
  34138. /**
  34139. * Intensity of the emissive part of the material.
  34140. * This helps controlling the emissive effect without modifying the emissive color.
  34141. */
  34142. _this._emissiveIntensity = 1.0;
  34143. /**
  34144. * Intensity of the environment e.g. how much the environment will light the object
  34145. * either through harmonics for rough material or through the refelction for shiny ones.
  34146. */
  34147. _this._environmentIntensity = 1.0;
  34148. /**
  34149. * This is a special control allowing the reduction of the specular highlights coming from the
  34150. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  34151. */
  34152. _this._specularIntensity = 1.0;
  34153. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  34154. /**
  34155. * Debug Control allowing disabling the bump map on this material.
  34156. */
  34157. _this._disableBumpMap = false;
  34158. /**
  34159. * AKA Occlusion Texture Intensity in other nomenclature.
  34160. */
  34161. _this._ambientTextureStrength = 1.0;
  34162. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  34163. /**
  34164. * AKA Diffuse Color in other nomenclature.
  34165. */
  34166. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  34167. /**
  34168. * AKA Specular Color in other nomenclature.
  34169. */
  34170. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  34171. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  34172. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  34173. /**
  34174. * AKA Glossiness in other nomenclature.
  34175. */
  34176. _this._microSurface = 0.9;
  34177. /**
  34178. * source material index of refraction (IOR)' / 'destination material IOR.
  34179. */
  34180. _this._indexOfRefraction = 0.66;
  34181. /**
  34182. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  34183. */
  34184. _this._invertRefractionY = false;
  34185. /**
  34186. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  34187. * Materials half opaque for instance using refraction could benefit from this control.
  34188. */
  34189. _this._linkRefractionWithTransparency = false;
  34190. _this._useLightmapAsShadowmap = false;
  34191. /**
  34192. * Specifies that the alpha is coming form the albedo channel alpha channel.
  34193. */
  34194. _this._useAlphaFromAlbedoTexture = false;
  34195. /**
  34196. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  34197. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  34198. */
  34199. _this._useSpecularOverAlpha = true;
  34200. /**
  34201. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  34202. */
  34203. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  34204. /**
  34205. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  34206. */
  34207. _this._useRoughnessFromMetallicTextureAlpha = true;
  34208. /**
  34209. * Specifies if the metallic texture contains the roughness information in its green channel.
  34210. */
  34211. _this._useRoughnessFromMetallicTextureGreen = false;
  34212. /**
  34213. * Specifies if the metallic texture contains the metallness information in its blue channel.
  34214. */
  34215. _this._useMetallnessFromMetallicTextureBlue = false;
  34216. /**
  34217. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  34218. */
  34219. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  34220. /**
  34221. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  34222. */
  34223. _this._useAmbientInGrayScale = false;
  34224. /**
  34225. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  34226. * The material will try to infer what glossiness each pixel should be.
  34227. */
  34228. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  34229. /**
  34230. * BJS is using an harcoded light falloff based on a manually sets up range.
  34231. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  34232. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  34233. */
  34234. _this._usePhysicalLightFalloff = true;
  34235. /**
  34236. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  34237. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  34238. */
  34239. _this._useRadianceOverAlpha = true;
  34240. /**
  34241. * Allows using the bump map in parallax mode.
  34242. */
  34243. _this._useParallax = false;
  34244. /**
  34245. * Allows using the bump map in parallax occlusion mode.
  34246. */
  34247. _this._useParallaxOcclusion = false;
  34248. /**
  34249. * Controls the scale bias of the parallax mode.
  34250. */
  34251. _this._parallaxScaleBias = 0.05;
  34252. /**
  34253. * If sets to true, disables all the lights affecting the material.
  34254. */
  34255. _this._disableLighting = false;
  34256. /**
  34257. * Number of Simultaneous lights allowed on the material.
  34258. */
  34259. _this._maxSimultaneousLights = 4;
  34260. /**
  34261. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  34262. */
  34263. _this._invertNormalMapX = false;
  34264. /**
  34265. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  34266. */
  34267. _this._invertNormalMapY = false;
  34268. /**
  34269. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34270. */
  34271. _this._twoSidedLighting = false;
  34272. /**
  34273. * Defines the alpha limits in alpha test mode.
  34274. */
  34275. _this._alphaCutOff = 0.4;
  34276. /**
  34277. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  34278. */
  34279. _this._forceAlphaTest = false;
  34280. /**
  34281. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  34282. * And/Or occlude the blended part.
  34283. */
  34284. _this._useAlphaFresnel = false;
  34285. /**
  34286. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  34287. * from cos thetav and roughness:
  34288. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  34289. */
  34290. _this._environmentBRDFTexture = null;
  34291. /**
  34292. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  34293. */
  34294. _this._forceIrradianceInFragment = false;
  34295. /**
  34296. * Force normal to face away from face.
  34297. * (Temporary internal fix to remove before 3.1)
  34298. */
  34299. _this._forceNormalForward = false;
  34300. _this._renderTargets = new BABYLON.SmartArray(16);
  34301. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34302. // Setup the default processing configuration to the scene.
  34303. _this._attachImageProcessingConfiguration(null);
  34304. _this.getRenderTargetTextures = function () {
  34305. _this._renderTargets.reset();
  34306. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  34307. _this._renderTargets.push(_this._reflectionTexture);
  34308. }
  34309. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  34310. _this._renderTargets.push(_this._refractionTexture);
  34311. }
  34312. return _this._renderTargets;
  34313. };
  34314. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  34315. return _this;
  34316. }
  34317. /**
  34318. * Attaches a new image processing configuration to the PBR Material.
  34319. * @param configuration
  34320. */
  34321. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  34322. var _this = this;
  34323. if (configuration === this._imageProcessingConfiguration) {
  34324. return;
  34325. }
  34326. // Detaches observer.
  34327. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34328. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34329. }
  34330. // Pick the scene configuration if needed.
  34331. if (!configuration) {
  34332. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  34333. }
  34334. else {
  34335. this._imageProcessingConfiguration = configuration;
  34336. }
  34337. // Attaches observer.
  34338. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  34339. _this._markAllSubMeshesAsImageProcessingDirty();
  34340. });
  34341. };
  34342. PBRBaseMaterial.prototype.getClassName = function () {
  34343. return "PBRBaseMaterial";
  34344. };
  34345. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  34346. get: function () {
  34347. return this._useLogarithmicDepth;
  34348. },
  34349. set: function (value) {
  34350. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  34351. },
  34352. enumerable: true,
  34353. configurable: true
  34354. });
  34355. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  34356. if (this._linkRefractionWithTransparency) {
  34357. return false;
  34358. }
  34359. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  34360. };
  34361. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  34362. if (this._forceAlphaTest) {
  34363. return true;
  34364. }
  34365. if (this._linkRefractionWithTransparency) {
  34366. return false;
  34367. }
  34368. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  34369. };
  34370. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  34371. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  34372. };
  34373. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  34374. return this._albedoTexture;
  34375. };
  34376. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34377. var _this = this;
  34378. if (subMesh.effect && this.isFrozen) {
  34379. if (this._wasPreviouslyReady) {
  34380. return true;
  34381. }
  34382. }
  34383. if (!subMesh._materialDefines) {
  34384. subMesh._materialDefines = new PBRMaterialDefines();
  34385. }
  34386. var scene = this.getScene();
  34387. var defines = subMesh._materialDefines;
  34388. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  34389. if (defines._renderId === scene.getRenderId()) {
  34390. return true;
  34391. }
  34392. }
  34393. var engine = scene.getEngine();
  34394. // Lights
  34395. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  34396. defines._needNormals = true;
  34397. // Textures
  34398. if (defines._areTexturesDirty) {
  34399. defines._needUVs = false;
  34400. if (scene.texturesEnabled) {
  34401. if (scene.getEngine().getCaps().textureLOD) {
  34402. defines.LODBASEDMICROSFURACE = true;
  34403. }
  34404. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  34405. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  34406. return false;
  34407. }
  34408. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  34409. }
  34410. else {
  34411. defines.ALBEDO = false;
  34412. }
  34413. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  34414. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  34415. return false;
  34416. }
  34417. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  34418. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  34419. }
  34420. else {
  34421. defines.AMBIENT = false;
  34422. }
  34423. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  34424. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  34425. return false;
  34426. }
  34427. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  34428. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  34429. }
  34430. else {
  34431. defines.OPACITY = false;
  34432. }
  34433. var reflectionTexture = this._getReflectionTexture();
  34434. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  34435. if (!reflectionTexture.isReadyOrNotBlocking()) {
  34436. return false;
  34437. }
  34438. defines.REFLECTION = true;
  34439. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  34440. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  34441. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  34442. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  34443. defines.INVERTCUBICMAP = true;
  34444. }
  34445. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  34446. switch (reflectionTexture.coordinatesMode) {
  34447. case BABYLON.Texture.CUBIC_MODE:
  34448. case BABYLON.Texture.INVCUBIC_MODE:
  34449. defines.REFLECTIONMAP_CUBIC = true;
  34450. break;
  34451. case BABYLON.Texture.EXPLICIT_MODE:
  34452. defines.REFLECTIONMAP_EXPLICIT = true;
  34453. break;
  34454. case BABYLON.Texture.PLANAR_MODE:
  34455. defines.REFLECTIONMAP_PLANAR = true;
  34456. break;
  34457. case BABYLON.Texture.PROJECTION_MODE:
  34458. defines.REFLECTIONMAP_PROJECTION = true;
  34459. break;
  34460. case BABYLON.Texture.SKYBOX_MODE:
  34461. defines.REFLECTIONMAP_SKYBOX = true;
  34462. break;
  34463. case BABYLON.Texture.SPHERICAL_MODE:
  34464. defines.REFLECTIONMAP_SPHERICAL = true;
  34465. break;
  34466. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  34467. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  34468. break;
  34469. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  34470. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  34471. break;
  34472. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  34473. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  34474. break;
  34475. }
  34476. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  34477. if (reflectionTexture.sphericalPolynomial) {
  34478. defines.USESPHERICALFROMREFLECTIONMAP = true;
  34479. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  34480. defines.USESPHERICALINFRAGMENT = true;
  34481. }
  34482. }
  34483. }
  34484. }
  34485. else {
  34486. defines.REFLECTION = false;
  34487. defines.REFLECTIONMAP_3D = false;
  34488. defines.REFLECTIONMAP_SPHERICAL = false;
  34489. defines.REFLECTIONMAP_PLANAR = false;
  34490. defines.REFLECTIONMAP_CUBIC = false;
  34491. defines.REFLECTIONMAP_PROJECTION = false;
  34492. defines.REFLECTIONMAP_SKYBOX = false;
  34493. defines.REFLECTIONMAP_EXPLICIT = false;
  34494. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34495. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34496. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34497. defines.INVERTCUBICMAP = false;
  34498. defines.USESPHERICALFROMREFLECTIONMAP = false;
  34499. defines.USESPHERICALINFRAGMENT = false;
  34500. defines.REFLECTIONMAP_OPPOSITEZ = false;
  34501. defines.LODINREFLECTIONALPHA = false;
  34502. defines.GAMMAREFLECTION = false;
  34503. }
  34504. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  34505. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  34506. return false;
  34507. }
  34508. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  34509. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  34510. }
  34511. else {
  34512. defines.LIGHTMAP = false;
  34513. }
  34514. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  34515. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  34516. return false;
  34517. }
  34518. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  34519. }
  34520. else {
  34521. defines.EMISSIVE = false;
  34522. }
  34523. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  34524. if (this._metallicTexture) {
  34525. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  34526. return false;
  34527. }
  34528. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  34529. defines.METALLICWORKFLOW = true;
  34530. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  34531. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  34532. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  34533. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  34534. }
  34535. else if (this._reflectivityTexture) {
  34536. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  34537. return false;
  34538. }
  34539. defines.METALLICWORKFLOW = false;
  34540. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  34541. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  34542. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  34543. }
  34544. else {
  34545. defines.METALLICWORKFLOW = false;
  34546. defines.REFLECTIVITY = false;
  34547. }
  34548. if (this._microSurfaceTexture) {
  34549. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  34550. return false;
  34551. }
  34552. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  34553. }
  34554. else {
  34555. defines.MICROSURFACEMAP = false;
  34556. }
  34557. }
  34558. else {
  34559. defines.REFLECTIVITY = false;
  34560. defines.MICROSURFACEMAP = false;
  34561. }
  34562. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  34563. // Bump texure can not be none blocking.
  34564. if (!this._bumpTexture.isReady()) {
  34565. return false;
  34566. }
  34567. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  34568. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  34569. defines.PARALLAX = true;
  34570. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  34571. }
  34572. else {
  34573. defines.PARALLAX = false;
  34574. }
  34575. }
  34576. else {
  34577. defines.BUMP = false;
  34578. }
  34579. var refractionTexture = this._getRefractionTexture();
  34580. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  34581. if (!refractionTexture.isReadyOrNotBlocking()) {
  34582. return false;
  34583. }
  34584. defines.REFRACTION = true;
  34585. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  34586. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  34587. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  34588. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  34589. if (this._linkRefractionWithTransparency) {
  34590. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  34591. }
  34592. }
  34593. else {
  34594. defines.REFRACTION = false;
  34595. }
  34596. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  34597. // This is blocking.
  34598. if (!this._environmentBRDFTexture.isReady()) {
  34599. return false;
  34600. }
  34601. defines.ENVIRONMENTBRDF = true;
  34602. }
  34603. else {
  34604. defines.ENVIRONMENTBRDF = false;
  34605. }
  34606. if (this._shouldUseAlphaFromAlbedoTexture()) {
  34607. defines.ALPHAFROMALBEDO = true;
  34608. }
  34609. else {
  34610. defines.ALPHAFROMALBEDO = false;
  34611. }
  34612. }
  34613. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  34614. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  34615. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  34616. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  34617. defines.METALLICWORKFLOW = true;
  34618. }
  34619. else {
  34620. defines.METALLICWORKFLOW = false;
  34621. }
  34622. if (!this.backFaceCulling && this._twoSidedLighting) {
  34623. defines.TWOSIDEDLIGHTING = true;
  34624. }
  34625. else {
  34626. defines.TWOSIDEDLIGHTING = false;
  34627. }
  34628. defines.ALPHATESTVALUE = this._alphaCutOff;
  34629. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  34630. defines.ALPHABLEND = this.needAlphaBlending();
  34631. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  34632. }
  34633. if (defines._areImageProcessingDirty) {
  34634. if (!this._imageProcessingConfiguration.isReady()) {
  34635. return false;
  34636. }
  34637. this._imageProcessingConfiguration.prepareDefines(defines);
  34638. }
  34639. defines.FORCENORMALFORWARD = this._forceNormalForward;
  34640. // Misc.
  34641. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  34642. // Values that need to be evaluated on every frame
  34643. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._forceAlphaTest);
  34644. // Attribs
  34645. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  34646. if (mesh) {
  34647. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34648. mesh.createNormals(true);
  34649. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  34650. }
  34651. }
  34652. }
  34653. // Get correct effect
  34654. if (defines.isDirty) {
  34655. defines.markAsProcessed();
  34656. scene.resetCachedMaterial();
  34657. // Fallbacks
  34658. var fallbacks = new BABYLON.EffectFallbacks();
  34659. if (defines.ENVIRONMENTBRDF) {
  34660. fallbacks.addFallback(0, "ENVIRONMENTBRDF");
  34661. }
  34662. if (defines.REFLECTION) {
  34663. fallbacks.addFallback(0, "REFLECTION");
  34664. }
  34665. if (defines.REFRACTION) {
  34666. fallbacks.addFallback(0, "REFRACTION");
  34667. }
  34668. if (defines.REFLECTIVITY) {
  34669. fallbacks.addFallback(0, "REFLECTIVITY");
  34670. }
  34671. if (defines.BUMP) {
  34672. fallbacks.addFallback(0, "BUMP");
  34673. }
  34674. if (defines.PARALLAX) {
  34675. fallbacks.addFallback(1, "PARALLAX");
  34676. }
  34677. if (defines.PARALLAXOCCLUSION) {
  34678. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  34679. }
  34680. if (defines.SPECULAROVERALPHA) {
  34681. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  34682. }
  34683. if (defines.FOG) {
  34684. fallbacks.addFallback(1, "FOG");
  34685. }
  34686. if (defines.POINTSIZE) {
  34687. fallbacks.addFallback(0, "POINTSIZE");
  34688. }
  34689. if (defines.LOGARITHMICDEPTH) {
  34690. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  34691. }
  34692. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  34693. if (defines.SPECULARTERM) {
  34694. fallbacks.addFallback(0, "SPECULARTERM");
  34695. }
  34696. if (defines.NUM_BONE_INFLUENCERS > 0) {
  34697. fallbacks.addCPUSkinningFallback(0, mesh);
  34698. }
  34699. //Attributes
  34700. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34701. if (defines.NORMAL) {
  34702. attribs.push(BABYLON.VertexBuffer.NormalKind);
  34703. }
  34704. if (defines.TANGENT) {
  34705. attribs.push(BABYLON.VertexBuffer.TangentKind);
  34706. }
  34707. if (defines.UV1) {
  34708. attribs.push(BABYLON.VertexBuffer.UVKind);
  34709. }
  34710. if (defines.UV2) {
  34711. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34712. }
  34713. if (defines.VERTEXCOLOR) {
  34714. attribs.push(BABYLON.VertexBuffer.ColorKind);
  34715. }
  34716. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  34717. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  34718. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  34719. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  34720. "vFogInfos", "vFogColor", "pointSize",
  34721. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  34722. "mBones",
  34723. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  34724. "vLightingIntensity",
  34725. "logarithmicDepthConstant",
  34726. "vSphericalX", "vSphericalY", "vSphericalZ",
  34727. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  34728. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  34729. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  34730. "vTangentSpaceParams"
  34731. ];
  34732. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  34733. "bumpSampler", "lightmapSampler", "opacitySampler",
  34734. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  34735. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  34736. "microSurfaceSampler", "environmentBrdfSampler"];
  34737. var uniformBuffers = ["Material", "Scene"];
  34738. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  34739. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  34740. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  34741. uniformsNames: uniforms,
  34742. uniformBuffersNames: uniformBuffers,
  34743. samplers: samplers,
  34744. defines: defines,
  34745. maxSimultaneousLights: this._maxSimultaneousLights
  34746. });
  34747. var onCompiled = function (effect) {
  34748. if (_this.onCompiled) {
  34749. _this.onCompiled(effect);
  34750. }
  34751. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  34752. };
  34753. var join = defines.toString();
  34754. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  34755. attributes: attribs,
  34756. uniformsNames: uniforms,
  34757. uniformBuffersNames: uniformBuffers,
  34758. samplers: samplers,
  34759. defines: join,
  34760. fallbacks: fallbacks,
  34761. onCompiled: onCompiled,
  34762. onError: this.onError,
  34763. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  34764. }, engine), defines);
  34765. this.buildUniformLayout();
  34766. }
  34767. if (!subMesh.effect.isReady()) {
  34768. return false;
  34769. }
  34770. defines._renderId = scene.getRenderId();
  34771. this._wasPreviouslyReady = true;
  34772. return true;
  34773. };
  34774. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  34775. // Order is important !
  34776. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  34777. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  34778. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  34779. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  34780. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  34781. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  34782. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  34783. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  34784. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  34785. this._uniformBuffer.addUniform("vBumpInfos", 3);
  34786. this._uniformBuffer.addUniform("albedoMatrix", 16);
  34787. this._uniformBuffer.addUniform("ambientMatrix", 16);
  34788. this._uniformBuffer.addUniform("opacityMatrix", 16);
  34789. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  34790. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  34791. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  34792. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  34793. this._uniformBuffer.addUniform("bumpMatrix", 16);
  34794. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  34795. this._uniformBuffer.addUniform("refractionMatrix", 16);
  34796. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  34797. this._uniformBuffer.addUniform("vReflectionColor", 3);
  34798. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  34799. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  34800. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  34801. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  34802. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  34803. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  34804. this._uniformBuffer.addUniform("pointSize", 1);
  34805. this._uniformBuffer.create();
  34806. };
  34807. PBRBaseMaterial.prototype.unbind = function () {
  34808. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  34809. this._uniformBuffer.setTexture("reflectionSampler", null);
  34810. }
  34811. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  34812. this._uniformBuffer.setTexture("refractionSampler", null);
  34813. }
  34814. _super.prototype.unbind.call(this);
  34815. };
  34816. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  34817. this._activeEffect.setMatrix("world", world);
  34818. };
  34819. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34820. var scene = this.getScene();
  34821. var defines = subMesh._materialDefines;
  34822. if (!defines) {
  34823. return;
  34824. }
  34825. var effect = subMesh.effect;
  34826. this._activeEffect = effect;
  34827. // Matrices
  34828. this.bindOnlyWorldMatrix(world);
  34829. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  34830. // Bones
  34831. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  34832. if (mustRebind) {
  34833. this._uniformBuffer.bindToEffect(effect, "Material");
  34834. this.bindViewProjection(effect);
  34835. var reflectionTexture = this._getReflectionTexture();
  34836. var refractionTexture = this._getRefractionTexture();
  34837. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  34838. // Texture uniforms
  34839. if (scene.texturesEnabled) {
  34840. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  34841. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  34842. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  34843. }
  34844. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  34845. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  34846. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  34847. }
  34848. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  34849. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  34850. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  34851. }
  34852. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  34853. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  34854. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  34855. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  34856. var polynomials = reflectionTexture.sphericalPolynomial;
  34857. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  34858. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  34859. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  34860. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  34861. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  34862. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  34863. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  34864. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  34865. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  34866. }
  34867. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  34868. }
  34869. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  34870. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  34871. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  34872. }
  34873. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  34874. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  34875. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  34876. }
  34877. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  34878. if (this._metallicTexture) {
  34879. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  34880. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  34881. }
  34882. else if (this._reflectivityTexture) {
  34883. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  34884. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  34885. }
  34886. if (this._microSurfaceTexture) {
  34887. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  34888. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  34889. }
  34890. }
  34891. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  34892. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  34893. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  34894. if (scene._mirroredCameraPosition) {
  34895. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  34896. }
  34897. else {
  34898. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  34899. }
  34900. }
  34901. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  34902. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  34903. var depth = 1.0;
  34904. if (!refractionTexture.isCube) {
  34905. if (refractionTexture.depth) {
  34906. depth = refractionTexture.depth;
  34907. }
  34908. }
  34909. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  34910. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  34911. }
  34912. }
  34913. // Point size
  34914. if (this.pointsCloud) {
  34915. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  34916. }
  34917. // Colors
  34918. if (defines.METALLICWORKFLOW) {
  34919. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  34920. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  34921. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  34922. }
  34923. else {
  34924. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  34925. }
  34926. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  34927. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  34928. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  34929. // Misc
  34930. this._lightingInfos.x = this._directIntensity;
  34931. this._lightingInfos.y = this._emissiveIntensity;
  34932. this._lightingInfos.z = this._environmentIntensity;
  34933. this._lightingInfos.w = this._specularIntensity;
  34934. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  34935. }
  34936. // Textures
  34937. if (scene.texturesEnabled) {
  34938. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  34939. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  34940. }
  34941. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  34942. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  34943. }
  34944. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  34945. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  34946. }
  34947. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  34948. if (defines.LODBASEDMICROSFURACE) {
  34949. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  34950. }
  34951. else {
  34952. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  34953. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  34954. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  34955. }
  34956. }
  34957. if (defines.ENVIRONMENTBRDF) {
  34958. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  34959. }
  34960. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  34961. if (defines.LODBASEDMICROSFURACE) {
  34962. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  34963. }
  34964. else {
  34965. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  34966. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  34967. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  34968. }
  34969. }
  34970. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  34971. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  34972. }
  34973. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  34974. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  34975. }
  34976. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  34977. if (this._metallicTexture) {
  34978. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  34979. }
  34980. else if (this._reflectivityTexture) {
  34981. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  34982. }
  34983. if (this._microSurfaceTexture) {
  34984. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  34985. }
  34986. }
  34987. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  34988. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  34989. }
  34990. }
  34991. // Clip plane
  34992. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  34993. // Colors
  34994. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  34995. var eyePosition = scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition;
  34996. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  34997. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  34998. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  34999. }
  35000. if (mustRebind || !this.isFrozen) {
  35001. // Lights
  35002. if (scene.lightsEnabled && !this._disableLighting) {
  35003. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  35004. }
  35005. // View
  35006. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  35007. this.bindView(effect);
  35008. }
  35009. // Fog
  35010. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  35011. // Morph targets
  35012. if (defines.NUM_MORPH_INFLUENCERS) {
  35013. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  35014. }
  35015. // image processing
  35016. this._imageProcessingConfiguration.bind(this._activeEffect);
  35017. // Log. depth
  35018. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  35019. }
  35020. this._uniformBuffer.update();
  35021. this._afterBind(mesh);
  35022. scene = null;
  35023. };
  35024. PBRBaseMaterial.prototype.getAnimatables = function () {
  35025. var results = [];
  35026. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  35027. results.push(this._albedoTexture);
  35028. }
  35029. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35030. results.push(this._ambientTexture);
  35031. }
  35032. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35033. results.push(this._opacityTexture);
  35034. }
  35035. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35036. results.push(this._reflectionTexture);
  35037. }
  35038. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35039. results.push(this._emissiveTexture);
  35040. }
  35041. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  35042. results.push(this._metallicTexture);
  35043. }
  35044. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  35045. results.push(this._reflectivityTexture);
  35046. }
  35047. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35048. results.push(this._bumpTexture);
  35049. }
  35050. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35051. results.push(this._lightmapTexture);
  35052. }
  35053. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35054. results.push(this._refractionTexture);
  35055. }
  35056. return results;
  35057. };
  35058. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  35059. if (this._reflectionTexture) {
  35060. return this._reflectionTexture;
  35061. }
  35062. return this.getScene().environmentTexture;
  35063. };
  35064. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  35065. if (this._refractionTexture) {
  35066. return this._refractionTexture;
  35067. }
  35068. if (this._linkRefractionWithTransparency) {
  35069. return this.getScene().environmentTexture;
  35070. }
  35071. return null;
  35072. };
  35073. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35074. if (forceDisposeTextures) {
  35075. if (this._albedoTexture) {
  35076. this._albedoTexture.dispose();
  35077. }
  35078. if (this._ambientTexture) {
  35079. this._ambientTexture.dispose();
  35080. }
  35081. if (this._opacityTexture) {
  35082. this._opacityTexture.dispose();
  35083. }
  35084. if (this._reflectionTexture) {
  35085. this._reflectionTexture.dispose();
  35086. }
  35087. if (this._environmentBRDFTexture) {
  35088. this._environmentBRDFTexture.dispose();
  35089. }
  35090. if (this._emissiveTexture) {
  35091. this._emissiveTexture.dispose();
  35092. }
  35093. if (this._metallicTexture) {
  35094. this._metallicTexture.dispose();
  35095. }
  35096. if (this._reflectivityTexture) {
  35097. this._reflectivityTexture.dispose();
  35098. }
  35099. if (this._bumpTexture) {
  35100. this._bumpTexture.dispose();
  35101. }
  35102. if (this._lightmapTexture) {
  35103. this._lightmapTexture.dispose();
  35104. }
  35105. if (this._refractionTexture) {
  35106. this._refractionTexture.dispose();
  35107. }
  35108. }
  35109. this._renderTargets.dispose();
  35110. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35111. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35112. }
  35113. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35114. };
  35115. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  35116. __decorate([
  35117. BABYLON.serializeAsImageProcessingConfiguration()
  35118. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  35119. __decorate([
  35120. BABYLON.serialize()
  35121. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  35122. return PBRBaseMaterial;
  35123. }(BABYLON.PushMaterial));
  35124. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  35125. })(BABYLON || (BABYLON = {}));
  35126. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  35127. var BABYLON;
  35128. (function (BABYLON) {
  35129. var Internals;
  35130. (function (Internals) {
  35131. /**
  35132. * The Physically based simple base material of BJS.
  35133. *
  35134. * This enables better naming and convention enforcements on top of the pbrMaterial.
  35135. * It is used as the base class for both the specGloss and metalRough conventions.
  35136. */
  35137. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  35138. __extends(PBRBaseSimpleMaterial, _super);
  35139. /**
  35140. * Instantiates a new PBRMaterial instance.
  35141. *
  35142. * @param name The material name
  35143. * @param scene The scene the material will be use in.
  35144. */
  35145. function PBRBaseSimpleMaterial(name, scene) {
  35146. var _this = _super.call(this, name, scene) || this;
  35147. /**
  35148. * Number of Simultaneous lights allowed on the material.
  35149. */
  35150. _this.maxSimultaneousLights = 4;
  35151. /**
  35152. * If sets to true, disables all the lights affecting the material.
  35153. */
  35154. _this.disableLighting = false;
  35155. /**
  35156. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  35157. */
  35158. _this.invertNormalMapX = false;
  35159. /**
  35160. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  35161. */
  35162. _this.invertNormalMapY = false;
  35163. /**
  35164. * Emissivie color used to self-illuminate the model.
  35165. */
  35166. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  35167. /**
  35168. * Occlusion Channel Strenght.
  35169. */
  35170. _this.occlusionStrength = 1.0;
  35171. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35172. _this._useAmbientInGrayScale = true;
  35173. return _this;
  35174. }
  35175. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  35176. /**
  35177. * Gets the current transparency mode.
  35178. */
  35179. get: function () {
  35180. return this._transparencyMode;
  35181. },
  35182. /**
  35183. * Sets the transparency mode of the material.
  35184. */
  35185. set: function (value) {
  35186. if (this._transparencyMode === value) {
  35187. return;
  35188. }
  35189. this._transparencyMode = value;
  35190. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  35191. this._forceAlphaTest = true;
  35192. }
  35193. else {
  35194. this._forceAlphaTest = false;
  35195. }
  35196. this._markAllSubMeshesAsTexturesDirty();
  35197. },
  35198. enumerable: true,
  35199. configurable: true
  35200. });
  35201. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  35202. /**
  35203. * Gets the current double sided mode.
  35204. */
  35205. get: function () {
  35206. return this._twoSidedLighting;
  35207. },
  35208. /**
  35209. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35210. */
  35211. set: function (value) {
  35212. if (this._twoSidedLighting === value) {
  35213. return;
  35214. }
  35215. this._twoSidedLighting = value;
  35216. this.backFaceCulling = !value;
  35217. this._markAllSubMeshesAsTexturesDirty();
  35218. },
  35219. enumerable: true,
  35220. configurable: true
  35221. });
  35222. /**
  35223. * Specifies wether or not the alpha value of the albedo texture should be used.
  35224. */
  35225. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  35226. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35227. };
  35228. /**
  35229. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  35230. */
  35231. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  35232. if (this._linkRefractionWithTransparency) {
  35233. return false;
  35234. }
  35235. return (this.alpha < 1.0) ||
  35236. (this._shouldUseAlphaFromAlbedoTexture() &&
  35237. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  35238. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  35239. };
  35240. /**
  35241. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  35242. */
  35243. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  35244. if (this._linkRefractionWithTransparency) {
  35245. return false;
  35246. }
  35247. return this._shouldUseAlphaFromAlbedoTexture() &&
  35248. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  35249. };
  35250. /**
  35251. * Return the active textures of the material.
  35252. */
  35253. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  35254. var activeTextures = _super.prototype.getActiveTextures.call(this);
  35255. if (this.environmentTexture) {
  35256. activeTextures.push(this.environmentTexture);
  35257. }
  35258. if (this.normalTexture) {
  35259. activeTextures.push(this.normalTexture);
  35260. }
  35261. if (this.emissiveTexture) {
  35262. activeTextures.push(this.emissiveTexture);
  35263. }
  35264. if (this.occlusionTexture) {
  35265. activeTextures.push(this.occlusionTexture);
  35266. }
  35267. return activeTextures;
  35268. };
  35269. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  35270. return "PBRBaseSimpleMaterial";
  35271. };
  35272. __decorate([
  35273. BABYLON.serialize(),
  35274. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35275. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  35276. __decorate([
  35277. BABYLON.serialize(),
  35278. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35279. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  35280. __decorate([
  35281. BABYLON.serializeAsTexture(),
  35282. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  35283. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  35284. __decorate([
  35285. BABYLON.serialize(),
  35286. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35287. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  35288. __decorate([
  35289. BABYLON.serialize(),
  35290. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35291. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  35292. __decorate([
  35293. BABYLON.serializeAsTexture(),
  35294. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  35295. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  35296. __decorate([
  35297. BABYLON.serializeAsColor3("emissive"),
  35298. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35299. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  35300. __decorate([
  35301. BABYLON.serializeAsTexture(),
  35302. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35303. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  35304. __decorate([
  35305. BABYLON.serialize(),
  35306. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  35307. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  35308. __decorate([
  35309. BABYLON.serializeAsTexture(),
  35310. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  35311. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  35312. __decorate([
  35313. BABYLON.serialize(),
  35314. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  35315. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  35316. __decorate([
  35317. BABYLON.serialize()
  35318. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  35319. __decorate([
  35320. BABYLON.serialize()
  35321. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  35322. return PBRBaseSimpleMaterial;
  35323. }(BABYLON.PBRBaseMaterial));
  35324. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  35325. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  35326. })(BABYLON || (BABYLON = {}));
  35327. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  35328. var BABYLON;
  35329. (function (BABYLON) {
  35330. /**
  35331. * The Physically based material of BJS.
  35332. *
  35333. * This offers the main features of a standard PBR material.
  35334. * For more information, please refer to the documentation :
  35335. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  35336. */
  35337. var PBRMaterial = /** @class */ (function (_super) {
  35338. __extends(PBRMaterial, _super);
  35339. /**
  35340. * Instantiates a new PBRMaterial instance.
  35341. *
  35342. * @param name The material name
  35343. * @param scene The scene the material will be use in.
  35344. */
  35345. function PBRMaterial(name, scene) {
  35346. var _this = _super.call(this, name, scene) || this;
  35347. /**
  35348. * Intensity of the direct lights e.g. the four lights available in your scene.
  35349. * This impacts both the direct diffuse and specular highlights.
  35350. */
  35351. _this.directIntensity = 1.0;
  35352. /**
  35353. * Intensity of the emissive part of the material.
  35354. * This helps controlling the emissive effect without modifying the emissive color.
  35355. */
  35356. _this.emissiveIntensity = 1.0;
  35357. /**
  35358. * Intensity of the environment e.g. how much the environment will light the object
  35359. * either through harmonics for rough material or through the refelction for shiny ones.
  35360. */
  35361. _this.environmentIntensity = 1.0;
  35362. /**
  35363. * This is a special control allowing the reduction of the specular highlights coming from the
  35364. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  35365. */
  35366. _this.specularIntensity = 1.0;
  35367. /**
  35368. * Debug Control allowing disabling the bump map on this material.
  35369. */
  35370. _this.disableBumpMap = false;
  35371. /**
  35372. * AKA Occlusion Texture Intensity in other nomenclature.
  35373. */
  35374. _this.ambientTextureStrength = 1.0;
  35375. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  35376. /**
  35377. * AKA Diffuse Color in other nomenclature.
  35378. */
  35379. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  35380. /**
  35381. * AKA Specular Color in other nomenclature.
  35382. */
  35383. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  35384. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  35385. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  35386. /**
  35387. * AKA Glossiness in other nomenclature.
  35388. */
  35389. _this.microSurface = 1.0;
  35390. /**
  35391. * source material index of refraction (IOR)' / 'destination material IOR.
  35392. */
  35393. _this.indexOfRefraction = 0.66;
  35394. /**
  35395. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  35396. */
  35397. _this.invertRefractionY = false;
  35398. /**
  35399. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  35400. * Materials half opaque for instance using refraction could benefit from this control.
  35401. */
  35402. _this.linkRefractionWithTransparency = false;
  35403. _this.useLightmapAsShadowmap = false;
  35404. /**
  35405. * Specifies that the alpha is coming form the albedo channel alpha channel.
  35406. */
  35407. _this.useAlphaFromAlbedoTexture = false;
  35408. /**
  35409. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  35410. */
  35411. _this.forceAlphaTest = false;
  35412. /**
  35413. * Defines the alpha limits in alpha test mode.
  35414. */
  35415. _this.alphaCutOff = 0.4;
  35416. /**
  35417. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  35418. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  35419. */
  35420. _this.useSpecularOverAlpha = true;
  35421. /**
  35422. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  35423. */
  35424. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  35425. /**
  35426. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  35427. */
  35428. _this.useRoughnessFromMetallicTextureAlpha = true;
  35429. /**
  35430. * Specifies if the metallic texture contains the roughness information in its green channel.
  35431. */
  35432. _this.useRoughnessFromMetallicTextureGreen = false;
  35433. /**
  35434. * Specifies if the metallic texture contains the metallness information in its blue channel.
  35435. */
  35436. _this.useMetallnessFromMetallicTextureBlue = false;
  35437. /**
  35438. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  35439. */
  35440. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  35441. /**
  35442. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  35443. */
  35444. _this.useAmbientInGrayScale = false;
  35445. /**
  35446. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  35447. * The material will try to infer what glossiness each pixel should be.
  35448. */
  35449. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  35450. /**
  35451. * BJS is using an harcoded light falloff based on a manually sets up range.
  35452. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  35453. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  35454. */
  35455. _this.usePhysicalLightFalloff = true;
  35456. /**
  35457. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  35458. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  35459. */
  35460. _this.useRadianceOverAlpha = true;
  35461. /**
  35462. * Allows using the bump map in parallax mode.
  35463. */
  35464. _this.useParallax = false;
  35465. /**
  35466. * Allows using the bump map in parallax occlusion mode.
  35467. */
  35468. _this.useParallaxOcclusion = false;
  35469. /**
  35470. * Controls the scale bias of the parallax mode.
  35471. */
  35472. _this.parallaxScaleBias = 0.05;
  35473. /**
  35474. * If sets to true, disables all the lights affecting the material.
  35475. */
  35476. _this.disableLighting = false;
  35477. /**
  35478. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  35479. */
  35480. _this.forceIrradianceInFragment = false;
  35481. /**
  35482. * Number of Simultaneous lights allowed on the material.
  35483. */
  35484. _this.maxSimultaneousLights = 4;
  35485. /**
  35486. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  35487. */
  35488. _this.invertNormalMapX = false;
  35489. /**
  35490. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  35491. */
  35492. _this.invertNormalMapY = false;
  35493. /**
  35494. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35495. */
  35496. _this.twoSidedLighting = false;
  35497. /**
  35498. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  35499. * And/Or occlude the blended part.
  35500. */
  35501. _this.useAlphaFresnel = false;
  35502. /**
  35503. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  35504. * And/Or occlude the blended part.
  35505. */
  35506. _this.environmentBRDFTexture = null;
  35507. /**
  35508. * Force normal to face away from face.
  35509. * (Temporary internal fix to remove before 3.1)
  35510. */
  35511. _this.forceNormalForward = false;
  35512. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  35513. return _this;
  35514. }
  35515. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  35516. /**
  35517. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  35518. */
  35519. get: function () {
  35520. return this._PBRMATERIAL_OPAQUE;
  35521. },
  35522. enumerable: true,
  35523. configurable: true
  35524. });
  35525. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  35526. /**
  35527. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  35528. */
  35529. get: function () {
  35530. return this._PBRMATERIAL_ALPHATEST;
  35531. },
  35532. enumerable: true,
  35533. configurable: true
  35534. });
  35535. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  35536. /**
  35537. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  35538. */
  35539. get: function () {
  35540. return this._PBRMATERIAL_ALPHABLEND;
  35541. },
  35542. enumerable: true,
  35543. configurable: true
  35544. });
  35545. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  35546. /**
  35547. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  35548. * They are also discarded below the alpha cutoff threshold to improve performances.
  35549. */
  35550. get: function () {
  35551. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  35552. },
  35553. enumerable: true,
  35554. configurable: true
  35555. });
  35556. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  35557. /**
  35558. * Gets the image processing configuration used either in this material.
  35559. */
  35560. get: function () {
  35561. return this._imageProcessingConfiguration;
  35562. },
  35563. /**
  35564. * Sets the Default image processing configuration used either in the this material.
  35565. *
  35566. * If sets to null, the scene one is in use.
  35567. */
  35568. set: function (value) {
  35569. this._attachImageProcessingConfiguration(value);
  35570. // Ensure the effect will be rebuilt.
  35571. this._markAllSubMeshesAsTexturesDirty();
  35572. },
  35573. enumerable: true,
  35574. configurable: true
  35575. });
  35576. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  35577. /**
  35578. * Gets wether the color curves effect is enabled.
  35579. */
  35580. get: function () {
  35581. return this.imageProcessingConfiguration.colorCurvesEnabled;
  35582. },
  35583. /**
  35584. * Sets wether the color curves effect is enabled.
  35585. */
  35586. set: function (value) {
  35587. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  35588. },
  35589. enumerable: true,
  35590. configurable: true
  35591. });
  35592. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  35593. /**
  35594. * Gets wether the color grading effect is enabled.
  35595. */
  35596. get: function () {
  35597. return this.imageProcessingConfiguration.colorGradingEnabled;
  35598. },
  35599. /**
  35600. * Gets wether the color grading effect is enabled.
  35601. */
  35602. set: function (value) {
  35603. this.imageProcessingConfiguration.colorGradingEnabled = value;
  35604. },
  35605. enumerable: true,
  35606. configurable: true
  35607. });
  35608. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  35609. /**
  35610. * Gets wether tonemapping is enabled or not.
  35611. */
  35612. get: function () {
  35613. return this._imageProcessingConfiguration.toneMappingEnabled;
  35614. },
  35615. /**
  35616. * Sets wether tonemapping is enabled or not
  35617. */
  35618. set: function (value) {
  35619. this._imageProcessingConfiguration.toneMappingEnabled = value;
  35620. },
  35621. enumerable: true,
  35622. configurable: true
  35623. });
  35624. ;
  35625. ;
  35626. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  35627. /**
  35628. * The camera exposure used on this material.
  35629. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  35630. * This corresponds to a photographic exposure.
  35631. */
  35632. get: function () {
  35633. return this._imageProcessingConfiguration.exposure;
  35634. },
  35635. /**
  35636. * The camera exposure used on this material.
  35637. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  35638. * This corresponds to a photographic exposure.
  35639. */
  35640. set: function (value) {
  35641. this._imageProcessingConfiguration.exposure = value;
  35642. },
  35643. enumerable: true,
  35644. configurable: true
  35645. });
  35646. ;
  35647. ;
  35648. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  35649. /**
  35650. * Gets The camera contrast used on this material.
  35651. */
  35652. get: function () {
  35653. return this._imageProcessingConfiguration.contrast;
  35654. },
  35655. /**
  35656. * Sets The camera contrast used on this material.
  35657. */
  35658. set: function (value) {
  35659. this._imageProcessingConfiguration.contrast = value;
  35660. },
  35661. enumerable: true,
  35662. configurable: true
  35663. });
  35664. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  35665. /**
  35666. * Gets the Color Grading 2D Lookup Texture.
  35667. */
  35668. get: function () {
  35669. return this._imageProcessingConfiguration.colorGradingTexture;
  35670. },
  35671. /**
  35672. * Sets the Color Grading 2D Lookup Texture.
  35673. */
  35674. set: function (value) {
  35675. this._imageProcessingConfiguration.colorGradingTexture = value;
  35676. },
  35677. enumerable: true,
  35678. configurable: true
  35679. });
  35680. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  35681. /**
  35682. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35683. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35684. * 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;
  35685. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35686. */
  35687. get: function () {
  35688. return this._imageProcessingConfiguration.colorCurves;
  35689. },
  35690. /**
  35691. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35692. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35693. * 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;
  35694. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35695. */
  35696. set: function (value) {
  35697. this._imageProcessingConfiguration.colorCurves = value;
  35698. },
  35699. enumerable: true,
  35700. configurable: true
  35701. });
  35702. PBRMaterial.prototype.getClassName = function () {
  35703. return "PBRMaterial";
  35704. };
  35705. PBRMaterial.prototype.getActiveTextures = function () {
  35706. var activeTextures = _super.prototype.getActiveTextures.call(this);
  35707. if (this._albedoTexture) {
  35708. activeTextures.push(this._albedoTexture);
  35709. }
  35710. if (this._ambientTexture) {
  35711. activeTextures.push(this._ambientTexture);
  35712. }
  35713. if (this._opacityTexture) {
  35714. activeTextures.push(this._opacityTexture);
  35715. }
  35716. if (this._reflectionTexture) {
  35717. activeTextures.push(this._reflectionTexture);
  35718. }
  35719. if (this._emissiveTexture) {
  35720. activeTextures.push(this._emissiveTexture);
  35721. }
  35722. if (this._reflectivityTexture) {
  35723. activeTextures.push(this._reflectivityTexture);
  35724. }
  35725. if (this._metallicTexture) {
  35726. activeTextures.push(this._metallicTexture);
  35727. }
  35728. if (this._microSurfaceTexture) {
  35729. activeTextures.push(this._microSurfaceTexture);
  35730. }
  35731. if (this._bumpTexture) {
  35732. activeTextures.push(this._bumpTexture);
  35733. }
  35734. if (this._lightmapTexture) {
  35735. activeTextures.push(this._lightmapTexture);
  35736. }
  35737. if (this._refractionTexture) {
  35738. activeTextures.push(this._refractionTexture);
  35739. }
  35740. return activeTextures;
  35741. };
  35742. PBRMaterial.prototype.hasTexture = function (texture) {
  35743. if (_super.prototype.hasTexture.call(this, texture)) {
  35744. return true;
  35745. }
  35746. if (this._albedoTexture === texture) {
  35747. return true;
  35748. }
  35749. if (this._ambientTexture === texture) {
  35750. return true;
  35751. }
  35752. if (this._opacityTexture === texture) {
  35753. return true;
  35754. }
  35755. if (this._reflectionTexture === texture) {
  35756. return true;
  35757. }
  35758. if (this._reflectivityTexture === texture) {
  35759. return true;
  35760. }
  35761. if (this._metallicTexture === texture) {
  35762. return true;
  35763. }
  35764. if (this._microSurfaceTexture === texture) {
  35765. return true;
  35766. }
  35767. if (this._bumpTexture === texture) {
  35768. return true;
  35769. }
  35770. if (this._lightmapTexture === texture) {
  35771. return true;
  35772. }
  35773. if (this._refractionTexture === texture) {
  35774. return true;
  35775. }
  35776. return false;
  35777. };
  35778. PBRMaterial.prototype.clone = function (name) {
  35779. var _this = this;
  35780. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  35781. clone.id = name;
  35782. clone.name = name;
  35783. return clone;
  35784. };
  35785. PBRMaterial.prototype.serialize = function () {
  35786. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  35787. serializationObject.customType = "BABYLON.PBRMaterial";
  35788. return serializationObject;
  35789. };
  35790. // Statics
  35791. PBRMaterial.Parse = function (source, scene, rootUrl) {
  35792. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  35793. };
  35794. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  35795. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  35796. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  35797. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  35798. __decorate([
  35799. BABYLON.serialize(),
  35800. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35801. ], PBRMaterial.prototype, "directIntensity", void 0);
  35802. __decorate([
  35803. BABYLON.serialize(),
  35804. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35805. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  35806. __decorate([
  35807. BABYLON.serialize(),
  35808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35809. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  35810. __decorate([
  35811. BABYLON.serialize(),
  35812. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35813. ], PBRMaterial.prototype, "specularIntensity", void 0);
  35814. __decorate([
  35815. BABYLON.serialize(),
  35816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35817. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  35818. __decorate([
  35819. BABYLON.serializeAsTexture(),
  35820. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35821. ], PBRMaterial.prototype, "albedoTexture", void 0);
  35822. __decorate([
  35823. BABYLON.serializeAsTexture(),
  35824. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35825. ], PBRMaterial.prototype, "ambientTexture", void 0);
  35826. __decorate([
  35827. BABYLON.serialize(),
  35828. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35829. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  35830. __decorate([
  35831. BABYLON.serializeAsTexture(),
  35832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35833. ], PBRMaterial.prototype, "opacityTexture", void 0);
  35834. __decorate([
  35835. BABYLON.serializeAsTexture(),
  35836. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35837. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  35838. __decorate([
  35839. BABYLON.serializeAsTexture(),
  35840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35841. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  35842. __decorate([
  35843. BABYLON.serializeAsTexture(),
  35844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35845. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  35846. __decorate([
  35847. BABYLON.serializeAsTexture(),
  35848. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35849. ], PBRMaterial.prototype, "metallicTexture", void 0);
  35850. __decorate([
  35851. BABYLON.serialize(),
  35852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35853. ], PBRMaterial.prototype, "metallic", void 0);
  35854. __decorate([
  35855. BABYLON.serialize(),
  35856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35857. ], PBRMaterial.prototype, "roughness", void 0);
  35858. __decorate([
  35859. BABYLON.serializeAsTexture(),
  35860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35861. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  35862. __decorate([
  35863. BABYLON.serializeAsTexture(),
  35864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35865. ], PBRMaterial.prototype, "bumpTexture", void 0);
  35866. __decorate([
  35867. BABYLON.serializeAsTexture(),
  35868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  35869. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  35870. __decorate([
  35871. BABYLON.serializeAsTexture(),
  35872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35873. ], PBRMaterial.prototype, "refractionTexture", void 0);
  35874. __decorate([
  35875. BABYLON.serializeAsColor3("ambient"),
  35876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35877. ], PBRMaterial.prototype, "ambientColor", void 0);
  35878. __decorate([
  35879. BABYLON.serializeAsColor3("albedo"),
  35880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35881. ], PBRMaterial.prototype, "albedoColor", void 0);
  35882. __decorate([
  35883. BABYLON.serializeAsColor3("reflectivity"),
  35884. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35885. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  35886. __decorate([
  35887. BABYLON.serializeAsColor3("reflection"),
  35888. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35889. ], PBRMaterial.prototype, "reflectionColor", void 0);
  35890. __decorate([
  35891. BABYLON.serializeAsColor3("emissive"),
  35892. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35893. ], PBRMaterial.prototype, "emissiveColor", void 0);
  35894. __decorate([
  35895. BABYLON.serialize(),
  35896. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35897. ], PBRMaterial.prototype, "microSurface", void 0);
  35898. __decorate([
  35899. BABYLON.serialize(),
  35900. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35901. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  35902. __decorate([
  35903. BABYLON.serialize(),
  35904. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35905. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  35906. __decorate([
  35907. BABYLON.serialize(),
  35908. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35909. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  35910. __decorate([
  35911. BABYLON.serialize(),
  35912. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35913. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  35914. __decorate([
  35915. BABYLON.serialize(),
  35916. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35917. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  35918. __decorate([
  35919. BABYLON.serialize(),
  35920. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35921. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  35922. __decorate([
  35923. BABYLON.serialize(),
  35924. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35925. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  35926. __decorate([
  35927. BABYLON.serialize(),
  35928. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35929. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  35930. __decorate([
  35931. BABYLON.serialize(),
  35932. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35933. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  35934. __decorate([
  35935. BABYLON.serialize(),
  35936. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35937. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  35938. __decorate([
  35939. BABYLON.serialize(),
  35940. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35941. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  35942. __decorate([
  35943. BABYLON.serialize(),
  35944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35945. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  35946. __decorate([
  35947. BABYLON.serialize(),
  35948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35949. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  35950. __decorate([
  35951. BABYLON.serialize(),
  35952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35953. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  35954. __decorate([
  35955. BABYLON.serialize(),
  35956. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35957. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  35958. __decorate([
  35959. BABYLON.serialize(),
  35960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35961. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  35962. __decorate([
  35963. BABYLON.serialize(),
  35964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35965. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  35966. __decorate([
  35967. BABYLON.serialize(),
  35968. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35969. ], PBRMaterial.prototype, "useParallax", void 0);
  35970. __decorate([
  35971. BABYLON.serialize(),
  35972. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35973. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  35974. __decorate([
  35975. BABYLON.serialize(),
  35976. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35977. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  35978. __decorate([
  35979. BABYLON.serialize(),
  35980. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35981. ], PBRMaterial.prototype, "disableLighting", void 0);
  35982. __decorate([
  35983. BABYLON.serialize(),
  35984. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35985. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  35986. __decorate([
  35987. BABYLON.serialize(),
  35988. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35989. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  35990. __decorate([
  35991. BABYLON.serialize(),
  35992. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35993. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  35994. __decorate([
  35995. BABYLON.serialize(),
  35996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35997. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  35998. __decorate([
  35999. BABYLON.serialize(),
  36000. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36001. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  36002. __decorate([
  36003. BABYLON.serialize(),
  36004. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36005. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  36006. __decorate([
  36007. BABYLON.serializeAsTexture(),
  36008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36009. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  36010. __decorate([
  36011. BABYLON.serialize(),
  36012. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36013. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  36014. return PBRMaterial;
  36015. }(BABYLON.PBRBaseMaterial));
  36016. BABYLON.PBRMaterial = PBRMaterial;
  36017. })(BABYLON || (BABYLON = {}));
  36018. //# sourceMappingURL=babylon.pbrMaterial.js.map
  36019. var BABYLON;
  36020. (function (BABYLON) {
  36021. /**
  36022. * The PBR material of BJS following the metal roughness convention.
  36023. *
  36024. * This fits to the PBR convention in the GLTF definition:
  36025. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  36026. */
  36027. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  36028. __extends(PBRMetallicRoughnessMaterial, _super);
  36029. /**
  36030. * Instantiates a new PBRMetalRoughnessMaterial instance.
  36031. *
  36032. * @param name The material name
  36033. * @param scene The scene the material will be use in.
  36034. */
  36035. function PBRMetallicRoughnessMaterial(name, scene) {
  36036. var _this = _super.call(this, name, scene) || this;
  36037. _this._useRoughnessFromMetallicTextureAlpha = false;
  36038. _this._useRoughnessFromMetallicTextureGreen = true;
  36039. _this._useMetallnessFromMetallicTextureBlue = true;
  36040. return _this;
  36041. }
  36042. /**
  36043. * Return the currrent class name of the material.
  36044. */
  36045. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  36046. return "PBRMetallicRoughnessMaterial";
  36047. };
  36048. /**
  36049. * Return the active textures of the material.
  36050. */
  36051. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  36052. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36053. if (this.baseTexture) {
  36054. activeTextures.push(this.baseTexture);
  36055. }
  36056. if (this.metallicRoughnessTexture) {
  36057. activeTextures.push(this.metallicRoughnessTexture);
  36058. }
  36059. return activeTextures;
  36060. };
  36061. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  36062. if (_super.prototype.hasTexture.call(this, texture)) {
  36063. return true;
  36064. }
  36065. if (this.baseTexture === texture) {
  36066. return true;
  36067. }
  36068. if (this.metallicRoughnessTexture === texture) {
  36069. return true;
  36070. }
  36071. return false;
  36072. };
  36073. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  36074. var _this = this;
  36075. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  36076. clone.id = name;
  36077. clone.name = name;
  36078. return clone;
  36079. };
  36080. /**
  36081. * Serialize the material to a parsable JSON object.
  36082. */
  36083. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  36084. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36085. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  36086. return serializationObject;
  36087. };
  36088. /**
  36089. * Parses a JSON object correponding to the serialize function.
  36090. */
  36091. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  36092. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  36093. };
  36094. __decorate([
  36095. BABYLON.serializeAsColor3(),
  36096. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  36097. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  36098. __decorate([
  36099. BABYLON.serializeAsTexture(),
  36100. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  36101. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  36102. __decorate([
  36103. BABYLON.serialize(),
  36104. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36105. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  36106. __decorate([
  36107. BABYLON.serialize(),
  36108. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36109. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  36110. __decorate([
  36111. BABYLON.serializeAsTexture(),
  36112. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  36113. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  36114. return PBRMetallicRoughnessMaterial;
  36115. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  36116. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  36117. })(BABYLON || (BABYLON = {}));
  36118. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  36119. var BABYLON;
  36120. (function (BABYLON) {
  36121. /**
  36122. * The PBR material of BJS following the specular glossiness convention.
  36123. *
  36124. * This fits to the PBR convention in the GLTF definition:
  36125. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  36126. */
  36127. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  36128. __extends(PBRSpecularGlossinessMaterial, _super);
  36129. /**
  36130. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  36131. *
  36132. * @param name The material name
  36133. * @param scene The scene the material will be use in.
  36134. */
  36135. function PBRSpecularGlossinessMaterial(name, scene) {
  36136. var _this = _super.call(this, name, scene) || this;
  36137. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  36138. return _this;
  36139. }
  36140. /**
  36141. * Return the currrent class name of the material.
  36142. */
  36143. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  36144. return "PBRSpecularGlossinessMaterial";
  36145. };
  36146. /**
  36147. * Return the active textures of the material.
  36148. */
  36149. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  36150. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36151. if (this.diffuseTexture) {
  36152. activeTextures.push(this.diffuseTexture);
  36153. }
  36154. if (this.specularGlossinessTexture) {
  36155. activeTextures.push(this.specularGlossinessTexture);
  36156. }
  36157. return activeTextures;
  36158. };
  36159. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  36160. if (_super.prototype.hasTexture.call(this, texture)) {
  36161. return true;
  36162. }
  36163. if (this.diffuseTexture === texture) {
  36164. return true;
  36165. }
  36166. if (this.specularGlossinessTexture === texture) {
  36167. return true;
  36168. }
  36169. return false;
  36170. };
  36171. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  36172. var _this = this;
  36173. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  36174. clone.id = name;
  36175. clone.name = name;
  36176. return clone;
  36177. };
  36178. /**
  36179. * Serialize the material to a parsable JSON object.
  36180. */
  36181. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  36182. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36183. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  36184. return serializationObject;
  36185. };
  36186. /**
  36187. * Parses a JSON object correponding to the serialize function.
  36188. */
  36189. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  36190. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  36191. };
  36192. __decorate([
  36193. BABYLON.serializeAsColor3("diffuse"),
  36194. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  36195. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  36196. __decorate([
  36197. BABYLON.serializeAsTexture(),
  36198. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  36199. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  36200. __decorate([
  36201. BABYLON.serializeAsColor3("specular"),
  36202. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  36203. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  36204. __decorate([
  36205. BABYLON.serialize(),
  36206. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  36207. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  36208. __decorate([
  36209. BABYLON.serializeAsTexture(),
  36210. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  36211. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  36212. return PBRSpecularGlossinessMaterial;
  36213. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  36214. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  36215. })(BABYLON || (BABYLON = {}));
  36216. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  36217. var BABYLON;
  36218. (function (BABYLON) {
  36219. BABYLON.CameraInputTypes = {};
  36220. var CameraInputsManager = /** @class */ (function () {
  36221. function CameraInputsManager(camera) {
  36222. this.attached = {};
  36223. this.camera = camera;
  36224. this.checkInputs = function () { };
  36225. }
  36226. CameraInputsManager.prototype.add = function (input) {
  36227. var type = input.getSimpleName();
  36228. if (this.attached[type]) {
  36229. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  36230. return;
  36231. }
  36232. this.attached[type] = input;
  36233. input.camera = this.camera;
  36234. //for checkInputs, we are dynamically creating a function
  36235. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  36236. if (input.checkInputs) {
  36237. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  36238. }
  36239. if (this.attachedElement) {
  36240. input.attachControl(this.attachedElement);
  36241. }
  36242. };
  36243. CameraInputsManager.prototype.remove = function (inputToRemove) {
  36244. for (var cam in this.attached) {
  36245. var input = this.attached[cam];
  36246. if (input === inputToRemove) {
  36247. input.detachControl(this.attachedElement);
  36248. input.camera = null;
  36249. delete this.attached[cam];
  36250. this.rebuildInputCheck();
  36251. }
  36252. }
  36253. };
  36254. CameraInputsManager.prototype.removeByType = function (inputType) {
  36255. for (var cam in this.attached) {
  36256. var input = this.attached[cam];
  36257. if (input.getClassName() === inputType) {
  36258. input.detachControl(this.attachedElement);
  36259. input.camera = null;
  36260. delete this.attached[cam];
  36261. this.rebuildInputCheck();
  36262. }
  36263. }
  36264. };
  36265. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  36266. var current = this.checkInputs;
  36267. return function () {
  36268. current();
  36269. fn();
  36270. };
  36271. };
  36272. CameraInputsManager.prototype.attachInput = function (input) {
  36273. if (this.attachedElement) {
  36274. input.attachControl(this.attachedElement, this.noPreventDefault);
  36275. }
  36276. };
  36277. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  36278. if (noPreventDefault === void 0) { noPreventDefault = false; }
  36279. if (this.attachedElement) {
  36280. return;
  36281. }
  36282. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  36283. this.attachedElement = element;
  36284. this.noPreventDefault = noPreventDefault;
  36285. for (var cam in this.attached) {
  36286. this.attached[cam].attachControl(element, noPreventDefault);
  36287. }
  36288. };
  36289. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  36290. if (disconnect === void 0) { disconnect = false; }
  36291. if (this.attachedElement !== element) {
  36292. return;
  36293. }
  36294. for (var cam in this.attached) {
  36295. this.attached[cam].detachControl(element);
  36296. if (disconnect) {
  36297. this.attached[cam].camera = null;
  36298. }
  36299. }
  36300. this.attachedElement = null;
  36301. };
  36302. CameraInputsManager.prototype.rebuildInputCheck = function () {
  36303. this.checkInputs = function () { };
  36304. for (var cam in this.attached) {
  36305. var input = this.attached[cam];
  36306. if (input.checkInputs) {
  36307. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  36308. }
  36309. }
  36310. };
  36311. CameraInputsManager.prototype.clear = function () {
  36312. if (this.attachedElement) {
  36313. this.detachElement(this.attachedElement, true);
  36314. }
  36315. this.attached = {};
  36316. this.attachedElement = null;
  36317. this.checkInputs = function () { };
  36318. };
  36319. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  36320. var inputs = {};
  36321. for (var cam in this.attached) {
  36322. var input = this.attached[cam];
  36323. var res = BABYLON.SerializationHelper.Serialize(input);
  36324. inputs[input.getClassName()] = res;
  36325. }
  36326. serializedCamera.inputsmgr = inputs;
  36327. };
  36328. CameraInputsManager.prototype.parse = function (parsedCamera) {
  36329. var parsedInputs = parsedCamera.inputsmgr;
  36330. if (parsedInputs) {
  36331. this.clear();
  36332. for (var n in parsedInputs) {
  36333. var construct = BABYLON.CameraInputTypes[n];
  36334. if (construct) {
  36335. var parsedinput = parsedInputs[n];
  36336. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  36337. this.add(input);
  36338. }
  36339. }
  36340. }
  36341. else {
  36342. //2016-03-08 this part is for managing backward compatibility
  36343. for (var n in this.attached) {
  36344. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  36345. if (construct) {
  36346. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  36347. this.remove(this.attached[n]);
  36348. this.add(input);
  36349. }
  36350. }
  36351. }
  36352. };
  36353. return CameraInputsManager;
  36354. }());
  36355. BABYLON.CameraInputsManager = CameraInputsManager;
  36356. })(BABYLON || (BABYLON = {}));
  36357. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  36358. var BABYLON;
  36359. (function (BABYLON) {
  36360. var FreeCameraMouseInput = /** @class */ (function () {
  36361. function FreeCameraMouseInput(touchEnabled) {
  36362. if (touchEnabled === void 0) { touchEnabled = true; }
  36363. this.touchEnabled = touchEnabled;
  36364. this.buttons = [0, 1, 2];
  36365. this.angularSensibility = 2000.0;
  36366. this.previousPosition = null;
  36367. }
  36368. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  36369. var _this = this;
  36370. var engine = this.camera.getEngine();
  36371. if (!this._pointerInput) {
  36372. this._pointerInput = function (p, s) {
  36373. var evt = p.event;
  36374. if (engine.isInVRExclusivePointerMode) {
  36375. return;
  36376. }
  36377. if (!_this.touchEnabled && evt.pointerType === "touch") {
  36378. return;
  36379. }
  36380. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  36381. return;
  36382. }
  36383. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && evt.srcElement) {
  36384. try {
  36385. evt.srcElement.setPointerCapture(evt.pointerId);
  36386. }
  36387. catch (e) {
  36388. //Nothing to do with the error. Execution will continue.
  36389. }
  36390. _this.previousPosition = {
  36391. x: evt.clientX,
  36392. y: evt.clientY
  36393. };
  36394. if (!noPreventDefault) {
  36395. evt.preventDefault();
  36396. element.focus();
  36397. }
  36398. }
  36399. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && evt.srcElement) {
  36400. try {
  36401. evt.srcElement.releasePointerCapture(evt.pointerId);
  36402. }
  36403. catch (e) {
  36404. //Nothing to do with the error.
  36405. }
  36406. _this.previousPosition = null;
  36407. if (!noPreventDefault) {
  36408. evt.preventDefault();
  36409. }
  36410. }
  36411. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  36412. if (!_this.previousPosition || engine.isPointerLock) {
  36413. return;
  36414. }
  36415. var offsetX = evt.clientX - _this.previousPosition.x;
  36416. var offsetY = evt.clientY - _this.previousPosition.y;
  36417. if (_this.camera.getScene().useRightHandedSystem) {
  36418. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  36419. }
  36420. else {
  36421. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  36422. }
  36423. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  36424. _this.previousPosition = {
  36425. x: evt.clientX,
  36426. y: evt.clientY
  36427. };
  36428. if (!noPreventDefault) {
  36429. evt.preventDefault();
  36430. }
  36431. }
  36432. };
  36433. }
  36434. this._onMouseMove = function (evt) {
  36435. if (!engine.isPointerLock) {
  36436. return;
  36437. }
  36438. if (engine.isInVRExclusivePointerMode) {
  36439. return;
  36440. }
  36441. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  36442. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  36443. if (_this.camera.getScene().useRightHandedSystem) {
  36444. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  36445. }
  36446. else {
  36447. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  36448. }
  36449. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  36450. _this.previousPosition = null;
  36451. if (!noPreventDefault) {
  36452. evt.preventDefault();
  36453. }
  36454. };
  36455. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  36456. element.addEventListener("mousemove", this._onMouseMove, false);
  36457. };
  36458. FreeCameraMouseInput.prototype.detachControl = function (element) {
  36459. if (this._observer && element) {
  36460. this.camera.getScene().onPointerObservable.remove(this._observer);
  36461. if (this._onMouseMove) {
  36462. element.removeEventListener("mousemove", this._onMouseMove);
  36463. }
  36464. this._observer = null;
  36465. this._onMouseMove = null;
  36466. this.previousPosition = null;
  36467. }
  36468. };
  36469. FreeCameraMouseInput.prototype.getClassName = function () {
  36470. return "FreeCameraMouseInput";
  36471. };
  36472. FreeCameraMouseInput.prototype.getSimpleName = function () {
  36473. return "mouse";
  36474. };
  36475. __decorate([
  36476. BABYLON.serialize()
  36477. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  36478. __decorate([
  36479. BABYLON.serialize()
  36480. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  36481. return FreeCameraMouseInput;
  36482. }());
  36483. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  36484. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  36485. })(BABYLON || (BABYLON = {}));
  36486. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  36487. var BABYLON;
  36488. (function (BABYLON) {
  36489. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  36490. function FreeCameraKeyboardMoveInput() {
  36491. this._keys = new Array();
  36492. this.keysUp = [38];
  36493. this.keysDown = [40];
  36494. this.keysLeft = [37];
  36495. this.keysRight = [39];
  36496. }
  36497. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  36498. var _this = this;
  36499. if (this._onCanvasBlurObserver) {
  36500. return;
  36501. }
  36502. this._scene = this.camera.getScene();
  36503. this._engine = this._scene.getEngine();
  36504. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  36505. _this._keys = [];
  36506. });
  36507. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  36508. var evt = info.event;
  36509. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  36510. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  36511. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  36512. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  36513. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  36514. var index = _this._keys.indexOf(evt.keyCode);
  36515. if (index === -1) {
  36516. _this._keys.push(evt.keyCode);
  36517. }
  36518. if (!noPreventDefault) {
  36519. evt.preventDefault();
  36520. }
  36521. }
  36522. }
  36523. else {
  36524. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  36525. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  36526. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  36527. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  36528. var index = _this._keys.indexOf(evt.keyCode);
  36529. if (index >= 0) {
  36530. _this._keys.splice(index, 1);
  36531. }
  36532. if (!noPreventDefault) {
  36533. evt.preventDefault();
  36534. }
  36535. }
  36536. }
  36537. });
  36538. };
  36539. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  36540. if (this._scene) {
  36541. if (this._onKeyboardObserver) {
  36542. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  36543. }
  36544. if (this._onCanvasBlurObserver) {
  36545. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  36546. }
  36547. this._onKeyboardObserver = null;
  36548. this._onCanvasBlurObserver = null;
  36549. }
  36550. this._keys = [];
  36551. };
  36552. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  36553. if (this._onKeyboardObserver) {
  36554. var camera = this.camera;
  36555. // Keyboard
  36556. for (var index = 0; index < this._keys.length; index++) {
  36557. var keyCode = this._keys[index];
  36558. var speed = camera._computeLocalCameraSpeed();
  36559. if (this.keysLeft.indexOf(keyCode) !== -1) {
  36560. camera._localDirection.copyFromFloats(-speed, 0, 0);
  36561. }
  36562. else if (this.keysUp.indexOf(keyCode) !== -1) {
  36563. camera._localDirection.copyFromFloats(0, 0, speed);
  36564. }
  36565. else if (this.keysRight.indexOf(keyCode) !== -1) {
  36566. camera._localDirection.copyFromFloats(speed, 0, 0);
  36567. }
  36568. else if (this.keysDown.indexOf(keyCode) !== -1) {
  36569. camera._localDirection.copyFromFloats(0, 0, -speed);
  36570. }
  36571. if (camera.getScene().useRightHandedSystem) {
  36572. camera._localDirection.z *= -1;
  36573. }
  36574. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  36575. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  36576. camera.cameraDirection.addInPlace(camera._transformedDirection);
  36577. }
  36578. }
  36579. };
  36580. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  36581. return "FreeCameraKeyboardMoveInput";
  36582. };
  36583. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  36584. this._keys = [];
  36585. };
  36586. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  36587. return "keyboard";
  36588. };
  36589. __decorate([
  36590. BABYLON.serialize()
  36591. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  36592. __decorate([
  36593. BABYLON.serialize()
  36594. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  36595. __decorate([
  36596. BABYLON.serialize()
  36597. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  36598. __decorate([
  36599. BABYLON.serialize()
  36600. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  36601. return FreeCameraKeyboardMoveInput;
  36602. }());
  36603. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  36604. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  36605. })(BABYLON || (BABYLON = {}));
  36606. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  36607. var BABYLON;
  36608. (function (BABYLON) {
  36609. var FreeCameraInputsManager = /** @class */ (function (_super) {
  36610. __extends(FreeCameraInputsManager, _super);
  36611. function FreeCameraInputsManager(camera) {
  36612. return _super.call(this, camera) || this;
  36613. }
  36614. FreeCameraInputsManager.prototype.addKeyboard = function () {
  36615. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  36616. return this;
  36617. };
  36618. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  36619. if (touchEnabled === void 0) { touchEnabled = true; }
  36620. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  36621. return this;
  36622. };
  36623. FreeCameraInputsManager.prototype.addGamepad = function () {
  36624. this.add(new BABYLON.FreeCameraGamepadInput());
  36625. return this;
  36626. };
  36627. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  36628. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  36629. return this;
  36630. };
  36631. FreeCameraInputsManager.prototype.addTouch = function () {
  36632. this.add(new BABYLON.FreeCameraTouchInput());
  36633. return this;
  36634. };
  36635. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  36636. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  36637. return this;
  36638. };
  36639. return FreeCameraInputsManager;
  36640. }(BABYLON.CameraInputsManager));
  36641. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  36642. })(BABYLON || (BABYLON = {}));
  36643. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  36644. /// <reference path="babylon.camera.ts" />
  36645. var BABYLON;
  36646. (function (BABYLON) {
  36647. var TargetCamera = /** @class */ (function (_super) {
  36648. __extends(TargetCamera, _super);
  36649. function TargetCamera(name, position, scene) {
  36650. var _this = _super.call(this, name, position, scene) || this;
  36651. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  36652. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  36653. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  36654. _this.speed = 2.0;
  36655. _this.noRotationConstraint = false;
  36656. _this.lockedTarget = null;
  36657. _this._currentTarget = BABYLON.Vector3.Zero();
  36658. _this._viewMatrix = BABYLON.Matrix.Zero();
  36659. _this._camMatrix = BABYLON.Matrix.Zero();
  36660. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  36661. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  36662. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  36663. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  36664. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  36665. _this._lookAtTemp = BABYLON.Matrix.Zero();
  36666. _this._tempMatrix = BABYLON.Matrix.Zero();
  36667. return _this;
  36668. }
  36669. TargetCamera.prototype.getFrontPosition = function (distance) {
  36670. var direction = this.getTarget().subtract(this.position);
  36671. direction.normalize();
  36672. direction.scaleInPlace(distance);
  36673. return this.globalPosition.add(direction);
  36674. };
  36675. TargetCamera.prototype._getLockedTargetPosition = function () {
  36676. if (!this.lockedTarget) {
  36677. return null;
  36678. }
  36679. if (this.lockedTarget.absolutePosition) {
  36680. this.lockedTarget.computeWorldMatrix();
  36681. }
  36682. return this.lockedTarget.absolutePosition || this.lockedTarget;
  36683. };
  36684. TargetCamera.prototype.storeState = function () {
  36685. this._storedPosition = this.position.clone();
  36686. this._storedRotation = this.rotation.clone();
  36687. if (this.rotationQuaternion) {
  36688. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  36689. }
  36690. return _super.prototype.storeState.call(this);
  36691. };
  36692. /**
  36693. * Restored camera state. You must call storeState() first
  36694. */
  36695. TargetCamera.prototype._restoreStateValues = function () {
  36696. if (!_super.prototype._restoreStateValues.call(this)) {
  36697. return false;
  36698. }
  36699. this.position = this._storedPosition.clone();
  36700. this.rotation = this._storedRotation.clone();
  36701. if (this.rotationQuaternion) {
  36702. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  36703. }
  36704. this.cameraDirection.copyFromFloats(0, 0, 0);
  36705. this.cameraRotation.copyFromFloats(0, 0);
  36706. return true;
  36707. };
  36708. // Cache
  36709. TargetCamera.prototype._initCache = function () {
  36710. _super.prototype._initCache.call(this);
  36711. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  36712. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  36713. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  36714. };
  36715. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  36716. if (!ignoreParentClass) {
  36717. _super.prototype._updateCache.call(this);
  36718. }
  36719. var lockedTargetPosition = this._getLockedTargetPosition();
  36720. if (!lockedTargetPosition) {
  36721. this._cache.lockedTarget = null;
  36722. }
  36723. else {
  36724. if (!this._cache.lockedTarget) {
  36725. this._cache.lockedTarget = lockedTargetPosition.clone();
  36726. }
  36727. else {
  36728. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  36729. }
  36730. }
  36731. this._cache.rotation.copyFrom(this.rotation);
  36732. if (this.rotationQuaternion)
  36733. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  36734. };
  36735. // Synchronized
  36736. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  36737. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  36738. return false;
  36739. }
  36740. var lockedTargetPosition = this._getLockedTargetPosition();
  36741. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  36742. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  36743. };
  36744. // Methods
  36745. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  36746. var engine = this.getEngine();
  36747. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  36748. };
  36749. // Target
  36750. TargetCamera.prototype.setTarget = function (target) {
  36751. this.upVector.normalize();
  36752. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  36753. this._camMatrix.invert();
  36754. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  36755. var vDir = target.subtract(this.position);
  36756. if (vDir.x >= 0.0) {
  36757. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  36758. }
  36759. else {
  36760. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  36761. }
  36762. this.rotation.z = 0;
  36763. if (isNaN(this.rotation.x)) {
  36764. this.rotation.x = 0;
  36765. }
  36766. if (isNaN(this.rotation.y)) {
  36767. this.rotation.y = 0;
  36768. }
  36769. if (isNaN(this.rotation.z)) {
  36770. this.rotation.z = 0;
  36771. }
  36772. if (this.rotationQuaternion) {
  36773. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  36774. }
  36775. };
  36776. /**
  36777. * Return the current target position of the camera. This value is expressed in local space.
  36778. */
  36779. TargetCamera.prototype.getTarget = function () {
  36780. return this._currentTarget;
  36781. };
  36782. TargetCamera.prototype._decideIfNeedsToMove = function () {
  36783. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  36784. };
  36785. TargetCamera.prototype._updatePosition = function () {
  36786. if (this.parent) {
  36787. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  36788. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  36789. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  36790. return;
  36791. }
  36792. this.position.addInPlace(this.cameraDirection);
  36793. };
  36794. TargetCamera.prototype._checkInputs = function () {
  36795. var needToMove = this._decideIfNeedsToMove();
  36796. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  36797. // Move
  36798. if (needToMove) {
  36799. this._updatePosition();
  36800. }
  36801. // Rotate
  36802. if (needToRotate) {
  36803. this.rotation.x += this.cameraRotation.x;
  36804. this.rotation.y += this.cameraRotation.y;
  36805. //rotate, if quaternion is set and rotation was used
  36806. if (this.rotationQuaternion) {
  36807. var len = this.rotation.lengthSquared();
  36808. if (len) {
  36809. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  36810. }
  36811. }
  36812. if (!this.noRotationConstraint) {
  36813. var limit = (Math.PI / 2) * 0.95;
  36814. if (this.rotation.x > limit)
  36815. this.rotation.x = limit;
  36816. if (this.rotation.x < -limit)
  36817. this.rotation.x = -limit;
  36818. }
  36819. }
  36820. // Inertia
  36821. if (needToMove) {
  36822. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  36823. this.cameraDirection.x = 0;
  36824. }
  36825. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  36826. this.cameraDirection.y = 0;
  36827. }
  36828. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  36829. this.cameraDirection.z = 0;
  36830. }
  36831. this.cameraDirection.scaleInPlace(this.inertia);
  36832. }
  36833. if (needToRotate) {
  36834. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  36835. this.cameraRotation.x = 0;
  36836. }
  36837. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  36838. this.cameraRotation.y = 0;
  36839. }
  36840. this.cameraRotation.scaleInPlace(this.inertia);
  36841. }
  36842. _super.prototype._checkInputs.call(this);
  36843. };
  36844. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  36845. if (this.rotationQuaternion) {
  36846. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  36847. }
  36848. else {
  36849. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  36850. }
  36851. //update the up vector!
  36852. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  36853. };
  36854. TargetCamera.prototype._getViewMatrix = function () {
  36855. if (!this.lockedTarget) {
  36856. // Compute
  36857. this._updateCameraRotationMatrix();
  36858. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  36859. // Computing target and final matrix
  36860. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  36861. }
  36862. else {
  36863. var targetPosition = this._getLockedTargetPosition();
  36864. if (targetPosition) {
  36865. this._currentTarget.copyFrom(targetPosition);
  36866. }
  36867. }
  36868. if (this.getScene().useRightHandedSystem) {
  36869. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  36870. }
  36871. else {
  36872. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  36873. }
  36874. return this._viewMatrix;
  36875. };
  36876. /**
  36877. * @override
  36878. * Override Camera.createRigCamera
  36879. */
  36880. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  36881. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  36882. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  36883. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  36884. if (!this.rotationQuaternion) {
  36885. this.rotationQuaternion = new BABYLON.Quaternion();
  36886. }
  36887. rigCamera._cameraRigParams = {};
  36888. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  36889. }
  36890. return rigCamera;
  36891. }
  36892. return null;
  36893. };
  36894. /**
  36895. * @override
  36896. * Override Camera._updateRigCameras
  36897. */
  36898. TargetCamera.prototype._updateRigCameras = function () {
  36899. var camLeft = this._rigCameras[0];
  36900. var camRight = this._rigCameras[1];
  36901. switch (this.cameraRigMode) {
  36902. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  36903. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  36904. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  36905. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  36906. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  36907. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  36908. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  36909. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  36910. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  36911. camLeft.setTarget(this.getTarget());
  36912. camRight.setTarget(this.getTarget());
  36913. break;
  36914. case BABYLON.Camera.RIG_MODE_VR:
  36915. if (camLeft.rotationQuaternion) {
  36916. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  36917. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  36918. }
  36919. else {
  36920. camLeft.rotation.copyFrom(this.rotation);
  36921. camRight.rotation.copyFrom(this.rotation);
  36922. }
  36923. camLeft.position.copyFrom(this.position);
  36924. camRight.position.copyFrom(this.position);
  36925. break;
  36926. }
  36927. _super.prototype._updateRigCameras.call(this);
  36928. };
  36929. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  36930. if (!this._rigCamTransformMatrix) {
  36931. this._rigCamTransformMatrix = new BABYLON.Matrix();
  36932. }
  36933. var target = this.getTarget();
  36934. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  36935. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  36936. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  36937. };
  36938. TargetCamera.prototype.getClassName = function () {
  36939. return "TargetCamera";
  36940. };
  36941. __decorate([
  36942. BABYLON.serializeAsVector3()
  36943. ], TargetCamera.prototype, "rotation", void 0);
  36944. __decorate([
  36945. BABYLON.serialize()
  36946. ], TargetCamera.prototype, "speed", void 0);
  36947. __decorate([
  36948. BABYLON.serializeAsMeshReference("lockedTargetId")
  36949. ], TargetCamera.prototype, "lockedTarget", void 0);
  36950. return TargetCamera;
  36951. }(BABYLON.Camera));
  36952. BABYLON.TargetCamera = TargetCamera;
  36953. })(BABYLON || (BABYLON = {}));
  36954. //# sourceMappingURL=babylon.targetCamera.js.map
  36955. var BABYLON;
  36956. (function (BABYLON) {
  36957. var FreeCamera = /** @class */ (function (_super) {
  36958. __extends(FreeCamera, _super);
  36959. function FreeCamera(name, position, scene) {
  36960. var _this = _super.call(this, name, position, scene) || this;
  36961. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  36962. _this.checkCollisions = false;
  36963. _this.applyGravity = false;
  36964. _this._needMoveForGravity = false;
  36965. _this._oldPosition = BABYLON.Vector3.Zero();
  36966. _this._diffPosition = BABYLON.Vector3.Zero();
  36967. _this._newPosition = BABYLON.Vector3.Zero();
  36968. // Collisions
  36969. _this._collisionMask = -1;
  36970. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  36971. if (collidedMesh === void 0) { collidedMesh = null; }
  36972. //TODO move this to the collision coordinator!
  36973. if (_this.getScene().workerCollisions)
  36974. newPosition.multiplyInPlace(_this._collider.radius);
  36975. var updatePosition = function (newPos) {
  36976. _this._newPosition.copyFrom(newPos);
  36977. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  36978. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  36979. _this.position.addInPlace(_this._diffPosition);
  36980. if (_this.onCollide && collidedMesh) {
  36981. _this.onCollide(collidedMesh);
  36982. }
  36983. }
  36984. };
  36985. updatePosition(newPosition);
  36986. };
  36987. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  36988. _this.inputs.addKeyboard().addMouse();
  36989. return _this;
  36990. }
  36991. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  36992. //-- begin properties for backward compatibility for inputs
  36993. get: function () {
  36994. var mouse = this.inputs.attached["mouse"];
  36995. if (mouse)
  36996. return mouse.angularSensibility;
  36997. return 0;
  36998. },
  36999. set: function (value) {
  37000. var mouse = this.inputs.attached["mouse"];
  37001. if (mouse)
  37002. mouse.angularSensibility = value;
  37003. },
  37004. enumerable: true,
  37005. configurable: true
  37006. });
  37007. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  37008. get: function () {
  37009. var keyboard = this.inputs.attached["keyboard"];
  37010. if (keyboard)
  37011. return keyboard.keysUp;
  37012. return [];
  37013. },
  37014. set: function (value) {
  37015. var keyboard = this.inputs.attached["keyboard"];
  37016. if (keyboard)
  37017. keyboard.keysUp = value;
  37018. },
  37019. enumerable: true,
  37020. configurable: true
  37021. });
  37022. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  37023. get: function () {
  37024. var keyboard = this.inputs.attached["keyboard"];
  37025. if (keyboard)
  37026. return keyboard.keysDown;
  37027. return [];
  37028. },
  37029. set: function (value) {
  37030. var keyboard = this.inputs.attached["keyboard"];
  37031. if (keyboard)
  37032. keyboard.keysDown = value;
  37033. },
  37034. enumerable: true,
  37035. configurable: true
  37036. });
  37037. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  37038. get: function () {
  37039. var keyboard = this.inputs.attached["keyboard"];
  37040. if (keyboard)
  37041. return keyboard.keysLeft;
  37042. return [];
  37043. },
  37044. set: function (value) {
  37045. var keyboard = this.inputs.attached["keyboard"];
  37046. if (keyboard)
  37047. keyboard.keysLeft = value;
  37048. },
  37049. enumerable: true,
  37050. configurable: true
  37051. });
  37052. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  37053. get: function () {
  37054. var keyboard = this.inputs.attached["keyboard"];
  37055. if (keyboard)
  37056. return keyboard.keysRight;
  37057. return [];
  37058. },
  37059. set: function (value) {
  37060. var keyboard = this.inputs.attached["keyboard"];
  37061. if (keyboard)
  37062. keyboard.keysRight = value;
  37063. },
  37064. enumerable: true,
  37065. configurable: true
  37066. });
  37067. // Controls
  37068. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  37069. this.inputs.attachElement(element, noPreventDefault);
  37070. };
  37071. FreeCamera.prototype.detachControl = function (element) {
  37072. this.inputs.detachElement(element);
  37073. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  37074. this.cameraRotation = new BABYLON.Vector2(0, 0);
  37075. };
  37076. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  37077. get: function () {
  37078. return this._collisionMask;
  37079. },
  37080. set: function (mask) {
  37081. this._collisionMask = !isNaN(mask) ? mask : -1;
  37082. },
  37083. enumerable: true,
  37084. configurable: true
  37085. });
  37086. FreeCamera.prototype._collideWithWorld = function (displacement) {
  37087. var globalPosition;
  37088. if (this.parent) {
  37089. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  37090. }
  37091. else {
  37092. globalPosition = this.position;
  37093. }
  37094. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  37095. if (!this._collider) {
  37096. this._collider = new BABYLON.Collider();
  37097. }
  37098. this._collider.radius = this.ellipsoid;
  37099. this._collider.collisionMask = this._collisionMask;
  37100. //no need for clone, as long as gravity is not on.
  37101. var actualDisplacement = displacement;
  37102. //add gravity to the direction to prevent the dual-collision checking
  37103. if (this.applyGravity) {
  37104. //this prevents mending with cameraDirection, a global variable of the free camera class.
  37105. actualDisplacement = displacement.add(this.getScene().gravity);
  37106. }
  37107. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  37108. };
  37109. FreeCamera.prototype._checkInputs = function () {
  37110. if (!this._localDirection) {
  37111. this._localDirection = BABYLON.Vector3.Zero();
  37112. this._transformedDirection = BABYLON.Vector3.Zero();
  37113. }
  37114. this.inputs.checkInputs();
  37115. _super.prototype._checkInputs.call(this);
  37116. };
  37117. FreeCamera.prototype._decideIfNeedsToMove = function () {
  37118. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  37119. };
  37120. FreeCamera.prototype._updatePosition = function () {
  37121. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  37122. this._collideWithWorld(this.cameraDirection);
  37123. }
  37124. else {
  37125. _super.prototype._updatePosition.call(this);
  37126. }
  37127. };
  37128. FreeCamera.prototype.dispose = function () {
  37129. this.inputs.clear();
  37130. _super.prototype.dispose.call(this);
  37131. };
  37132. FreeCamera.prototype.getClassName = function () {
  37133. return "FreeCamera";
  37134. };
  37135. __decorate([
  37136. BABYLON.serializeAsVector3()
  37137. ], FreeCamera.prototype, "ellipsoid", void 0);
  37138. __decorate([
  37139. BABYLON.serialize()
  37140. ], FreeCamera.prototype, "checkCollisions", void 0);
  37141. __decorate([
  37142. BABYLON.serialize()
  37143. ], FreeCamera.prototype, "applyGravity", void 0);
  37144. return FreeCamera;
  37145. }(BABYLON.TargetCamera));
  37146. BABYLON.FreeCamera = FreeCamera;
  37147. })(BABYLON || (BABYLON = {}));
  37148. //# sourceMappingURL=babylon.freeCamera.js.map
  37149. var BABYLON;
  37150. (function (BABYLON) {
  37151. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  37152. function ArcRotateCameraKeyboardMoveInput() {
  37153. this._keys = new Array();
  37154. this.keysUp = [38];
  37155. this.keysDown = [40];
  37156. this.keysLeft = [37];
  37157. this.keysRight = [39];
  37158. this.keysReset = [220];
  37159. this.panningSensibility = 50.0;
  37160. this.zoomingSensibility = 25.0;
  37161. this.useAltToZoom = true;
  37162. }
  37163. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  37164. var _this = this;
  37165. if (this._onCanvasBlurObserver) {
  37166. return;
  37167. }
  37168. this._scene = this.camera.getScene();
  37169. this._engine = this._scene.getEngine();
  37170. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  37171. _this._keys = [];
  37172. });
  37173. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  37174. var evt = info.event;
  37175. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  37176. _this._ctrlPressed = evt.ctrlKey;
  37177. _this._altPressed = evt.altKey;
  37178. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37179. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37180. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37181. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  37182. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  37183. var index = _this._keys.indexOf(evt.keyCode);
  37184. if (index === -1) {
  37185. _this._keys.push(evt.keyCode);
  37186. }
  37187. if (evt.preventDefault) {
  37188. if (!noPreventDefault) {
  37189. evt.preventDefault();
  37190. }
  37191. }
  37192. }
  37193. }
  37194. else {
  37195. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37196. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37197. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37198. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  37199. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  37200. var index = _this._keys.indexOf(evt.keyCode);
  37201. if (index >= 0) {
  37202. _this._keys.splice(index, 1);
  37203. }
  37204. if (evt.preventDefault) {
  37205. if (!noPreventDefault) {
  37206. evt.preventDefault();
  37207. }
  37208. }
  37209. }
  37210. }
  37211. });
  37212. };
  37213. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  37214. if (this._scene) {
  37215. if (this._onKeyboardObserver) {
  37216. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  37217. }
  37218. if (this._onCanvasBlurObserver) {
  37219. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  37220. }
  37221. this._onKeyboardObserver = null;
  37222. this._onCanvasBlurObserver = null;
  37223. }
  37224. this._keys = [];
  37225. };
  37226. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  37227. if (this._onKeyboardObserver) {
  37228. var camera = this.camera;
  37229. for (var index = 0; index < this._keys.length; index++) {
  37230. var keyCode = this._keys[index];
  37231. if (this.keysLeft.indexOf(keyCode) !== -1) {
  37232. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37233. camera.inertialPanningX -= 1 / this.panningSensibility;
  37234. }
  37235. else {
  37236. camera.inertialAlphaOffset -= 0.01;
  37237. }
  37238. }
  37239. else if (this.keysUp.indexOf(keyCode) !== -1) {
  37240. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37241. camera.inertialPanningY += 1 / this.panningSensibility;
  37242. }
  37243. else if (this._altPressed && this.useAltToZoom) {
  37244. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  37245. }
  37246. else {
  37247. camera.inertialBetaOffset -= 0.01;
  37248. }
  37249. }
  37250. else if (this.keysRight.indexOf(keyCode) !== -1) {
  37251. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37252. camera.inertialPanningX += 1 / this.panningSensibility;
  37253. }
  37254. else {
  37255. camera.inertialAlphaOffset += 0.01;
  37256. }
  37257. }
  37258. else if (this.keysDown.indexOf(keyCode) !== -1) {
  37259. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37260. camera.inertialPanningY -= 1 / this.panningSensibility;
  37261. }
  37262. else if (this._altPressed && this.useAltToZoom) {
  37263. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  37264. }
  37265. else {
  37266. camera.inertialBetaOffset += 0.01;
  37267. }
  37268. }
  37269. else if (this.keysReset.indexOf(keyCode) !== -1) {
  37270. camera.restoreState();
  37271. }
  37272. }
  37273. }
  37274. };
  37275. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  37276. return "ArcRotateCameraKeyboardMoveInput";
  37277. };
  37278. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  37279. return "keyboard";
  37280. };
  37281. __decorate([
  37282. BABYLON.serialize()
  37283. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  37284. __decorate([
  37285. BABYLON.serialize()
  37286. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  37287. __decorate([
  37288. BABYLON.serialize()
  37289. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  37290. __decorate([
  37291. BABYLON.serialize()
  37292. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  37293. __decorate([
  37294. BABYLON.serialize()
  37295. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  37296. __decorate([
  37297. BABYLON.serialize()
  37298. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  37299. __decorate([
  37300. BABYLON.serialize()
  37301. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  37302. __decorate([
  37303. BABYLON.serialize()
  37304. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  37305. return ArcRotateCameraKeyboardMoveInput;
  37306. }());
  37307. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  37308. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  37309. })(BABYLON || (BABYLON = {}));
  37310. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  37311. var BABYLON;
  37312. (function (BABYLON) {
  37313. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  37314. function ArcRotateCameraMouseWheelInput() {
  37315. this.wheelPrecision = 3.0;
  37316. /**
  37317. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  37318. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  37319. */
  37320. this.wheelDeltaPercentage = 0;
  37321. }
  37322. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  37323. var _this = this;
  37324. this._wheel = function (p, s) {
  37325. //sanity check - this should be a PointerWheel event.
  37326. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  37327. return;
  37328. var event = p.event;
  37329. var delta = 0;
  37330. if (event.wheelDelta) {
  37331. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  37332. }
  37333. else if (event.detail) {
  37334. delta = -event.detail / _this.wheelPrecision;
  37335. }
  37336. if (delta)
  37337. _this.camera.inertialRadiusOffset += delta;
  37338. if (event.preventDefault) {
  37339. if (!noPreventDefault) {
  37340. event.preventDefault();
  37341. }
  37342. }
  37343. };
  37344. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  37345. };
  37346. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  37347. if (this._observer && element) {
  37348. this.camera.getScene().onPointerObservable.remove(this._observer);
  37349. this._observer = null;
  37350. this._wheel = null;
  37351. }
  37352. };
  37353. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  37354. return "ArcRotateCameraMouseWheelInput";
  37355. };
  37356. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  37357. return "mousewheel";
  37358. };
  37359. __decorate([
  37360. BABYLON.serialize()
  37361. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  37362. __decorate([
  37363. BABYLON.serialize()
  37364. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  37365. return ArcRotateCameraMouseWheelInput;
  37366. }());
  37367. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  37368. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  37369. })(BABYLON || (BABYLON = {}));
  37370. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  37371. var BABYLON;
  37372. (function (BABYLON) {
  37373. var ArcRotateCameraPointersInput = /** @class */ (function () {
  37374. function ArcRotateCameraPointersInput() {
  37375. this.buttons = [0, 1, 2];
  37376. this.angularSensibilityX = 1000.0;
  37377. this.angularSensibilityY = 1000.0;
  37378. this.pinchPrecision = 12.0;
  37379. /**
  37380. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  37381. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  37382. */
  37383. this.pinchDeltaPercentage = 0;
  37384. this.panningSensibility = 1000.0;
  37385. this.multiTouchPanning = true;
  37386. this.multiTouchPanAndZoom = true;
  37387. this._isPanClick = false;
  37388. this.pinchInwards = true;
  37389. }
  37390. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  37391. var _this = this;
  37392. var engine = this.camera.getEngine();
  37393. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  37394. var pointA = null;
  37395. var pointB = null;
  37396. var previousPinchSquaredDistance = 0;
  37397. var initialDistance = 0;
  37398. var twoFingerActivityCount = 0;
  37399. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  37400. this._pointerInput = function (p, s) {
  37401. var evt = p.event;
  37402. if (engine.isInVRExclusivePointerMode) {
  37403. return;
  37404. }
  37405. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  37406. return;
  37407. }
  37408. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && evt.srcElement) {
  37409. try {
  37410. evt.srcElement.setPointerCapture(evt.pointerId);
  37411. }
  37412. catch (e) {
  37413. //Nothing to do with the error. Execution will continue.
  37414. }
  37415. // Manage panning with pan button click
  37416. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  37417. // manage pointers
  37418. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  37419. if (pointA === null) {
  37420. pointA = cacheSoloPointer;
  37421. }
  37422. else if (pointB === null) {
  37423. pointB = cacheSoloPointer;
  37424. }
  37425. if (!noPreventDefault) {
  37426. evt.preventDefault();
  37427. element.focus();
  37428. }
  37429. }
  37430. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  37431. _this.camera.restoreState();
  37432. }
  37433. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && evt.srcElement) {
  37434. try {
  37435. evt.srcElement.releasePointerCapture(evt.pointerId);
  37436. }
  37437. catch (e) {
  37438. //Nothing to do with the error.
  37439. }
  37440. cacheSoloPointer = null;
  37441. previousPinchSquaredDistance = 0;
  37442. previousMultiTouchPanPosition.isPaning = false;
  37443. previousMultiTouchPanPosition.isPinching = false;
  37444. twoFingerActivityCount = 0;
  37445. initialDistance = 0;
  37446. if (p.event.pointerType !== "touch") {
  37447. pointB = null; // Mouse and pen are mono pointer
  37448. }
  37449. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  37450. //but emptying completly pointers collection is required to fix a bug on iPhone :
  37451. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  37452. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  37453. if (engine.badOS) {
  37454. pointA = pointB = null;
  37455. }
  37456. else {
  37457. //only remove the impacted pointer in case of multitouch allowing on most
  37458. //platforms switching from rotate to zoom and pan seamlessly.
  37459. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  37460. pointA = pointB;
  37461. pointB = null;
  37462. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  37463. }
  37464. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  37465. pointB = null;
  37466. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  37467. }
  37468. else {
  37469. pointA = pointB = null;
  37470. }
  37471. }
  37472. if (!noPreventDefault) {
  37473. evt.preventDefault();
  37474. }
  37475. }
  37476. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  37477. if (!noPreventDefault) {
  37478. evt.preventDefault();
  37479. }
  37480. // One button down
  37481. if (pointA && pointB === null && cacheSoloPointer) {
  37482. if (_this.panningSensibility !== 0 &&
  37483. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  37484. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  37485. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  37486. }
  37487. else {
  37488. var offsetX = evt.clientX - cacheSoloPointer.x;
  37489. var offsetY = evt.clientY - cacheSoloPointer.y;
  37490. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  37491. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  37492. }
  37493. cacheSoloPointer.x = evt.clientX;
  37494. cacheSoloPointer.y = evt.clientY;
  37495. }
  37496. else if (pointA && pointB) {
  37497. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  37498. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  37499. ed.x = evt.clientX;
  37500. ed.y = evt.clientY;
  37501. var direction = _this.pinchInwards ? 1 : -1;
  37502. var distX = pointA.x - pointB.x;
  37503. var distY = pointA.y - pointB.y;
  37504. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  37505. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  37506. if (previousPinchSquaredDistance === 0) {
  37507. initialDistance = pinchDistance;
  37508. previousPinchSquaredDistance = pinchSquaredDistance;
  37509. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  37510. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  37511. return;
  37512. }
  37513. if (_this.multiTouchPanAndZoom) {
  37514. if (_this.pinchDeltaPercentage) {
  37515. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  37516. }
  37517. else {
  37518. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  37519. (_this.pinchPrecision *
  37520. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  37521. direction);
  37522. }
  37523. if (_this.panningSensibility !== 0) {
  37524. var pointersCenterX = (pointA.x + pointB.x) / 2;
  37525. var pointersCenterY = (pointA.y + pointB.y) / 2;
  37526. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  37527. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  37528. previousMultiTouchPanPosition.x = pointersCenterX;
  37529. previousMultiTouchPanPosition.y = pointersCenterY;
  37530. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  37531. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  37532. }
  37533. }
  37534. else {
  37535. twoFingerActivityCount++;
  37536. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  37537. if (_this.pinchDeltaPercentage) {
  37538. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  37539. }
  37540. else {
  37541. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  37542. (_this.pinchPrecision *
  37543. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  37544. direction);
  37545. }
  37546. previousMultiTouchPanPosition.isPaning = false;
  37547. previousMultiTouchPanPosition.isPinching = true;
  37548. }
  37549. else {
  37550. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  37551. if (!previousMultiTouchPanPosition.isPaning) {
  37552. previousMultiTouchPanPosition.isPaning = true;
  37553. previousMultiTouchPanPosition.isPinching = false;
  37554. previousMultiTouchPanPosition.x = ed.x;
  37555. previousMultiTouchPanPosition.y = ed.y;
  37556. return;
  37557. }
  37558. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  37559. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  37560. }
  37561. }
  37562. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  37563. previousMultiTouchPanPosition.x = ed.x;
  37564. previousMultiTouchPanPosition.y = ed.y;
  37565. }
  37566. }
  37567. previousPinchSquaredDistance = pinchSquaredDistance;
  37568. }
  37569. }
  37570. };
  37571. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  37572. this._onContextMenu = function (evt) {
  37573. evt.preventDefault();
  37574. };
  37575. if (!this.camera._useCtrlForPanning) {
  37576. element.addEventListener("contextmenu", this._onContextMenu, false);
  37577. }
  37578. this._onLostFocus = function () {
  37579. //this._keys = [];
  37580. pointA = pointB = null;
  37581. previousPinchSquaredDistance = 0;
  37582. previousMultiTouchPanPosition.isPaning = false;
  37583. previousMultiTouchPanPosition.isPinching = false;
  37584. twoFingerActivityCount = 0;
  37585. cacheSoloPointer = null;
  37586. initialDistance = 0;
  37587. };
  37588. this._onMouseMove = function (evt) {
  37589. if (!engine.isPointerLock) {
  37590. return;
  37591. }
  37592. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  37593. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  37594. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  37595. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  37596. if (!noPreventDefault) {
  37597. evt.preventDefault();
  37598. }
  37599. };
  37600. this._onGestureStart = function (e) {
  37601. if (window.MSGesture === undefined) {
  37602. return;
  37603. }
  37604. if (!_this._MSGestureHandler) {
  37605. _this._MSGestureHandler = new MSGesture();
  37606. _this._MSGestureHandler.target = element;
  37607. }
  37608. _this._MSGestureHandler.addPointer(e.pointerId);
  37609. };
  37610. this._onGesture = function (e) {
  37611. _this.camera.radius *= e.scale;
  37612. if (e.preventDefault) {
  37613. if (!noPreventDefault) {
  37614. e.stopPropagation();
  37615. e.preventDefault();
  37616. }
  37617. }
  37618. };
  37619. element.addEventListener("mousemove", this._onMouseMove, false);
  37620. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  37621. element.addEventListener("MSGestureChange", this._onGesture, false);
  37622. BABYLON.Tools.RegisterTopRootEvents([
  37623. { name: "blur", handler: this._onLostFocus }
  37624. ]);
  37625. };
  37626. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  37627. if (this._onLostFocus) {
  37628. BABYLON.Tools.UnregisterTopRootEvents([
  37629. { name: "blur", handler: this._onLostFocus }
  37630. ]);
  37631. }
  37632. if (element && this._observer) {
  37633. this.camera.getScene().onPointerObservable.remove(this._observer);
  37634. this._observer = null;
  37635. if (this._onContextMenu) {
  37636. element.removeEventListener("contextmenu", this._onContextMenu);
  37637. }
  37638. if (this._onMouseMove) {
  37639. element.removeEventListener("mousemove", this._onMouseMove);
  37640. }
  37641. if (this._onGestureStart) {
  37642. element.removeEventListener("MSPointerDown", this._onGestureStart);
  37643. }
  37644. if (this._onGesture) {
  37645. element.removeEventListener("MSGestureChange", this._onGesture);
  37646. }
  37647. this._isPanClick = false;
  37648. this.pinchInwards = true;
  37649. this._onMouseMove = null;
  37650. this._onGestureStart = null;
  37651. this._onGesture = null;
  37652. this._MSGestureHandler = null;
  37653. this._onLostFocus = null;
  37654. this._onContextMenu = null;
  37655. }
  37656. };
  37657. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  37658. return "ArcRotateCameraPointersInput";
  37659. };
  37660. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  37661. return "pointers";
  37662. };
  37663. __decorate([
  37664. BABYLON.serialize()
  37665. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  37666. __decorate([
  37667. BABYLON.serialize()
  37668. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  37669. __decorate([
  37670. BABYLON.serialize()
  37671. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  37672. __decorate([
  37673. BABYLON.serialize()
  37674. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  37675. __decorate([
  37676. BABYLON.serialize()
  37677. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  37678. __decorate([
  37679. BABYLON.serialize()
  37680. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  37681. __decorate([
  37682. BABYLON.serialize()
  37683. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  37684. __decorate([
  37685. BABYLON.serialize()
  37686. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  37687. return ArcRotateCameraPointersInput;
  37688. }());
  37689. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  37690. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  37691. })(BABYLON || (BABYLON = {}));
  37692. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  37693. /// <reference path="babylon.targetCamera.ts" />
  37694. /// <reference path="..\Tools\babylon.tools.ts" />
  37695. var BABYLON;
  37696. (function (BABYLON) {
  37697. var ArcRotateCamera = /** @class */ (function (_super) {
  37698. __extends(ArcRotateCamera, _super);
  37699. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  37700. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  37701. _this.inertialAlphaOffset = 0;
  37702. _this.inertialBetaOffset = 0;
  37703. _this.inertialRadiusOffset = 0;
  37704. _this.lowerAlphaLimit = null;
  37705. _this.upperAlphaLimit = null;
  37706. _this.lowerBetaLimit = 0.01;
  37707. _this.upperBetaLimit = Math.PI;
  37708. _this.lowerRadiusLimit = null;
  37709. _this.upperRadiusLimit = null;
  37710. _this.inertialPanningX = 0;
  37711. _this.inertialPanningY = 0;
  37712. _this.pinchToPanMaxDistance = 20;
  37713. _this.panningDistanceLimit = null;
  37714. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  37715. _this.panningInertia = 0.9;
  37716. //-- end properties for backward compatibility for inputs
  37717. _this.zoomOnFactor = 1;
  37718. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  37719. _this.allowUpsideDown = true;
  37720. _this._viewMatrix = new BABYLON.Matrix();
  37721. // Panning
  37722. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  37723. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  37724. _this.checkCollisions = false;
  37725. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  37726. _this._previousPosition = BABYLON.Vector3.Zero();
  37727. _this._collisionVelocity = BABYLON.Vector3.Zero();
  37728. _this._newPosition = BABYLON.Vector3.Zero();
  37729. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  37730. if (collidedMesh === void 0) { collidedMesh = null; }
  37731. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  37732. newPosition.multiplyInPlace(_this._collider.radius);
  37733. }
  37734. if (!collidedMesh) {
  37735. _this._previousPosition.copyFrom(_this.position);
  37736. }
  37737. else {
  37738. _this.setPosition(newPosition);
  37739. if (_this.onCollide) {
  37740. _this.onCollide(collidedMesh);
  37741. }
  37742. }
  37743. // Recompute because of constraints
  37744. var cosa = Math.cos(_this.alpha);
  37745. var sina = Math.sin(_this.alpha);
  37746. var cosb = Math.cos(_this.beta);
  37747. var sinb = Math.sin(_this.beta);
  37748. if (sinb === 0) {
  37749. sinb = 0.0001;
  37750. }
  37751. var target = _this._getTargetPosition();
  37752. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  37753. _this.position.copyFrom(_this._newPosition);
  37754. var up = _this.upVector;
  37755. if (_this.allowUpsideDown && _this.beta < 0) {
  37756. up = up.clone();
  37757. up = up.negate();
  37758. }
  37759. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  37760. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  37761. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  37762. _this._collisionTriggered = false;
  37763. };
  37764. _this._target = BABYLON.Vector3.Zero();
  37765. if (target) {
  37766. _this.setTarget(target);
  37767. }
  37768. _this.alpha = alpha;
  37769. _this.beta = beta;
  37770. _this.radius = radius;
  37771. _this.getViewMatrix();
  37772. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  37773. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  37774. return _this;
  37775. }
  37776. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  37777. get: function () {
  37778. return this._target;
  37779. },
  37780. set: function (value) {
  37781. this.setTarget(value);
  37782. },
  37783. enumerable: true,
  37784. configurable: true
  37785. });
  37786. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  37787. //-- begin properties for backward compatibility for inputs
  37788. get: function () {
  37789. var pointers = this.inputs.attached["pointers"];
  37790. if (pointers)
  37791. return pointers.angularSensibilityX;
  37792. return 0;
  37793. },
  37794. set: function (value) {
  37795. var pointers = this.inputs.attached["pointers"];
  37796. if (pointers) {
  37797. pointers.angularSensibilityX = value;
  37798. }
  37799. },
  37800. enumerable: true,
  37801. configurable: true
  37802. });
  37803. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  37804. get: function () {
  37805. var pointers = this.inputs.attached["pointers"];
  37806. if (pointers)
  37807. return pointers.angularSensibilityY;
  37808. return 0;
  37809. },
  37810. set: function (value) {
  37811. var pointers = this.inputs.attached["pointers"];
  37812. if (pointers) {
  37813. pointers.angularSensibilityY = value;
  37814. }
  37815. },
  37816. enumerable: true,
  37817. configurable: true
  37818. });
  37819. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  37820. get: function () {
  37821. var pointers = this.inputs.attached["pointers"];
  37822. if (pointers)
  37823. return pointers.pinchPrecision;
  37824. return 0;
  37825. },
  37826. set: function (value) {
  37827. var pointers = this.inputs.attached["pointers"];
  37828. if (pointers) {
  37829. pointers.pinchPrecision = value;
  37830. }
  37831. },
  37832. enumerable: true,
  37833. configurable: true
  37834. });
  37835. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  37836. get: function () {
  37837. var pointers = this.inputs.attached["pointers"];
  37838. if (pointers)
  37839. return pointers.pinchDeltaPercentage;
  37840. return 0;
  37841. },
  37842. set: function (value) {
  37843. var pointers = this.inputs.attached["pointers"];
  37844. if (pointers) {
  37845. pointers.pinchDeltaPercentage = value;
  37846. }
  37847. },
  37848. enumerable: true,
  37849. configurable: true
  37850. });
  37851. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  37852. get: function () {
  37853. var pointers = this.inputs.attached["pointers"];
  37854. if (pointers)
  37855. return pointers.panningSensibility;
  37856. return 0;
  37857. },
  37858. set: function (value) {
  37859. var pointers = this.inputs.attached["pointers"];
  37860. if (pointers) {
  37861. pointers.panningSensibility = value;
  37862. }
  37863. },
  37864. enumerable: true,
  37865. configurable: true
  37866. });
  37867. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  37868. get: function () {
  37869. var keyboard = this.inputs.attached["keyboard"];
  37870. if (keyboard)
  37871. return keyboard.keysUp;
  37872. return [];
  37873. },
  37874. set: function (value) {
  37875. var keyboard = this.inputs.attached["keyboard"];
  37876. if (keyboard)
  37877. keyboard.keysUp = value;
  37878. },
  37879. enumerable: true,
  37880. configurable: true
  37881. });
  37882. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  37883. get: function () {
  37884. var keyboard = this.inputs.attached["keyboard"];
  37885. if (keyboard)
  37886. return keyboard.keysDown;
  37887. return [];
  37888. },
  37889. set: function (value) {
  37890. var keyboard = this.inputs.attached["keyboard"];
  37891. if (keyboard)
  37892. keyboard.keysDown = value;
  37893. },
  37894. enumerable: true,
  37895. configurable: true
  37896. });
  37897. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  37898. get: function () {
  37899. var keyboard = this.inputs.attached["keyboard"];
  37900. if (keyboard)
  37901. return keyboard.keysLeft;
  37902. return [];
  37903. },
  37904. set: function (value) {
  37905. var keyboard = this.inputs.attached["keyboard"];
  37906. if (keyboard)
  37907. keyboard.keysLeft = value;
  37908. },
  37909. enumerable: true,
  37910. configurable: true
  37911. });
  37912. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  37913. get: function () {
  37914. var keyboard = this.inputs.attached["keyboard"];
  37915. if (keyboard)
  37916. return keyboard.keysRight;
  37917. return [];
  37918. },
  37919. set: function (value) {
  37920. var keyboard = this.inputs.attached["keyboard"];
  37921. if (keyboard)
  37922. keyboard.keysRight = value;
  37923. },
  37924. enumerable: true,
  37925. configurable: true
  37926. });
  37927. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  37928. get: function () {
  37929. var mousewheel = this.inputs.attached["mousewheel"];
  37930. if (mousewheel)
  37931. return mousewheel.wheelPrecision;
  37932. return 0;
  37933. },
  37934. set: function (value) {
  37935. var mousewheel = this.inputs.attached["mousewheel"];
  37936. if (mousewheel)
  37937. mousewheel.wheelPrecision = value;
  37938. },
  37939. enumerable: true,
  37940. configurable: true
  37941. });
  37942. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  37943. get: function () {
  37944. var mousewheel = this.inputs.attached["mousewheel"];
  37945. if (mousewheel)
  37946. return mousewheel.wheelDeltaPercentage;
  37947. return 0;
  37948. },
  37949. set: function (value) {
  37950. var mousewheel = this.inputs.attached["mousewheel"];
  37951. if (mousewheel)
  37952. mousewheel.wheelDeltaPercentage = value;
  37953. },
  37954. enumerable: true,
  37955. configurable: true
  37956. });
  37957. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  37958. get: function () {
  37959. return this._bouncingBehavior;
  37960. },
  37961. enumerable: true,
  37962. configurable: true
  37963. });
  37964. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  37965. get: function () {
  37966. return this._bouncingBehavior != null;
  37967. },
  37968. set: function (value) {
  37969. if (value === this.useBouncingBehavior) {
  37970. return;
  37971. }
  37972. if (value) {
  37973. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  37974. this.addBehavior(this._bouncingBehavior);
  37975. }
  37976. else if (this._bouncingBehavior) {
  37977. this.removeBehavior(this._bouncingBehavior);
  37978. this._bouncingBehavior = null;
  37979. }
  37980. },
  37981. enumerable: true,
  37982. configurable: true
  37983. });
  37984. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  37985. get: function () {
  37986. return this._framingBehavior;
  37987. },
  37988. enumerable: true,
  37989. configurable: true
  37990. });
  37991. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  37992. get: function () {
  37993. return this._framingBehavior != null;
  37994. },
  37995. set: function (value) {
  37996. if (value === this.useFramingBehavior) {
  37997. return;
  37998. }
  37999. if (value) {
  38000. this._framingBehavior = new BABYLON.FramingBehavior();
  38001. this.addBehavior(this._framingBehavior);
  38002. }
  38003. else if (this._framingBehavior) {
  38004. this.removeBehavior(this._framingBehavior);
  38005. this._framingBehavior = null;
  38006. }
  38007. },
  38008. enumerable: true,
  38009. configurable: true
  38010. });
  38011. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  38012. get: function () {
  38013. return this._autoRotationBehavior;
  38014. },
  38015. enumerable: true,
  38016. configurable: true
  38017. });
  38018. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  38019. get: function () {
  38020. return this._autoRotationBehavior != null;
  38021. },
  38022. set: function (value) {
  38023. if (value === this.useAutoRotationBehavior) {
  38024. return;
  38025. }
  38026. if (value) {
  38027. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  38028. this.addBehavior(this._autoRotationBehavior);
  38029. }
  38030. else if (this._autoRotationBehavior) {
  38031. this.removeBehavior(this._autoRotationBehavior);
  38032. this._autoRotationBehavior = null;
  38033. }
  38034. },
  38035. enumerable: true,
  38036. configurable: true
  38037. });
  38038. // Cache
  38039. ArcRotateCamera.prototype._initCache = function () {
  38040. _super.prototype._initCache.call(this);
  38041. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38042. this._cache.alpha = undefined;
  38043. this._cache.beta = undefined;
  38044. this._cache.radius = undefined;
  38045. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  38046. };
  38047. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  38048. if (!ignoreParentClass) {
  38049. _super.prototype._updateCache.call(this);
  38050. }
  38051. this._cache._target.copyFrom(this._getTargetPosition());
  38052. this._cache.alpha = this.alpha;
  38053. this._cache.beta = this.beta;
  38054. this._cache.radius = this.radius;
  38055. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  38056. };
  38057. ArcRotateCamera.prototype._getTargetPosition = function () {
  38058. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  38059. var pos = this._targetHost.getAbsolutePosition();
  38060. if (this._targetBoundingCenter) {
  38061. pos.addToRef(this._targetBoundingCenter, this._target);
  38062. }
  38063. else {
  38064. this._target.copyFrom(pos);
  38065. }
  38066. }
  38067. var lockedTargetPosition = this._getLockedTargetPosition();
  38068. if (lockedTargetPosition) {
  38069. return lockedTargetPosition;
  38070. }
  38071. return this._target;
  38072. };
  38073. ArcRotateCamera.prototype.storeState = function () {
  38074. this._storedAlpha = this.alpha;
  38075. this._storedBeta = this.beta;
  38076. this._storedRadius = this.radius;
  38077. this._storedTarget = this._getTargetPosition().clone();
  38078. return _super.prototype.storeState.call(this);
  38079. };
  38080. /**
  38081. * Restored camera state. You must call storeState() first
  38082. */
  38083. ArcRotateCamera.prototype._restoreStateValues = function () {
  38084. if (!_super.prototype._restoreStateValues.call(this)) {
  38085. return false;
  38086. }
  38087. this.alpha = this._storedAlpha;
  38088. this.beta = this._storedBeta;
  38089. this.radius = this._storedRadius;
  38090. this.setTarget(this._storedTarget.clone());
  38091. this.inertialAlphaOffset = 0;
  38092. this.inertialBetaOffset = 0;
  38093. this.inertialRadiusOffset = 0;
  38094. this.inertialPanningX = 0;
  38095. this.inertialPanningY = 0;
  38096. return true;
  38097. };
  38098. // Synchronized
  38099. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  38100. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  38101. return false;
  38102. return this._cache._target.equals(this._getTargetPosition())
  38103. && this._cache.alpha === this.alpha
  38104. && this._cache.beta === this.beta
  38105. && this._cache.radius === this.radius
  38106. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  38107. };
  38108. // Methods
  38109. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  38110. var _this = this;
  38111. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  38112. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  38113. this._useCtrlForPanning = useCtrlForPanning;
  38114. this._panningMouseButton = panningMouseButton;
  38115. this.inputs.attachElement(element, noPreventDefault);
  38116. this._reset = function () {
  38117. _this.inertialAlphaOffset = 0;
  38118. _this.inertialBetaOffset = 0;
  38119. _this.inertialRadiusOffset = 0;
  38120. _this.inertialPanningX = 0;
  38121. _this.inertialPanningY = 0;
  38122. };
  38123. };
  38124. ArcRotateCamera.prototype.detachControl = function (element) {
  38125. this.inputs.detachElement(element);
  38126. if (this._reset) {
  38127. this._reset();
  38128. }
  38129. };
  38130. ArcRotateCamera.prototype._checkInputs = function () {
  38131. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  38132. if (this._collisionTriggered) {
  38133. return;
  38134. }
  38135. this.inputs.checkInputs();
  38136. // Inertia
  38137. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  38138. if (this.getScene().useRightHandedSystem) {
  38139. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  38140. }
  38141. else {
  38142. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  38143. }
  38144. this.beta += this.inertialBetaOffset;
  38145. this.radius -= this.inertialRadiusOffset;
  38146. this.inertialAlphaOffset *= this.inertia;
  38147. this.inertialBetaOffset *= this.inertia;
  38148. this.inertialRadiusOffset *= this.inertia;
  38149. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  38150. this.inertialAlphaOffset = 0;
  38151. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  38152. this.inertialBetaOffset = 0;
  38153. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  38154. this.inertialRadiusOffset = 0;
  38155. }
  38156. // Panning inertia
  38157. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  38158. if (!this._localDirection) {
  38159. this._localDirection = BABYLON.Vector3.Zero();
  38160. this._transformedDirection = BABYLON.Vector3.Zero();
  38161. }
  38162. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  38163. this._localDirection.multiplyInPlace(this.panningAxis);
  38164. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  38165. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  38166. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  38167. if (!this.panningAxis.y) {
  38168. this._transformedDirection.y = 0;
  38169. }
  38170. if (!this._targetHost) {
  38171. if (this.panningDistanceLimit) {
  38172. this._transformedDirection.addInPlace(this._target);
  38173. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  38174. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  38175. this._target.copyFrom(this._transformedDirection);
  38176. }
  38177. }
  38178. else {
  38179. this._target.addInPlace(this._transformedDirection);
  38180. }
  38181. }
  38182. this.inertialPanningX *= this.panningInertia;
  38183. this.inertialPanningY *= this.panningInertia;
  38184. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  38185. this.inertialPanningX = 0;
  38186. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  38187. this.inertialPanningY = 0;
  38188. }
  38189. // Limits
  38190. this._checkLimits();
  38191. _super.prototype._checkInputs.call(this);
  38192. };
  38193. ArcRotateCamera.prototype._checkLimits = function () {
  38194. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  38195. if (this.allowUpsideDown && this.beta > Math.PI) {
  38196. this.beta = this.beta - (2 * Math.PI);
  38197. }
  38198. }
  38199. else {
  38200. if (this.beta < this.lowerBetaLimit) {
  38201. this.beta = this.lowerBetaLimit;
  38202. }
  38203. }
  38204. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  38205. if (this.allowUpsideDown && this.beta < -Math.PI) {
  38206. this.beta = this.beta + (2 * Math.PI);
  38207. }
  38208. }
  38209. else {
  38210. if (this.beta > this.upperBetaLimit) {
  38211. this.beta = this.upperBetaLimit;
  38212. }
  38213. }
  38214. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  38215. this.alpha = this.lowerAlphaLimit;
  38216. }
  38217. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  38218. this.alpha = this.upperAlphaLimit;
  38219. }
  38220. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  38221. this.radius = this.lowerRadiusLimit;
  38222. }
  38223. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  38224. this.radius = this.upperRadiusLimit;
  38225. }
  38226. };
  38227. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  38228. var radiusv3 = this.position.subtract(this._getTargetPosition());
  38229. this.radius = radiusv3.length();
  38230. if (this.radius === 0) {
  38231. this.radius = 0.0001; // Just to avoid division by zero
  38232. }
  38233. // Alpha
  38234. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  38235. if (radiusv3.z < 0) {
  38236. this.alpha = 2 * Math.PI - this.alpha;
  38237. }
  38238. // Beta
  38239. this.beta = Math.acos(radiusv3.y / this.radius);
  38240. this._checkLimits();
  38241. };
  38242. ArcRotateCamera.prototype.setPosition = function (position) {
  38243. if (this.position.equals(position)) {
  38244. return;
  38245. }
  38246. this.position.copyFrom(position);
  38247. this.rebuildAnglesAndRadius();
  38248. };
  38249. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  38250. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  38251. if (allowSamePosition === void 0) { allowSamePosition = false; }
  38252. if (target.getBoundingInfo) {
  38253. if (toBoundingCenter) {
  38254. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  38255. }
  38256. else {
  38257. this._targetBoundingCenter = null;
  38258. }
  38259. this._targetHost = target;
  38260. this._target = this._getTargetPosition();
  38261. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  38262. }
  38263. else {
  38264. var newTarget = target;
  38265. var currentTarget = this._getTargetPosition();
  38266. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  38267. return;
  38268. }
  38269. this._targetHost = null;
  38270. this._target = newTarget;
  38271. this._targetBoundingCenter = null;
  38272. this.onMeshTargetChangedObservable.notifyObservers(null);
  38273. }
  38274. this.rebuildAnglesAndRadius();
  38275. };
  38276. ArcRotateCamera.prototype._getViewMatrix = function () {
  38277. // Compute
  38278. var cosa = Math.cos(this.alpha);
  38279. var sina = Math.sin(this.alpha);
  38280. var cosb = Math.cos(this.beta);
  38281. var sinb = Math.sin(this.beta);
  38282. if (sinb === 0) {
  38283. sinb = 0.0001;
  38284. }
  38285. var target = this._getTargetPosition();
  38286. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  38287. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  38288. if (!this._collider) {
  38289. this._collider = new BABYLON.Collider();
  38290. }
  38291. this._collider.radius = this.collisionRadius;
  38292. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  38293. this._collisionTriggered = true;
  38294. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  38295. }
  38296. else {
  38297. this.position.copyFrom(this._newPosition);
  38298. var up = this.upVector;
  38299. if (this.allowUpsideDown && sinb < 0) {
  38300. up = up.clone();
  38301. up = up.negate();
  38302. }
  38303. if (this.getScene().useRightHandedSystem) {
  38304. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  38305. }
  38306. else {
  38307. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  38308. }
  38309. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  38310. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  38311. }
  38312. this._currentTarget = target;
  38313. return this._viewMatrix;
  38314. };
  38315. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  38316. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  38317. meshes = meshes || this.getScene().meshes;
  38318. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  38319. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  38320. this.radius = distance * this.zoomOnFactor;
  38321. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  38322. };
  38323. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  38324. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  38325. var meshesOrMinMaxVector;
  38326. var distance;
  38327. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  38328. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  38329. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  38330. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  38331. }
  38332. else {
  38333. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  38334. meshesOrMinMaxVector = minMaxVectorAndDistance;
  38335. distance = minMaxVectorAndDistance.distance;
  38336. }
  38337. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  38338. if (!doNotUpdateMaxZ) {
  38339. this.maxZ = distance * 2;
  38340. }
  38341. };
  38342. /**
  38343. * @override
  38344. * Override Camera.createRigCamera
  38345. */
  38346. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  38347. var alphaShift = 0;
  38348. switch (this.cameraRigMode) {
  38349. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  38350. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  38351. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  38352. case BABYLON.Camera.RIG_MODE_VR:
  38353. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  38354. break;
  38355. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  38356. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  38357. break;
  38358. }
  38359. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  38360. rigCam._cameraRigParams = {};
  38361. return rigCam;
  38362. };
  38363. /**
  38364. * @override
  38365. * Override Camera._updateRigCameras
  38366. */
  38367. ArcRotateCamera.prototype._updateRigCameras = function () {
  38368. var camLeft = this._rigCameras[0];
  38369. var camRight = this._rigCameras[1];
  38370. camLeft.beta = camRight.beta = this.beta;
  38371. camLeft.radius = camRight.radius = this.radius;
  38372. switch (this.cameraRigMode) {
  38373. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  38374. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  38375. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  38376. case BABYLON.Camera.RIG_MODE_VR:
  38377. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  38378. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  38379. break;
  38380. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  38381. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  38382. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  38383. break;
  38384. }
  38385. _super.prototype._updateRigCameras.call(this);
  38386. };
  38387. ArcRotateCamera.prototype.dispose = function () {
  38388. this.inputs.clear();
  38389. _super.prototype.dispose.call(this);
  38390. };
  38391. ArcRotateCamera.prototype.getClassName = function () {
  38392. return "ArcRotateCamera";
  38393. };
  38394. __decorate([
  38395. BABYLON.serialize()
  38396. ], ArcRotateCamera.prototype, "alpha", void 0);
  38397. __decorate([
  38398. BABYLON.serialize()
  38399. ], ArcRotateCamera.prototype, "beta", void 0);
  38400. __decorate([
  38401. BABYLON.serialize()
  38402. ], ArcRotateCamera.prototype, "radius", void 0);
  38403. __decorate([
  38404. BABYLON.serializeAsVector3("target")
  38405. ], ArcRotateCamera.prototype, "_target", void 0);
  38406. __decorate([
  38407. BABYLON.serialize()
  38408. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  38409. __decorate([
  38410. BABYLON.serialize()
  38411. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  38412. __decorate([
  38413. BABYLON.serialize()
  38414. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  38415. __decorate([
  38416. BABYLON.serialize()
  38417. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  38418. __decorate([
  38419. BABYLON.serialize()
  38420. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  38421. __decorate([
  38422. BABYLON.serialize()
  38423. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  38424. __decorate([
  38425. BABYLON.serialize()
  38426. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  38427. __decorate([
  38428. BABYLON.serialize()
  38429. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  38430. __decorate([
  38431. BABYLON.serialize()
  38432. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  38433. __decorate([
  38434. BABYLON.serialize()
  38435. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  38436. __decorate([
  38437. BABYLON.serialize()
  38438. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  38439. __decorate([
  38440. BABYLON.serialize()
  38441. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  38442. __decorate([
  38443. BABYLON.serialize()
  38444. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  38445. __decorate([
  38446. BABYLON.serializeAsVector3()
  38447. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  38448. __decorate([
  38449. BABYLON.serialize()
  38450. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  38451. __decorate([
  38452. BABYLON.serialize()
  38453. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  38454. __decorate([
  38455. BABYLON.serialize()
  38456. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  38457. return ArcRotateCamera;
  38458. }(BABYLON.TargetCamera));
  38459. BABYLON.ArcRotateCamera = ArcRotateCamera;
  38460. })(BABYLON || (BABYLON = {}));
  38461. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  38462. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  38463. var BABYLON;
  38464. (function (BABYLON) {
  38465. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  38466. __extends(ArcRotateCameraInputsManager, _super);
  38467. function ArcRotateCameraInputsManager(camera) {
  38468. return _super.call(this, camera) || this;
  38469. }
  38470. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  38471. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  38472. return this;
  38473. };
  38474. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  38475. this.add(new BABYLON.ArcRotateCameraPointersInput());
  38476. return this;
  38477. };
  38478. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  38479. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  38480. return this;
  38481. };
  38482. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  38483. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  38484. return this;
  38485. };
  38486. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  38487. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  38488. return this;
  38489. };
  38490. return ArcRotateCameraInputsManager;
  38491. }(BABYLON.CameraInputsManager));
  38492. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  38493. })(BABYLON || (BABYLON = {}));
  38494. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  38495. var BABYLON;
  38496. (function (BABYLON) {
  38497. var HemisphericLight = /** @class */ (function (_super) {
  38498. __extends(HemisphericLight, _super);
  38499. /**
  38500. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  38501. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  38502. * The HemisphericLight can't cast shadows.
  38503. * Documentation : http://doc.babylonjs.com/tutorials/lights
  38504. */
  38505. function HemisphericLight(name, direction, scene) {
  38506. var _this = _super.call(this, name, scene) || this;
  38507. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  38508. _this.direction = direction || BABYLON.Vector3.Up();
  38509. return _this;
  38510. }
  38511. HemisphericLight.prototype._buildUniformLayout = function () {
  38512. this._uniformBuffer.addUniform("vLightData", 4);
  38513. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  38514. this._uniformBuffer.addUniform("vLightSpecular", 3);
  38515. this._uniformBuffer.addUniform("vLightGround", 3);
  38516. this._uniformBuffer.addUniform("shadowsInfo", 3);
  38517. this._uniformBuffer.addUniform("depthValues", 2);
  38518. this._uniformBuffer.create();
  38519. };
  38520. /**
  38521. * Returns the string "HemisphericLight".
  38522. */
  38523. HemisphericLight.prototype.getClassName = function () {
  38524. return "HemisphericLight";
  38525. };
  38526. /**
  38527. * Sets the HemisphericLight direction towards the passed target (Vector3).
  38528. * Returns the updated direction.
  38529. */
  38530. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  38531. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  38532. return this.direction;
  38533. };
  38534. HemisphericLight.prototype.getShadowGenerator = function () {
  38535. return null;
  38536. };
  38537. /**
  38538. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  38539. * Returns the HemisphericLight.
  38540. */
  38541. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  38542. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  38543. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  38544. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  38545. return this;
  38546. };
  38547. HemisphericLight.prototype._getWorldMatrix = function () {
  38548. if (!this._worldMatrix) {
  38549. this._worldMatrix = BABYLON.Matrix.Identity();
  38550. }
  38551. return this._worldMatrix;
  38552. };
  38553. /**
  38554. * Returns the integer 3.
  38555. */
  38556. HemisphericLight.prototype.getTypeID = function () {
  38557. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  38558. };
  38559. __decorate([
  38560. BABYLON.serializeAsColor3()
  38561. ], HemisphericLight.prototype, "groundColor", void 0);
  38562. __decorate([
  38563. BABYLON.serializeAsVector3()
  38564. ], HemisphericLight.prototype, "direction", void 0);
  38565. return HemisphericLight;
  38566. }(BABYLON.Light));
  38567. BABYLON.HemisphericLight = HemisphericLight;
  38568. })(BABYLON || (BABYLON = {}));
  38569. //# sourceMappingURL=babylon.hemisphericLight.js.map
  38570. var BABYLON;
  38571. (function (BABYLON) {
  38572. var ShadowLight = /** @class */ (function (_super) {
  38573. __extends(ShadowLight, _super);
  38574. function ShadowLight() {
  38575. var _this = _super !== null && _super.apply(this, arguments) || this;
  38576. _this._needProjectionMatrixCompute = true;
  38577. return _this;
  38578. }
  38579. Object.defineProperty(ShadowLight.prototype, "direction", {
  38580. get: function () {
  38581. return this._direction;
  38582. },
  38583. set: function (value) {
  38584. this._direction = value;
  38585. },
  38586. enumerable: true,
  38587. configurable: true
  38588. });
  38589. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  38590. get: function () {
  38591. return this._shadowMinZ;
  38592. },
  38593. set: function (value) {
  38594. this._shadowMinZ = value;
  38595. this.forceProjectionMatrixCompute();
  38596. },
  38597. enumerable: true,
  38598. configurable: true
  38599. });
  38600. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  38601. get: function () {
  38602. return this._shadowMaxZ;
  38603. },
  38604. set: function (value) {
  38605. this._shadowMaxZ = value;
  38606. this.forceProjectionMatrixCompute();
  38607. },
  38608. enumerable: true,
  38609. configurable: true
  38610. });
  38611. /**
  38612. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  38613. */
  38614. ShadowLight.prototype.computeTransformedInformation = function () {
  38615. if (this.parent && this.parent.getWorldMatrix) {
  38616. if (!this.transformedPosition) {
  38617. this.transformedPosition = BABYLON.Vector3.Zero();
  38618. }
  38619. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  38620. // In case the direction is present.
  38621. if (this.direction) {
  38622. if (!this.transformedDirection) {
  38623. this.transformedDirection = BABYLON.Vector3.Zero();
  38624. }
  38625. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  38626. }
  38627. return true;
  38628. }
  38629. return false;
  38630. };
  38631. /**
  38632. * Return the depth scale used for the shadow map.
  38633. */
  38634. ShadowLight.prototype.getDepthScale = function () {
  38635. return 50.0;
  38636. };
  38637. /**
  38638. * Returns the light direction (Vector3) for any passed face index.
  38639. */
  38640. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  38641. return this.transformedDirection ? this.transformedDirection : this.direction;
  38642. };
  38643. /**
  38644. * Returns the DirectionalLight absolute position in the World.
  38645. */
  38646. ShadowLight.prototype.getAbsolutePosition = function () {
  38647. return this.transformedPosition ? this.transformedPosition : this.position;
  38648. };
  38649. /**
  38650. * Sets the DirectionalLight direction toward the passed target (Vector3).
  38651. * Returns the updated DirectionalLight direction (Vector3).
  38652. */
  38653. ShadowLight.prototype.setDirectionToTarget = function (target) {
  38654. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  38655. return this.direction;
  38656. };
  38657. /**
  38658. * Returns the light rotation (Vector3).
  38659. */
  38660. ShadowLight.prototype.getRotation = function () {
  38661. this.direction.normalize();
  38662. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  38663. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  38664. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  38665. };
  38666. /**
  38667. * Boolean : false by default.
  38668. */
  38669. ShadowLight.prototype.needCube = function () {
  38670. return false;
  38671. };
  38672. /**
  38673. * Specifies wether or not the projection matrix should be recomputed this frame.
  38674. */
  38675. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  38676. return this._needProjectionMatrixCompute;
  38677. };
  38678. /**
  38679. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  38680. */
  38681. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  38682. this._needProjectionMatrixCompute = true;
  38683. };
  38684. /**
  38685. * Get the world matrix of the sahdow lights.
  38686. */
  38687. ShadowLight.prototype._getWorldMatrix = function () {
  38688. if (!this._worldMatrix) {
  38689. this._worldMatrix = BABYLON.Matrix.Identity();
  38690. }
  38691. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  38692. return this._worldMatrix;
  38693. };
  38694. /**
  38695. * Gets the minZ used for shadow according to both the scene and the light.
  38696. * @param activeCamera
  38697. */
  38698. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  38699. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  38700. };
  38701. /**
  38702. * Gets the maxZ used for shadow according to both the scene and the light.
  38703. * @param activeCamera
  38704. */
  38705. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  38706. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  38707. };
  38708. /**
  38709. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  38710. * Returns the light.
  38711. */
  38712. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  38713. if (this.customProjectionMatrixBuilder) {
  38714. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  38715. }
  38716. else {
  38717. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  38718. }
  38719. return this;
  38720. };
  38721. __decorate([
  38722. BABYLON.serializeAsVector3()
  38723. ], ShadowLight.prototype, "position", void 0);
  38724. __decorate([
  38725. BABYLON.serializeAsVector3()
  38726. ], ShadowLight.prototype, "direction", null);
  38727. __decorate([
  38728. BABYLON.serialize()
  38729. ], ShadowLight.prototype, "shadowMinZ", null);
  38730. __decorate([
  38731. BABYLON.serialize()
  38732. ], ShadowLight.prototype, "shadowMaxZ", null);
  38733. return ShadowLight;
  38734. }(BABYLON.Light));
  38735. BABYLON.ShadowLight = ShadowLight;
  38736. })(BABYLON || (BABYLON = {}));
  38737. //# sourceMappingURL=babylon.shadowLight.js.map
  38738. var BABYLON;
  38739. (function (BABYLON) {
  38740. var PointLight = /** @class */ (function (_super) {
  38741. __extends(PointLight, _super);
  38742. /**
  38743. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  38744. * A PointLight emits the light in every direction.
  38745. * It can cast shadows.
  38746. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  38747. * ```javascript
  38748. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  38749. * ```
  38750. * Documentation : http://doc.babylonjs.com/tutorials/lights
  38751. */
  38752. function PointLight(name, position, scene) {
  38753. var _this = _super.call(this, name, scene) || this;
  38754. _this._shadowAngle = Math.PI / 2;
  38755. _this.position = position;
  38756. return _this;
  38757. }
  38758. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  38759. /**
  38760. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  38761. * This specifies what angle the shadow will use to be created.
  38762. *
  38763. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  38764. */
  38765. get: function () {
  38766. return this._shadowAngle;
  38767. },
  38768. /**
  38769. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  38770. * This specifies what angle the shadow will use to be created.
  38771. *
  38772. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  38773. */
  38774. set: function (value) {
  38775. this._shadowAngle = value;
  38776. this.forceProjectionMatrixCompute();
  38777. },
  38778. enumerable: true,
  38779. configurable: true
  38780. });
  38781. Object.defineProperty(PointLight.prototype, "direction", {
  38782. get: function () {
  38783. return this._direction;
  38784. },
  38785. /**
  38786. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  38787. */
  38788. set: function (value) {
  38789. var previousNeedCube = this.needCube();
  38790. this._direction = value;
  38791. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  38792. this._shadowGenerator.recreateShadowMap();
  38793. }
  38794. },
  38795. enumerable: true,
  38796. configurable: true
  38797. });
  38798. /**
  38799. * Returns the string "PointLight"
  38800. */
  38801. PointLight.prototype.getClassName = function () {
  38802. return "PointLight";
  38803. };
  38804. /**
  38805. * Returns the integer 0.
  38806. */
  38807. PointLight.prototype.getTypeID = function () {
  38808. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  38809. };
  38810. /**
  38811. * Specifies wether or not the shadowmap should be a cube texture.
  38812. */
  38813. PointLight.prototype.needCube = function () {
  38814. return !this.direction;
  38815. };
  38816. /**
  38817. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  38818. */
  38819. PointLight.prototype.getShadowDirection = function (faceIndex) {
  38820. if (this.direction) {
  38821. return _super.prototype.getShadowDirection.call(this, faceIndex);
  38822. }
  38823. else {
  38824. switch (faceIndex) {
  38825. case 0:
  38826. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  38827. case 1:
  38828. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  38829. case 2:
  38830. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  38831. case 3:
  38832. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  38833. case 4:
  38834. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  38835. case 5:
  38836. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  38837. }
  38838. }
  38839. return BABYLON.Vector3.Zero();
  38840. };
  38841. /**
  38842. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  38843. * - fov = PI / 2
  38844. * - aspect ratio : 1.0
  38845. * - z-near and far equal to the active camera minZ and maxZ.
  38846. * Returns the PointLight.
  38847. */
  38848. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  38849. var activeCamera = this.getScene().activeCamera;
  38850. if (!activeCamera) {
  38851. return;
  38852. }
  38853. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  38854. };
  38855. PointLight.prototype._buildUniformLayout = function () {
  38856. this._uniformBuffer.addUniform("vLightData", 4);
  38857. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  38858. this._uniformBuffer.addUniform("vLightSpecular", 3);
  38859. this._uniformBuffer.addUniform("shadowsInfo", 3);
  38860. this._uniformBuffer.addUniform("depthValues", 2);
  38861. this._uniformBuffer.create();
  38862. };
  38863. /**
  38864. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  38865. * Returns the PointLight.
  38866. */
  38867. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  38868. if (this.computeTransformedInformation()) {
  38869. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  38870. return this;
  38871. }
  38872. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  38873. return this;
  38874. };
  38875. __decorate([
  38876. BABYLON.serialize()
  38877. ], PointLight.prototype, "shadowAngle", null);
  38878. return PointLight;
  38879. }(BABYLON.ShadowLight));
  38880. BABYLON.PointLight = PointLight;
  38881. })(BABYLON || (BABYLON = {}));
  38882. //# sourceMappingURL=babylon.pointLight.js.map
  38883. /// <reference path="babylon.light.ts" />
  38884. var BABYLON;
  38885. (function (BABYLON) {
  38886. var DirectionalLight = /** @class */ (function (_super) {
  38887. __extends(DirectionalLight, _super);
  38888. /**
  38889. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  38890. * The directional light is emitted from everywhere in the given direction.
  38891. * It can cast shawdows.
  38892. * Documentation : http://doc.babylonjs.com/tutorials/lights
  38893. */
  38894. function DirectionalLight(name, direction, scene) {
  38895. var _this = _super.call(this, name, scene) || this;
  38896. _this._shadowFrustumSize = 0;
  38897. _this._shadowOrthoScale = 0.5;
  38898. _this.autoUpdateExtends = true;
  38899. // Cache
  38900. _this._orthoLeft = Number.MAX_VALUE;
  38901. _this._orthoRight = Number.MIN_VALUE;
  38902. _this._orthoTop = Number.MIN_VALUE;
  38903. _this._orthoBottom = Number.MAX_VALUE;
  38904. _this.position = direction.scale(-1.0);
  38905. _this.direction = direction;
  38906. return _this;
  38907. }
  38908. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  38909. /**
  38910. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  38911. */
  38912. get: function () {
  38913. return this._shadowFrustumSize;
  38914. },
  38915. /**
  38916. * Specifies a fix frustum size for the shadow generation.
  38917. */
  38918. set: function (value) {
  38919. this._shadowFrustumSize = value;
  38920. this.forceProjectionMatrixCompute();
  38921. },
  38922. enumerable: true,
  38923. configurable: true
  38924. });
  38925. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  38926. get: function () {
  38927. return this._shadowOrthoScale;
  38928. },
  38929. set: function (value) {
  38930. this._shadowOrthoScale = value;
  38931. this.forceProjectionMatrixCompute();
  38932. },
  38933. enumerable: true,
  38934. configurable: true
  38935. });
  38936. /**
  38937. * Returns the string "DirectionalLight".
  38938. */
  38939. DirectionalLight.prototype.getClassName = function () {
  38940. return "DirectionalLight";
  38941. };
  38942. /**
  38943. * Returns the integer 1.
  38944. */
  38945. DirectionalLight.prototype.getTypeID = function () {
  38946. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  38947. };
  38948. /**
  38949. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  38950. * Returns the DirectionalLight Shadow projection matrix.
  38951. */
  38952. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  38953. if (this.shadowFrustumSize > 0) {
  38954. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  38955. }
  38956. else {
  38957. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  38958. }
  38959. };
  38960. /**
  38961. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  38962. * Returns the DirectionalLight Shadow projection matrix.
  38963. */
  38964. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  38965. var activeCamera = this.getScene().activeCamera;
  38966. if (!activeCamera) {
  38967. return;
  38968. }
  38969. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  38970. };
  38971. /**
  38972. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  38973. * Returns the DirectionalLight Shadow projection matrix.
  38974. */
  38975. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  38976. var activeCamera = this.getScene().activeCamera;
  38977. if (!activeCamera) {
  38978. return;
  38979. }
  38980. // Check extends
  38981. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  38982. var tempVector3 = BABYLON.Vector3.Zero();
  38983. this._orthoLeft = Number.MAX_VALUE;
  38984. this._orthoRight = Number.MIN_VALUE;
  38985. this._orthoTop = Number.MIN_VALUE;
  38986. this._orthoBottom = Number.MAX_VALUE;
  38987. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  38988. var mesh = renderList[meshIndex];
  38989. if (!mesh) {
  38990. continue;
  38991. }
  38992. var boundingInfo = mesh.getBoundingInfo();
  38993. if (!boundingInfo) {
  38994. continue;
  38995. }
  38996. var boundingBox = boundingInfo.boundingBox;
  38997. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  38998. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  38999. if (tempVector3.x < this._orthoLeft)
  39000. this._orthoLeft = tempVector3.x;
  39001. if (tempVector3.y < this._orthoBottom)
  39002. this._orthoBottom = tempVector3.y;
  39003. if (tempVector3.x > this._orthoRight)
  39004. this._orthoRight = tempVector3.x;
  39005. if (tempVector3.y > this._orthoTop)
  39006. this._orthoTop = tempVector3.y;
  39007. }
  39008. }
  39009. }
  39010. var xOffset = this._orthoRight - this._orthoLeft;
  39011. var yOffset = this._orthoTop - this._orthoBottom;
  39012. 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);
  39013. };
  39014. DirectionalLight.prototype._buildUniformLayout = function () {
  39015. this._uniformBuffer.addUniform("vLightData", 4);
  39016. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39017. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39018. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39019. this._uniformBuffer.addUniform("depthValues", 2);
  39020. this._uniformBuffer.create();
  39021. };
  39022. /**
  39023. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  39024. * Returns the DirectionalLight.
  39025. */
  39026. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  39027. if (this.computeTransformedInformation()) {
  39028. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  39029. return this;
  39030. }
  39031. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  39032. return this;
  39033. };
  39034. /**
  39035. * Gets the minZ used for shadow according to both the scene and the light.
  39036. *
  39037. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  39038. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  39039. * @param activeCamera
  39040. */
  39041. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  39042. return 1;
  39043. };
  39044. /**
  39045. * Gets the maxZ used for shadow according to both the scene and the light.
  39046. *
  39047. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  39048. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  39049. * @param activeCamera
  39050. */
  39051. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  39052. return 1;
  39053. };
  39054. __decorate([
  39055. BABYLON.serialize()
  39056. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  39057. __decorate([
  39058. BABYLON.serialize()
  39059. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  39060. __decorate([
  39061. BABYLON.serialize()
  39062. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  39063. return DirectionalLight;
  39064. }(BABYLON.ShadowLight));
  39065. BABYLON.DirectionalLight = DirectionalLight;
  39066. })(BABYLON || (BABYLON = {}));
  39067. //# sourceMappingURL=babylon.directionalLight.js.map
  39068. var BABYLON;
  39069. (function (BABYLON) {
  39070. var SpotLight = /** @class */ (function (_super) {
  39071. __extends(SpotLight, _super);
  39072. /**
  39073. * Creates a SpotLight object in the scene with the passed parameters :
  39074. * - `position` (Vector3) is the initial SpotLight position,
  39075. * - `direction` (Vector3) is the initial SpotLight direction,
  39076. * - `angle` (float, in radians) is the spot light cone angle,
  39077. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  39078. * A spot light is a simply light oriented cone.
  39079. * It can cast shadows.
  39080. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39081. */
  39082. function SpotLight(name, position, direction, angle, exponent, scene) {
  39083. var _this = _super.call(this, name, scene) || this;
  39084. _this.position = position;
  39085. _this.direction = direction;
  39086. _this.angle = angle;
  39087. _this.exponent = exponent;
  39088. return _this;
  39089. }
  39090. Object.defineProperty(SpotLight.prototype, "angle", {
  39091. get: function () {
  39092. return this._angle;
  39093. },
  39094. set: function (value) {
  39095. this._angle = value;
  39096. this.forceProjectionMatrixCompute();
  39097. },
  39098. enumerable: true,
  39099. configurable: true
  39100. });
  39101. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  39102. get: function () {
  39103. return this._shadowAngleScale;
  39104. },
  39105. /**
  39106. * Allows scaling the angle of the light for shadow generation only.
  39107. */
  39108. set: function (value) {
  39109. this._shadowAngleScale = value;
  39110. this.forceProjectionMatrixCompute();
  39111. },
  39112. enumerable: true,
  39113. configurable: true
  39114. });
  39115. /**
  39116. * Returns the string "SpotLight".
  39117. */
  39118. SpotLight.prototype.getClassName = function () {
  39119. return "SpotLight";
  39120. };
  39121. /**
  39122. * Returns the integer 2.
  39123. */
  39124. SpotLight.prototype.getTypeID = function () {
  39125. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  39126. };
  39127. /**
  39128. * 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.
  39129. * Returns the SpotLight.
  39130. */
  39131. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39132. var activeCamera = this.getScene().activeCamera;
  39133. if (!activeCamera) {
  39134. return;
  39135. }
  39136. this._shadowAngleScale = this._shadowAngleScale || 1;
  39137. var angle = this._shadowAngleScale * this._angle;
  39138. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  39139. };
  39140. SpotLight.prototype._buildUniformLayout = function () {
  39141. this._uniformBuffer.addUniform("vLightData", 4);
  39142. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39143. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39144. this._uniformBuffer.addUniform("vLightDirection", 3);
  39145. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39146. this._uniformBuffer.addUniform("depthValues", 2);
  39147. this._uniformBuffer.create();
  39148. };
  39149. /**
  39150. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  39151. * Return the SpotLight.
  39152. */
  39153. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  39154. var normalizeDirection;
  39155. if (this.computeTransformedInformation()) {
  39156. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  39157. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  39158. }
  39159. else {
  39160. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  39161. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  39162. }
  39163. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  39164. return this;
  39165. };
  39166. __decorate([
  39167. BABYLON.serialize()
  39168. ], SpotLight.prototype, "angle", null);
  39169. __decorate([
  39170. BABYLON.serialize()
  39171. /**
  39172. * Allows scaling the angle of the light for shadow generation only.
  39173. */
  39174. ], SpotLight.prototype, "shadowAngleScale", null);
  39175. __decorate([
  39176. BABYLON.serialize()
  39177. ], SpotLight.prototype, "exponent", void 0);
  39178. return SpotLight;
  39179. }(BABYLON.ShadowLight));
  39180. BABYLON.SpotLight = SpotLight;
  39181. })(BABYLON || (BABYLON = {}));
  39182. //# sourceMappingURL=babylon.spotLight.js.map
  39183. var BABYLON;
  39184. (function (BABYLON) {
  39185. var AnimationRange = /** @class */ (function () {
  39186. function AnimationRange(name, from, to) {
  39187. this.name = name;
  39188. this.from = from;
  39189. this.to = to;
  39190. }
  39191. AnimationRange.prototype.clone = function () {
  39192. return new AnimationRange(this.name, this.from, this.to);
  39193. };
  39194. return AnimationRange;
  39195. }());
  39196. BABYLON.AnimationRange = AnimationRange;
  39197. /**
  39198. * Composed of a frame, and an action function
  39199. */
  39200. var AnimationEvent = /** @class */ (function () {
  39201. function AnimationEvent(frame, action, onlyOnce) {
  39202. this.frame = frame;
  39203. this.action = action;
  39204. this.onlyOnce = onlyOnce;
  39205. this.isDone = false;
  39206. }
  39207. return AnimationEvent;
  39208. }());
  39209. BABYLON.AnimationEvent = AnimationEvent;
  39210. var PathCursor = /** @class */ (function () {
  39211. function PathCursor(path) {
  39212. this.path = path;
  39213. this._onchange = new Array();
  39214. this.value = 0;
  39215. this.animations = new Array();
  39216. }
  39217. PathCursor.prototype.getPoint = function () {
  39218. var point = this.path.getPointAtLengthPosition(this.value);
  39219. return new BABYLON.Vector3(point.x, 0, point.y);
  39220. };
  39221. PathCursor.prototype.moveAhead = function (step) {
  39222. if (step === void 0) { step = 0.002; }
  39223. this.move(step);
  39224. return this;
  39225. };
  39226. PathCursor.prototype.moveBack = function (step) {
  39227. if (step === void 0) { step = 0.002; }
  39228. this.move(-step);
  39229. return this;
  39230. };
  39231. PathCursor.prototype.move = function (step) {
  39232. if (Math.abs(step) > 1) {
  39233. throw "step size should be less than 1.";
  39234. }
  39235. this.value += step;
  39236. this.ensureLimits();
  39237. this.raiseOnChange();
  39238. return this;
  39239. };
  39240. PathCursor.prototype.ensureLimits = function () {
  39241. while (this.value > 1) {
  39242. this.value -= 1;
  39243. }
  39244. while (this.value < 0) {
  39245. this.value += 1;
  39246. }
  39247. return this;
  39248. };
  39249. // used by animation engine
  39250. PathCursor.prototype.raiseOnChange = function () {
  39251. var _this = this;
  39252. this._onchange.forEach(function (f) { return f(_this); });
  39253. return this;
  39254. };
  39255. PathCursor.prototype.onchange = function (f) {
  39256. this._onchange.push(f);
  39257. return this;
  39258. };
  39259. return PathCursor;
  39260. }());
  39261. BABYLON.PathCursor = PathCursor;
  39262. var Animation = /** @class */ (function () {
  39263. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  39264. this.name = name;
  39265. this.targetProperty = targetProperty;
  39266. this.framePerSecond = framePerSecond;
  39267. this.dataType = dataType;
  39268. this.loopMode = loopMode;
  39269. this.enableBlending = enableBlending;
  39270. this._runtimeAnimations = new Array();
  39271. // The set of event that will be linked to this animation
  39272. this._events = new Array();
  39273. this.blendingSpeed = 0.01;
  39274. this._ranges = {};
  39275. this.targetPropertyPath = targetProperty.split(".");
  39276. this.dataType = dataType;
  39277. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  39278. }
  39279. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  39280. var dataType = undefined;
  39281. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  39282. dataType = Animation.ANIMATIONTYPE_FLOAT;
  39283. }
  39284. else if (from instanceof BABYLON.Quaternion) {
  39285. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  39286. }
  39287. else if (from instanceof BABYLON.Vector3) {
  39288. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  39289. }
  39290. else if (from instanceof BABYLON.Vector2) {
  39291. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  39292. }
  39293. else if (from instanceof BABYLON.Color3) {
  39294. dataType = Animation.ANIMATIONTYPE_COLOR3;
  39295. }
  39296. else if (from instanceof BABYLON.Size) {
  39297. dataType = Animation.ANIMATIONTYPE_SIZE;
  39298. }
  39299. if (dataType == undefined) {
  39300. return null;
  39301. }
  39302. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  39303. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  39304. animation.setKeys(keys);
  39305. if (easingFunction !== undefined) {
  39306. animation.setEasingFunction(easingFunction);
  39307. }
  39308. return animation;
  39309. };
  39310. /**
  39311. * Sets up an animation.
  39312. * @param property the property to animate
  39313. * @param animationType the animation type to apply
  39314. * @param easingFunction the easing function used in the animation
  39315. * @returns The created animation
  39316. */
  39317. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  39318. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  39319. animation.setEasingFunction(easingFunction);
  39320. return animation;
  39321. };
  39322. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  39323. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  39324. if (!animation) {
  39325. return null;
  39326. }
  39327. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  39328. };
  39329. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  39330. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  39331. if (!animation) {
  39332. return null;
  39333. }
  39334. node.animations.push(animation);
  39335. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  39336. };
  39337. /**
  39338. * Transition property of the Camera to the target Value.
  39339. * @param property The property to transition
  39340. * @param targetValue The target Value of the property
  39341. * @param host The object where the property to animate belongs
  39342. * @param scene Scene used to run the animation
  39343. * @param frameRate Framerate (in frame/s) to use
  39344. * @param transition The transition type we want to use
  39345. * @param duration The duration of the animation, in milliseconds
  39346. * @param onAnimationEnd Call back trigger at the end of the animation.
  39347. */
  39348. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  39349. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  39350. if (duration <= 0) {
  39351. host[property] = targetValue;
  39352. if (onAnimationEnd) {
  39353. onAnimationEnd();
  39354. }
  39355. return null;
  39356. }
  39357. var endFrame = frameRate * (duration / 1000);
  39358. transition.setKeys([{
  39359. frame: 0,
  39360. value: host[property].clone ? host[property].clone() : host[property]
  39361. },
  39362. {
  39363. frame: endFrame,
  39364. value: targetValue
  39365. }]);
  39366. if (!host.animations) {
  39367. host.animations = [];
  39368. }
  39369. host.animations.push(transition);
  39370. var animation = scene.beginAnimation(host, 0, endFrame, false);
  39371. animation.onAnimationEnd = onAnimationEnd;
  39372. return animation;
  39373. };
  39374. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  39375. /**
  39376. * Return the array of runtime animations currently using this animation
  39377. */
  39378. get: function () {
  39379. return this._runtimeAnimations;
  39380. },
  39381. enumerable: true,
  39382. configurable: true
  39383. });
  39384. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  39385. get: function () {
  39386. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  39387. var runtimeAnimation = _a[_i];
  39388. if (!runtimeAnimation.isStopped) {
  39389. return true;
  39390. }
  39391. }
  39392. return false;
  39393. },
  39394. enumerable: true,
  39395. configurable: true
  39396. });
  39397. // Methods
  39398. /**
  39399. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  39400. */
  39401. Animation.prototype.toString = function (fullDetails) {
  39402. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  39403. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  39404. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  39405. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  39406. if (fullDetails) {
  39407. ret += ", Ranges: {";
  39408. var first = true;
  39409. for (var name in this._ranges) {
  39410. if (first) {
  39411. ret += ", ";
  39412. first = false;
  39413. }
  39414. ret += name;
  39415. }
  39416. ret += "}";
  39417. }
  39418. return ret;
  39419. };
  39420. /**
  39421. * Add an event to this animation.
  39422. */
  39423. Animation.prototype.addEvent = function (event) {
  39424. this._events.push(event);
  39425. };
  39426. /**
  39427. * Remove all events found at the given frame
  39428. * @param frame
  39429. */
  39430. Animation.prototype.removeEvents = function (frame) {
  39431. for (var index = 0; index < this._events.length; index++) {
  39432. if (this._events[index].frame === frame) {
  39433. this._events.splice(index, 1);
  39434. index--;
  39435. }
  39436. }
  39437. };
  39438. Animation.prototype.getEvents = function () {
  39439. return this._events;
  39440. };
  39441. Animation.prototype.createRange = function (name, from, to) {
  39442. // check name not already in use; could happen for bones after serialized
  39443. if (!this._ranges[name]) {
  39444. this._ranges[name] = new AnimationRange(name, from, to);
  39445. }
  39446. };
  39447. Animation.prototype.deleteRange = function (name, deleteFrames) {
  39448. if (deleteFrames === void 0) { deleteFrames = true; }
  39449. var range = this._ranges[name];
  39450. if (!range) {
  39451. return;
  39452. }
  39453. if (deleteFrames) {
  39454. var from = range.from;
  39455. var to = range.to;
  39456. // this loop MUST go high to low for multiple splices to work
  39457. for (var key = this._keys.length - 1; key >= 0; key--) {
  39458. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  39459. this._keys.splice(key, 1);
  39460. }
  39461. }
  39462. }
  39463. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  39464. };
  39465. Animation.prototype.getRange = function (name) {
  39466. return this._ranges[name];
  39467. };
  39468. Animation.prototype.getKeys = function () {
  39469. return this._keys;
  39470. };
  39471. Animation.prototype.getHighestFrame = function () {
  39472. var ret = 0;
  39473. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  39474. if (ret < this._keys[key].frame) {
  39475. ret = this._keys[key].frame;
  39476. }
  39477. }
  39478. return ret;
  39479. };
  39480. Animation.prototype.getEasingFunction = function () {
  39481. return this._easingFunction;
  39482. };
  39483. Animation.prototype.setEasingFunction = function (easingFunction) {
  39484. this._easingFunction = easingFunction;
  39485. };
  39486. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  39487. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  39488. };
  39489. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  39490. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  39491. };
  39492. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  39493. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  39494. };
  39495. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  39496. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  39497. };
  39498. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  39499. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  39500. };
  39501. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  39502. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  39503. };
  39504. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  39505. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  39506. };
  39507. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  39508. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  39509. };
  39510. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  39511. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  39512. };
  39513. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  39514. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  39515. };
  39516. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  39517. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  39518. };
  39519. Animation.prototype.clone = function () {
  39520. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  39521. clone.enableBlending = this.enableBlending;
  39522. clone.blendingSpeed = this.blendingSpeed;
  39523. if (this._keys) {
  39524. clone.setKeys(this._keys);
  39525. }
  39526. if (this._ranges) {
  39527. clone._ranges = {};
  39528. for (var name in this._ranges) {
  39529. var range = this._ranges[name];
  39530. if (!range) {
  39531. continue;
  39532. }
  39533. clone._ranges[name] = range.clone();
  39534. }
  39535. }
  39536. return clone;
  39537. };
  39538. Animation.prototype.setKeys = function (values) {
  39539. this._keys = values.slice(0);
  39540. };
  39541. Animation.prototype.serialize = function () {
  39542. var serializationObject = {};
  39543. serializationObject.name = this.name;
  39544. serializationObject.property = this.targetProperty;
  39545. serializationObject.framePerSecond = this.framePerSecond;
  39546. serializationObject.dataType = this.dataType;
  39547. serializationObject.loopBehavior = this.loopMode;
  39548. serializationObject.enableBlending = this.enableBlending;
  39549. serializationObject.blendingSpeed = this.blendingSpeed;
  39550. var dataType = this.dataType;
  39551. serializationObject.keys = [];
  39552. var keys = this.getKeys();
  39553. for (var index = 0; index < keys.length; index++) {
  39554. var animationKey = keys[index];
  39555. var key = {};
  39556. key.frame = animationKey.frame;
  39557. switch (dataType) {
  39558. case Animation.ANIMATIONTYPE_FLOAT:
  39559. key.values = [animationKey.value];
  39560. break;
  39561. case Animation.ANIMATIONTYPE_QUATERNION:
  39562. case Animation.ANIMATIONTYPE_MATRIX:
  39563. case Animation.ANIMATIONTYPE_VECTOR3:
  39564. case Animation.ANIMATIONTYPE_COLOR3:
  39565. key.values = animationKey.value.asArray();
  39566. break;
  39567. }
  39568. serializationObject.keys.push(key);
  39569. }
  39570. serializationObject.ranges = [];
  39571. for (var name in this._ranges) {
  39572. var source = this._ranges[name];
  39573. if (!source) {
  39574. continue;
  39575. }
  39576. var range = {};
  39577. range.name = name;
  39578. range.from = source.from;
  39579. range.to = source.to;
  39580. serializationObject.ranges.push(range);
  39581. }
  39582. return serializationObject;
  39583. };
  39584. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  39585. get: function () {
  39586. return Animation._ANIMATIONTYPE_FLOAT;
  39587. },
  39588. enumerable: true,
  39589. configurable: true
  39590. });
  39591. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  39592. get: function () {
  39593. return Animation._ANIMATIONTYPE_VECTOR3;
  39594. },
  39595. enumerable: true,
  39596. configurable: true
  39597. });
  39598. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  39599. get: function () {
  39600. return Animation._ANIMATIONTYPE_VECTOR2;
  39601. },
  39602. enumerable: true,
  39603. configurable: true
  39604. });
  39605. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  39606. get: function () {
  39607. return Animation._ANIMATIONTYPE_SIZE;
  39608. },
  39609. enumerable: true,
  39610. configurable: true
  39611. });
  39612. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  39613. get: function () {
  39614. return Animation._ANIMATIONTYPE_QUATERNION;
  39615. },
  39616. enumerable: true,
  39617. configurable: true
  39618. });
  39619. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  39620. get: function () {
  39621. return Animation._ANIMATIONTYPE_MATRIX;
  39622. },
  39623. enumerable: true,
  39624. configurable: true
  39625. });
  39626. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  39627. get: function () {
  39628. return Animation._ANIMATIONTYPE_COLOR3;
  39629. },
  39630. enumerable: true,
  39631. configurable: true
  39632. });
  39633. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  39634. get: function () {
  39635. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  39636. },
  39637. enumerable: true,
  39638. configurable: true
  39639. });
  39640. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  39641. get: function () {
  39642. return Animation._ANIMATIONLOOPMODE_CYCLE;
  39643. },
  39644. enumerable: true,
  39645. configurable: true
  39646. });
  39647. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  39648. get: function () {
  39649. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  39650. },
  39651. enumerable: true,
  39652. configurable: true
  39653. });
  39654. Animation.Parse = function (parsedAnimation) {
  39655. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  39656. var dataType = parsedAnimation.dataType;
  39657. var keys = [];
  39658. var data;
  39659. var index;
  39660. if (parsedAnimation.enableBlending) {
  39661. animation.enableBlending = parsedAnimation.enableBlending;
  39662. }
  39663. if (parsedAnimation.blendingSpeed) {
  39664. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  39665. }
  39666. for (index = 0; index < parsedAnimation.keys.length; index++) {
  39667. var key = parsedAnimation.keys[index];
  39668. var inTangent;
  39669. var outTangent;
  39670. switch (dataType) {
  39671. case Animation.ANIMATIONTYPE_FLOAT:
  39672. data = key.values[0];
  39673. if (key.values.length >= 1) {
  39674. inTangent = key.values[1];
  39675. }
  39676. if (key.values.length >= 2) {
  39677. outTangent = key.values[2];
  39678. }
  39679. break;
  39680. case Animation.ANIMATIONTYPE_QUATERNION:
  39681. data = BABYLON.Quaternion.FromArray(key.values);
  39682. if (key.values.length >= 8) {
  39683. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  39684. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  39685. inTangent = _inTangent;
  39686. }
  39687. }
  39688. if (key.values.length >= 12) {
  39689. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  39690. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  39691. outTangent = _outTangent;
  39692. }
  39693. }
  39694. break;
  39695. case Animation.ANIMATIONTYPE_MATRIX:
  39696. data = BABYLON.Matrix.FromArray(key.values);
  39697. break;
  39698. case Animation.ANIMATIONTYPE_COLOR3:
  39699. data = BABYLON.Color3.FromArray(key.values);
  39700. break;
  39701. case Animation.ANIMATIONTYPE_VECTOR3:
  39702. default:
  39703. data = BABYLON.Vector3.FromArray(key.values);
  39704. break;
  39705. }
  39706. var keyData = {};
  39707. keyData.frame = key.frame;
  39708. keyData.value = data;
  39709. if (inTangent != undefined) {
  39710. keyData.inTangent = inTangent;
  39711. }
  39712. if (outTangent != undefined) {
  39713. keyData.outTangent = outTangent;
  39714. }
  39715. keys.push(keyData);
  39716. }
  39717. animation.setKeys(keys);
  39718. if (parsedAnimation.ranges) {
  39719. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  39720. data = parsedAnimation.ranges[index];
  39721. animation.createRange(data.name, data.from, data.to);
  39722. }
  39723. }
  39724. return animation;
  39725. };
  39726. Animation.AppendSerializedAnimations = function (source, destination) {
  39727. if (source.animations) {
  39728. destination.animations = [];
  39729. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  39730. var animation = source.animations[animationIndex];
  39731. destination.animations.push(animation.serialize());
  39732. }
  39733. }
  39734. };
  39735. Animation.AllowMatricesInterpolation = false;
  39736. // Statics
  39737. Animation._ANIMATIONTYPE_FLOAT = 0;
  39738. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  39739. Animation._ANIMATIONTYPE_QUATERNION = 2;
  39740. Animation._ANIMATIONTYPE_MATRIX = 3;
  39741. Animation._ANIMATIONTYPE_COLOR3 = 4;
  39742. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  39743. Animation._ANIMATIONTYPE_SIZE = 6;
  39744. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  39745. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  39746. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  39747. return Animation;
  39748. }());
  39749. BABYLON.Animation = Animation;
  39750. })(BABYLON || (BABYLON = {}));
  39751. //# sourceMappingURL=babylon.animation.js.map
  39752. var BABYLON;
  39753. (function (BABYLON) {
  39754. var RuntimeAnimation = /** @class */ (function () {
  39755. function RuntimeAnimation(target, animation) {
  39756. this._offsetsCache = {};
  39757. this._highLimitsCache = {};
  39758. this._stopped = false;
  39759. this._blendingFactor = 0;
  39760. this._ratioOffset = 0;
  39761. this._animation = animation;
  39762. this._target = target;
  39763. animation._runtimeAnimations.push(this);
  39764. }
  39765. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  39766. get: function () {
  39767. return this._animation;
  39768. },
  39769. enumerable: true,
  39770. configurable: true
  39771. });
  39772. RuntimeAnimation.prototype.reset = function () {
  39773. this._offsetsCache = {};
  39774. this._highLimitsCache = {};
  39775. this.currentFrame = 0;
  39776. this._blendingFactor = 0;
  39777. this._originalBlendValue = null;
  39778. };
  39779. RuntimeAnimation.prototype.isStopped = function () {
  39780. return this._stopped;
  39781. };
  39782. RuntimeAnimation.prototype.dispose = function () {
  39783. var index = this._animation.runtimeAnimations.indexOf(this);
  39784. if (index > -1) {
  39785. this._animation.runtimeAnimations.splice(index, 1);
  39786. }
  39787. };
  39788. RuntimeAnimation.prototype._getKeyValue = function (value) {
  39789. if (typeof value === "function") {
  39790. return value();
  39791. }
  39792. return value;
  39793. };
  39794. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  39795. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  39796. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  39797. }
  39798. this.currentFrame = currentFrame;
  39799. var keys = this._animation.getKeys();
  39800. // Try to get a hash to find the right key
  39801. 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));
  39802. if (keys[startKeyIndex].frame >= currentFrame) {
  39803. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  39804. startKeyIndex--;
  39805. }
  39806. }
  39807. for (var key = startKeyIndex; key < keys.length; key++) {
  39808. var endKey = keys[key + 1];
  39809. if (endKey.frame >= currentFrame) {
  39810. var startKey = keys[key];
  39811. var startValue = this._getKeyValue(startKey.value);
  39812. var endValue = this._getKeyValue(endKey.value);
  39813. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  39814. var frameDelta = endKey.frame - startKey.frame;
  39815. // gradient : percent of currentFrame between the frame inf and the frame sup
  39816. var gradient = (currentFrame - startKey.frame) / frameDelta;
  39817. // check for easingFunction and correction of gradient
  39818. var easingFunction = this._animation.getEasingFunction();
  39819. if (easingFunction != null) {
  39820. gradient = easingFunction.ease(gradient);
  39821. }
  39822. switch (this._animation.dataType) {
  39823. // Float
  39824. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  39825. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  39826. switch (loopMode) {
  39827. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  39828. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  39829. return floatValue;
  39830. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  39831. return offsetValue * repeatCount + floatValue;
  39832. }
  39833. break;
  39834. // Quaternion
  39835. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  39836. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  39837. switch (loopMode) {
  39838. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  39839. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  39840. return quatValue;
  39841. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  39842. return quatValue.add(offsetValue.scale(repeatCount));
  39843. }
  39844. return quatValue;
  39845. // Vector3
  39846. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  39847. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  39848. switch (loopMode) {
  39849. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  39850. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  39851. return vec3Value;
  39852. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  39853. return vec3Value.add(offsetValue.scale(repeatCount));
  39854. }
  39855. // Vector2
  39856. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  39857. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  39858. switch (loopMode) {
  39859. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  39860. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  39861. return vec2Value;
  39862. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  39863. return vec2Value.add(offsetValue.scale(repeatCount));
  39864. }
  39865. // Size
  39866. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  39867. switch (loopMode) {
  39868. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  39869. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  39870. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  39871. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  39872. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  39873. }
  39874. // Color3
  39875. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  39876. switch (loopMode) {
  39877. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  39878. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  39879. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  39880. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  39881. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  39882. }
  39883. // Matrix
  39884. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  39885. switch (loopMode) {
  39886. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  39887. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  39888. if (BABYLON.Animation.AllowMatricesInterpolation) {
  39889. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  39890. }
  39891. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  39892. return startValue;
  39893. }
  39894. default:
  39895. break;
  39896. }
  39897. break;
  39898. }
  39899. }
  39900. return this._getKeyValue(keys[keys.length - 1].value);
  39901. };
  39902. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  39903. if (blend === void 0) { blend = false; }
  39904. // Set value
  39905. var path;
  39906. var destination;
  39907. var targetPropertyPath = this._animation.targetPropertyPath;
  39908. if (targetPropertyPath.length > 1) {
  39909. var property = this._target[targetPropertyPath[0]];
  39910. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  39911. property = property[targetPropertyPath[index]];
  39912. }
  39913. path = targetPropertyPath[targetPropertyPath.length - 1];
  39914. destination = property;
  39915. }
  39916. else {
  39917. path = targetPropertyPath[0];
  39918. destination = this._target;
  39919. }
  39920. // Blending
  39921. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  39922. if (!this._originalBlendValue) {
  39923. if (destination[path].clone) {
  39924. this._originalBlendValue = destination[path].clone();
  39925. }
  39926. else {
  39927. this._originalBlendValue = destination[path];
  39928. }
  39929. }
  39930. if (this._originalBlendValue.prototype) {
  39931. if (this._originalBlendValue.prototype.Lerp) {
  39932. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  39933. }
  39934. else {
  39935. destination[path] = currentValue;
  39936. }
  39937. }
  39938. else if (this._originalBlendValue.m) {
  39939. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  39940. }
  39941. else {
  39942. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  39943. }
  39944. this._blendingFactor += this._animation.blendingSpeed;
  39945. }
  39946. else {
  39947. destination[path] = currentValue;
  39948. }
  39949. if (this._target.markAsDirty) {
  39950. this._target.markAsDirty(this._animation.targetProperty);
  39951. }
  39952. };
  39953. RuntimeAnimation.prototype.goToFrame = function (frame) {
  39954. var keys = this._animation.getKeys();
  39955. if (frame < keys[0].frame) {
  39956. frame = keys[0].frame;
  39957. }
  39958. else if (frame > keys[keys.length - 1].frame) {
  39959. frame = keys[keys.length - 1].frame;
  39960. }
  39961. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  39962. this.setValue(currentValue);
  39963. };
  39964. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  39965. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  39966. this._ratioOffset = this._previousRatio - newRatio;
  39967. };
  39968. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  39969. if (blend === void 0) { blend = false; }
  39970. var targetPropertyPath = this._animation.targetPropertyPath;
  39971. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  39972. this._stopped = true;
  39973. return false;
  39974. }
  39975. var returnValue = true;
  39976. var keys = this._animation.getKeys();
  39977. // Adding a start key at frame 0 if missing
  39978. if (keys[0].frame !== 0) {
  39979. var newKey = { frame: 0, value: keys[0].value };
  39980. keys.splice(0, 0, newKey);
  39981. }
  39982. // Check limits
  39983. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  39984. from = keys[0].frame;
  39985. }
  39986. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  39987. to = keys[keys.length - 1].frame;
  39988. }
  39989. //to and from cannot be the same key
  39990. if (from === to) {
  39991. if (from > keys[0].frame) {
  39992. from--;
  39993. }
  39994. else if (to < keys[keys.length - 1].frame) {
  39995. to++;
  39996. }
  39997. }
  39998. // Compute ratio
  39999. var range = to - from;
  40000. var offsetValue;
  40001. // ratio represents the frame delta between from and to
  40002. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  40003. var highLimitValue = 0;
  40004. this._previousDelay = delay;
  40005. this._previousRatio = ratio;
  40006. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  40007. returnValue = false;
  40008. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  40009. }
  40010. else {
  40011. // Get max value if required
  40012. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  40013. var keyOffset = to.toString() + from.toString();
  40014. if (!this._offsetsCache[keyOffset]) {
  40015. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  40016. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  40017. switch (this._animation.dataType) {
  40018. // Float
  40019. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40020. this._offsetsCache[keyOffset] = toValue - fromValue;
  40021. break;
  40022. // Quaternion
  40023. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40024. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40025. break;
  40026. // Vector3
  40027. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40028. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40029. // Vector2
  40030. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40031. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40032. // Size
  40033. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40034. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40035. // Color3
  40036. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40037. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40038. default:
  40039. break;
  40040. }
  40041. this._highLimitsCache[keyOffset] = toValue;
  40042. }
  40043. highLimitValue = this._highLimitsCache[keyOffset];
  40044. offsetValue = this._offsetsCache[keyOffset];
  40045. }
  40046. }
  40047. if (offsetValue === undefined) {
  40048. switch (this._animation.dataType) {
  40049. // Float
  40050. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40051. offsetValue = 0;
  40052. break;
  40053. // Quaternion
  40054. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40055. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  40056. break;
  40057. // Vector3
  40058. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40059. offsetValue = BABYLON.Vector3.Zero();
  40060. break;
  40061. // Vector2
  40062. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40063. offsetValue = BABYLON.Vector2.Zero();
  40064. break;
  40065. // Size
  40066. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40067. offsetValue = BABYLON.Size.Zero();
  40068. break;
  40069. // Color3
  40070. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40071. offsetValue = BABYLON.Color3.Black();
  40072. }
  40073. }
  40074. // Compute value
  40075. var repeatCount = (ratio / range) >> 0;
  40076. var currentFrame = returnValue ? from + ratio % range : to;
  40077. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  40078. // Set value
  40079. this.setValue(currentValue);
  40080. // Check events
  40081. var events = this._animation.getEvents();
  40082. for (var index = 0; index < events.length; index++) {
  40083. // Make sure current frame has passed event frame and that event frame is within the current range
  40084. // Also, handle both forward and reverse animations
  40085. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  40086. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  40087. var event = events[index];
  40088. if (!event.isDone) {
  40089. // If event should be done only once, remove it.
  40090. if (event.onlyOnce) {
  40091. events.splice(index, 1);
  40092. index--;
  40093. }
  40094. event.isDone = true;
  40095. event.action();
  40096. } // Don't do anything if the event has already be done.
  40097. }
  40098. else if (events[index].isDone && !events[index].onlyOnce) {
  40099. // reset event, the animation is looping
  40100. events[index].isDone = false;
  40101. }
  40102. }
  40103. if (!returnValue) {
  40104. this._stopped = true;
  40105. }
  40106. return returnValue;
  40107. };
  40108. return RuntimeAnimation;
  40109. }());
  40110. BABYLON.RuntimeAnimation = RuntimeAnimation;
  40111. })(BABYLON || (BABYLON = {}));
  40112. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  40113. var BABYLON;
  40114. (function (BABYLON) {
  40115. var Animatable = /** @class */ (function () {
  40116. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  40117. if (fromFrame === void 0) { fromFrame = 0; }
  40118. if (toFrame === void 0) { toFrame = 100; }
  40119. if (loopAnimation === void 0) { loopAnimation = false; }
  40120. if (speedRatio === void 0) { speedRatio = 1.0; }
  40121. this.target = target;
  40122. this.fromFrame = fromFrame;
  40123. this.toFrame = toFrame;
  40124. this.loopAnimation = loopAnimation;
  40125. this.onAnimationEnd = onAnimationEnd;
  40126. this._localDelayOffset = null;
  40127. this._pausedDelay = null;
  40128. this._runtimeAnimations = new Array();
  40129. this._paused = false;
  40130. this._speedRatio = 1;
  40131. this.animationStarted = false;
  40132. if (animations) {
  40133. this.appendAnimations(target, animations);
  40134. }
  40135. this._speedRatio = speedRatio;
  40136. this._scene = scene;
  40137. scene._activeAnimatables.push(this);
  40138. }
  40139. Object.defineProperty(Animatable.prototype, "speedRatio", {
  40140. get: function () {
  40141. return this._speedRatio;
  40142. },
  40143. set: function (value) {
  40144. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  40145. var animation = this._runtimeAnimations[index];
  40146. animation._prepareForSpeedRatioChange(value);
  40147. }
  40148. this._speedRatio = value;
  40149. },
  40150. enumerable: true,
  40151. configurable: true
  40152. });
  40153. // Methods
  40154. Animatable.prototype.getAnimations = function () {
  40155. return this._runtimeAnimations;
  40156. };
  40157. Animatable.prototype.appendAnimations = function (target, animations) {
  40158. for (var index = 0; index < animations.length; index++) {
  40159. var animation = animations[index];
  40160. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  40161. }
  40162. };
  40163. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  40164. var runtimeAnimations = this._runtimeAnimations;
  40165. for (var index = 0; index < runtimeAnimations.length; index++) {
  40166. if (runtimeAnimations[index].animation.targetProperty === property) {
  40167. return runtimeAnimations[index].animation;
  40168. }
  40169. }
  40170. return null;
  40171. };
  40172. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  40173. var runtimeAnimations = this._runtimeAnimations;
  40174. for (var index = 0; index < runtimeAnimations.length; index++) {
  40175. if (runtimeAnimations[index].animation.targetProperty === property) {
  40176. return runtimeAnimations[index];
  40177. }
  40178. }
  40179. return null;
  40180. };
  40181. Animatable.prototype.reset = function () {
  40182. var runtimeAnimations = this._runtimeAnimations;
  40183. for (var index = 0; index < runtimeAnimations.length; index++) {
  40184. runtimeAnimations[index].reset();
  40185. }
  40186. this._localDelayOffset = null;
  40187. this._pausedDelay = null;
  40188. };
  40189. Animatable.prototype.enableBlending = function (blendingSpeed) {
  40190. var runtimeAnimations = this._runtimeAnimations;
  40191. for (var index = 0; index < runtimeAnimations.length; index++) {
  40192. runtimeAnimations[index].animation.enableBlending = true;
  40193. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  40194. }
  40195. };
  40196. Animatable.prototype.disableBlending = function () {
  40197. var runtimeAnimations = this._runtimeAnimations;
  40198. for (var index = 0; index < runtimeAnimations.length; index++) {
  40199. runtimeAnimations[index].animation.enableBlending = false;
  40200. }
  40201. };
  40202. Animatable.prototype.goToFrame = function (frame) {
  40203. var runtimeAnimations = this._runtimeAnimations;
  40204. if (runtimeAnimations[0]) {
  40205. var fps = runtimeAnimations[0].animation.framePerSecond;
  40206. var currentFrame = runtimeAnimations[0].currentFrame;
  40207. var adjustTime = frame - currentFrame;
  40208. var delay = adjustTime * 1000 / fps;
  40209. if (this._localDelayOffset === null) {
  40210. this._localDelayOffset = 0;
  40211. }
  40212. this._localDelayOffset -= delay;
  40213. }
  40214. for (var index = 0; index < runtimeAnimations.length; index++) {
  40215. runtimeAnimations[index].goToFrame(frame);
  40216. }
  40217. };
  40218. Animatable.prototype.pause = function () {
  40219. if (this._paused) {
  40220. return;
  40221. }
  40222. this._paused = true;
  40223. };
  40224. Animatable.prototype.restart = function () {
  40225. this._paused = false;
  40226. };
  40227. Animatable.prototype.stop = function (animationName) {
  40228. if (animationName) {
  40229. var idx = this._scene._activeAnimatables.indexOf(this);
  40230. if (idx > -1) {
  40231. var runtimeAnimations = this._runtimeAnimations;
  40232. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  40233. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  40234. continue;
  40235. }
  40236. runtimeAnimations[index].dispose();
  40237. runtimeAnimations.splice(index, 1);
  40238. }
  40239. if (runtimeAnimations.length == 0) {
  40240. this._scene._activeAnimatables.splice(idx, 1);
  40241. if (this.onAnimationEnd) {
  40242. this.onAnimationEnd();
  40243. }
  40244. }
  40245. }
  40246. }
  40247. else {
  40248. var index = this._scene._activeAnimatables.indexOf(this);
  40249. if (index > -1) {
  40250. this._scene._activeAnimatables.splice(index, 1);
  40251. var runtimeAnimations = this._runtimeAnimations;
  40252. for (var index = 0; index < runtimeAnimations.length; index++) {
  40253. runtimeAnimations[index].dispose();
  40254. }
  40255. if (this.onAnimationEnd) {
  40256. this.onAnimationEnd();
  40257. }
  40258. }
  40259. }
  40260. };
  40261. Animatable.prototype._animate = function (delay) {
  40262. if (this._paused) {
  40263. this.animationStarted = false;
  40264. if (this._pausedDelay === null) {
  40265. this._pausedDelay = delay;
  40266. }
  40267. return true;
  40268. }
  40269. if (this._localDelayOffset === null) {
  40270. this._localDelayOffset = delay;
  40271. }
  40272. else if (this._pausedDelay !== null) {
  40273. this._localDelayOffset += delay - this._pausedDelay;
  40274. this._pausedDelay = null;
  40275. }
  40276. // Animating
  40277. var running = false;
  40278. var runtimeAnimations = this._runtimeAnimations;
  40279. var index;
  40280. for (index = 0; index < runtimeAnimations.length; index++) {
  40281. var animation = runtimeAnimations[index];
  40282. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  40283. running = running || isRunning;
  40284. }
  40285. this.animationStarted = running;
  40286. if (!running) {
  40287. // Remove from active animatables
  40288. index = this._scene._activeAnimatables.indexOf(this);
  40289. this._scene._activeAnimatables.splice(index, 1);
  40290. // Dispose all runtime animations
  40291. for (index = 0; index < runtimeAnimations.length; index++) {
  40292. runtimeAnimations[index].dispose();
  40293. }
  40294. }
  40295. if (!running && this.onAnimationEnd) {
  40296. this.onAnimationEnd();
  40297. this.onAnimationEnd = null;
  40298. }
  40299. return running;
  40300. };
  40301. return Animatable;
  40302. }());
  40303. BABYLON.Animatable = Animatable;
  40304. })(BABYLON || (BABYLON = {}));
  40305. //# sourceMappingURL=babylon.animatable.js.map
  40306. var BABYLON;
  40307. (function (BABYLON) {
  40308. var EasingFunction = /** @class */ (function () {
  40309. function EasingFunction() {
  40310. // Properties
  40311. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  40312. }
  40313. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  40314. get: function () {
  40315. return EasingFunction._EASINGMODE_EASEIN;
  40316. },
  40317. enumerable: true,
  40318. configurable: true
  40319. });
  40320. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  40321. get: function () {
  40322. return EasingFunction._EASINGMODE_EASEOUT;
  40323. },
  40324. enumerable: true,
  40325. configurable: true
  40326. });
  40327. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  40328. get: function () {
  40329. return EasingFunction._EASINGMODE_EASEINOUT;
  40330. },
  40331. enumerable: true,
  40332. configurable: true
  40333. });
  40334. EasingFunction.prototype.setEasingMode = function (easingMode) {
  40335. var n = Math.min(Math.max(easingMode, 0), 2);
  40336. this._easingMode = n;
  40337. };
  40338. EasingFunction.prototype.getEasingMode = function () {
  40339. return this._easingMode;
  40340. };
  40341. EasingFunction.prototype.easeInCore = function (gradient) {
  40342. throw new Error('You must implement this method');
  40343. };
  40344. EasingFunction.prototype.ease = function (gradient) {
  40345. switch (this._easingMode) {
  40346. case EasingFunction.EASINGMODE_EASEIN:
  40347. return this.easeInCore(gradient);
  40348. case EasingFunction.EASINGMODE_EASEOUT:
  40349. return (1 - this.easeInCore(1 - gradient));
  40350. }
  40351. if (gradient >= 0.5) {
  40352. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  40353. }
  40354. return (this.easeInCore(gradient * 2) * 0.5);
  40355. };
  40356. //Statics
  40357. EasingFunction._EASINGMODE_EASEIN = 0;
  40358. EasingFunction._EASINGMODE_EASEOUT = 1;
  40359. EasingFunction._EASINGMODE_EASEINOUT = 2;
  40360. return EasingFunction;
  40361. }());
  40362. BABYLON.EasingFunction = EasingFunction;
  40363. var CircleEase = /** @class */ (function (_super) {
  40364. __extends(CircleEase, _super);
  40365. function CircleEase() {
  40366. return _super !== null && _super.apply(this, arguments) || this;
  40367. }
  40368. CircleEase.prototype.easeInCore = function (gradient) {
  40369. gradient = Math.max(0, Math.min(1, gradient));
  40370. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  40371. };
  40372. return CircleEase;
  40373. }(EasingFunction));
  40374. BABYLON.CircleEase = CircleEase;
  40375. var BackEase = /** @class */ (function (_super) {
  40376. __extends(BackEase, _super);
  40377. function BackEase(amplitude) {
  40378. if (amplitude === void 0) { amplitude = 1; }
  40379. var _this = _super.call(this) || this;
  40380. _this.amplitude = amplitude;
  40381. return _this;
  40382. }
  40383. BackEase.prototype.easeInCore = function (gradient) {
  40384. var num = Math.max(0, this.amplitude);
  40385. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  40386. };
  40387. return BackEase;
  40388. }(EasingFunction));
  40389. BABYLON.BackEase = BackEase;
  40390. var BounceEase = /** @class */ (function (_super) {
  40391. __extends(BounceEase, _super);
  40392. function BounceEase(bounces, bounciness) {
  40393. if (bounces === void 0) { bounces = 3; }
  40394. if (bounciness === void 0) { bounciness = 2; }
  40395. var _this = _super.call(this) || this;
  40396. _this.bounces = bounces;
  40397. _this.bounciness = bounciness;
  40398. return _this;
  40399. }
  40400. BounceEase.prototype.easeInCore = function (gradient) {
  40401. var y = Math.max(0.0, this.bounces);
  40402. var bounciness = this.bounciness;
  40403. if (bounciness <= 1.0) {
  40404. bounciness = 1.001;
  40405. }
  40406. var num9 = Math.pow(bounciness, y);
  40407. var num5 = 1.0 - bounciness;
  40408. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  40409. var num15 = gradient * num4;
  40410. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  40411. var num3 = Math.floor(num65);
  40412. var num13 = num3 + 1.0;
  40413. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  40414. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  40415. var num7 = (num8 + num12) * 0.5;
  40416. var num6 = gradient - num7;
  40417. var num2 = num7 - num8;
  40418. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  40419. };
  40420. return BounceEase;
  40421. }(EasingFunction));
  40422. BABYLON.BounceEase = BounceEase;
  40423. var CubicEase = /** @class */ (function (_super) {
  40424. __extends(CubicEase, _super);
  40425. function CubicEase() {
  40426. return _super !== null && _super.apply(this, arguments) || this;
  40427. }
  40428. CubicEase.prototype.easeInCore = function (gradient) {
  40429. return (gradient * gradient * gradient);
  40430. };
  40431. return CubicEase;
  40432. }(EasingFunction));
  40433. BABYLON.CubicEase = CubicEase;
  40434. var ElasticEase = /** @class */ (function (_super) {
  40435. __extends(ElasticEase, _super);
  40436. function ElasticEase(oscillations, springiness) {
  40437. if (oscillations === void 0) { oscillations = 3; }
  40438. if (springiness === void 0) { springiness = 3; }
  40439. var _this = _super.call(this) || this;
  40440. _this.oscillations = oscillations;
  40441. _this.springiness = springiness;
  40442. return _this;
  40443. }
  40444. ElasticEase.prototype.easeInCore = function (gradient) {
  40445. var num2;
  40446. var num3 = Math.max(0.0, this.oscillations);
  40447. var num = Math.max(0.0, this.springiness);
  40448. if (num == 0) {
  40449. num2 = gradient;
  40450. }
  40451. else {
  40452. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  40453. }
  40454. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  40455. };
  40456. return ElasticEase;
  40457. }(EasingFunction));
  40458. BABYLON.ElasticEase = ElasticEase;
  40459. var ExponentialEase = /** @class */ (function (_super) {
  40460. __extends(ExponentialEase, _super);
  40461. function ExponentialEase(exponent) {
  40462. if (exponent === void 0) { exponent = 2; }
  40463. var _this = _super.call(this) || this;
  40464. _this.exponent = exponent;
  40465. return _this;
  40466. }
  40467. ExponentialEase.prototype.easeInCore = function (gradient) {
  40468. if (this.exponent <= 0) {
  40469. return gradient;
  40470. }
  40471. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  40472. };
  40473. return ExponentialEase;
  40474. }(EasingFunction));
  40475. BABYLON.ExponentialEase = ExponentialEase;
  40476. var PowerEase = /** @class */ (function (_super) {
  40477. __extends(PowerEase, _super);
  40478. function PowerEase(power) {
  40479. if (power === void 0) { power = 2; }
  40480. var _this = _super.call(this) || this;
  40481. _this.power = power;
  40482. return _this;
  40483. }
  40484. PowerEase.prototype.easeInCore = function (gradient) {
  40485. var y = Math.max(0.0, this.power);
  40486. return Math.pow(gradient, y);
  40487. };
  40488. return PowerEase;
  40489. }(EasingFunction));
  40490. BABYLON.PowerEase = PowerEase;
  40491. var QuadraticEase = /** @class */ (function (_super) {
  40492. __extends(QuadraticEase, _super);
  40493. function QuadraticEase() {
  40494. return _super !== null && _super.apply(this, arguments) || this;
  40495. }
  40496. QuadraticEase.prototype.easeInCore = function (gradient) {
  40497. return (gradient * gradient);
  40498. };
  40499. return QuadraticEase;
  40500. }(EasingFunction));
  40501. BABYLON.QuadraticEase = QuadraticEase;
  40502. var QuarticEase = /** @class */ (function (_super) {
  40503. __extends(QuarticEase, _super);
  40504. function QuarticEase() {
  40505. return _super !== null && _super.apply(this, arguments) || this;
  40506. }
  40507. QuarticEase.prototype.easeInCore = function (gradient) {
  40508. return (gradient * gradient * gradient * gradient);
  40509. };
  40510. return QuarticEase;
  40511. }(EasingFunction));
  40512. BABYLON.QuarticEase = QuarticEase;
  40513. var QuinticEase = /** @class */ (function (_super) {
  40514. __extends(QuinticEase, _super);
  40515. function QuinticEase() {
  40516. return _super !== null && _super.apply(this, arguments) || this;
  40517. }
  40518. QuinticEase.prototype.easeInCore = function (gradient) {
  40519. return (gradient * gradient * gradient * gradient * gradient);
  40520. };
  40521. return QuinticEase;
  40522. }(EasingFunction));
  40523. BABYLON.QuinticEase = QuinticEase;
  40524. var SineEase = /** @class */ (function (_super) {
  40525. __extends(SineEase, _super);
  40526. function SineEase() {
  40527. return _super !== null && _super.apply(this, arguments) || this;
  40528. }
  40529. SineEase.prototype.easeInCore = function (gradient) {
  40530. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  40531. };
  40532. return SineEase;
  40533. }(EasingFunction));
  40534. BABYLON.SineEase = SineEase;
  40535. var BezierCurveEase = /** @class */ (function (_super) {
  40536. __extends(BezierCurveEase, _super);
  40537. function BezierCurveEase(x1, y1, x2, y2) {
  40538. if (x1 === void 0) { x1 = 0; }
  40539. if (y1 === void 0) { y1 = 0; }
  40540. if (x2 === void 0) { x2 = 1; }
  40541. if (y2 === void 0) { y2 = 1; }
  40542. var _this = _super.call(this) || this;
  40543. _this.x1 = x1;
  40544. _this.y1 = y1;
  40545. _this.x2 = x2;
  40546. _this.y2 = y2;
  40547. return _this;
  40548. }
  40549. BezierCurveEase.prototype.easeInCore = function (gradient) {
  40550. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  40551. };
  40552. return BezierCurveEase;
  40553. }(EasingFunction));
  40554. BABYLON.BezierCurveEase = BezierCurveEase;
  40555. })(BABYLON || (BABYLON = {}));
  40556. //# sourceMappingURL=babylon.easing.js.map
  40557. var BABYLON;
  40558. (function (BABYLON) {
  40559. var Condition = /** @class */ (function () {
  40560. function Condition(actionManager) {
  40561. this._actionManager = actionManager;
  40562. }
  40563. Condition.prototype.isValid = function () {
  40564. return true;
  40565. };
  40566. Condition.prototype._getProperty = function (propertyPath) {
  40567. return this._actionManager._getProperty(propertyPath);
  40568. };
  40569. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  40570. return this._actionManager._getEffectiveTarget(target, propertyPath);
  40571. };
  40572. Condition.prototype.serialize = function () {
  40573. };
  40574. Condition.prototype._serialize = function (serializedCondition) {
  40575. return {
  40576. type: 2,
  40577. children: [],
  40578. name: serializedCondition.name,
  40579. properties: serializedCondition.properties
  40580. };
  40581. };
  40582. return Condition;
  40583. }());
  40584. BABYLON.Condition = Condition;
  40585. var ValueCondition = /** @class */ (function (_super) {
  40586. __extends(ValueCondition, _super);
  40587. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  40588. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  40589. var _this = _super.call(this, actionManager) || this;
  40590. _this.propertyPath = propertyPath;
  40591. _this.value = value;
  40592. _this.operator = operator;
  40593. _this._target = target;
  40594. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  40595. _this._property = _this._getProperty(_this.propertyPath);
  40596. return _this;
  40597. }
  40598. Object.defineProperty(ValueCondition, "IsEqual", {
  40599. get: function () {
  40600. return ValueCondition._IsEqual;
  40601. },
  40602. enumerable: true,
  40603. configurable: true
  40604. });
  40605. Object.defineProperty(ValueCondition, "IsDifferent", {
  40606. get: function () {
  40607. return ValueCondition._IsDifferent;
  40608. },
  40609. enumerable: true,
  40610. configurable: true
  40611. });
  40612. Object.defineProperty(ValueCondition, "IsGreater", {
  40613. get: function () {
  40614. return ValueCondition._IsGreater;
  40615. },
  40616. enumerable: true,
  40617. configurable: true
  40618. });
  40619. Object.defineProperty(ValueCondition, "IsLesser", {
  40620. get: function () {
  40621. return ValueCondition._IsLesser;
  40622. },
  40623. enumerable: true,
  40624. configurable: true
  40625. });
  40626. // Methods
  40627. ValueCondition.prototype.isValid = function () {
  40628. switch (this.operator) {
  40629. case ValueCondition.IsGreater:
  40630. return this._effectiveTarget[this._property] > this.value;
  40631. case ValueCondition.IsLesser:
  40632. return this._effectiveTarget[this._property] < this.value;
  40633. case ValueCondition.IsEqual:
  40634. case ValueCondition.IsDifferent:
  40635. var check;
  40636. if (this.value.equals) {
  40637. check = this.value.equals(this._effectiveTarget[this._property]);
  40638. }
  40639. else {
  40640. check = this.value === this._effectiveTarget[this._property];
  40641. }
  40642. return this.operator === ValueCondition.IsEqual ? check : !check;
  40643. }
  40644. return false;
  40645. };
  40646. ValueCondition.prototype.serialize = function () {
  40647. return this._serialize({
  40648. name: "ValueCondition",
  40649. properties: [
  40650. BABYLON.Action._GetTargetProperty(this._target),
  40651. { name: "propertyPath", value: this.propertyPath },
  40652. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  40653. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  40654. ]
  40655. });
  40656. };
  40657. ValueCondition.GetOperatorName = function (operator) {
  40658. switch (operator) {
  40659. case ValueCondition._IsEqual: return "IsEqual";
  40660. case ValueCondition._IsDifferent: return "IsDifferent";
  40661. case ValueCondition._IsGreater: return "IsGreater";
  40662. case ValueCondition._IsLesser: return "IsLesser";
  40663. default: return "";
  40664. }
  40665. };
  40666. // Statics
  40667. ValueCondition._IsEqual = 0;
  40668. ValueCondition._IsDifferent = 1;
  40669. ValueCondition._IsGreater = 2;
  40670. ValueCondition._IsLesser = 3;
  40671. return ValueCondition;
  40672. }(Condition));
  40673. BABYLON.ValueCondition = ValueCondition;
  40674. var PredicateCondition = /** @class */ (function (_super) {
  40675. __extends(PredicateCondition, _super);
  40676. function PredicateCondition(actionManager, predicate) {
  40677. var _this = _super.call(this, actionManager) || this;
  40678. _this.predicate = predicate;
  40679. return _this;
  40680. }
  40681. PredicateCondition.prototype.isValid = function () {
  40682. return this.predicate();
  40683. };
  40684. return PredicateCondition;
  40685. }(Condition));
  40686. BABYLON.PredicateCondition = PredicateCondition;
  40687. var StateCondition = /** @class */ (function (_super) {
  40688. __extends(StateCondition, _super);
  40689. function StateCondition(actionManager, target, value) {
  40690. var _this = _super.call(this, actionManager) || this;
  40691. _this.value = value;
  40692. _this._target = target;
  40693. return _this;
  40694. }
  40695. // Methods
  40696. StateCondition.prototype.isValid = function () {
  40697. return this._target.state === this.value;
  40698. };
  40699. StateCondition.prototype.serialize = function () {
  40700. return this._serialize({
  40701. name: "StateCondition",
  40702. properties: [
  40703. BABYLON.Action._GetTargetProperty(this._target),
  40704. { name: "value", value: this.value }
  40705. ]
  40706. });
  40707. };
  40708. return StateCondition;
  40709. }(Condition));
  40710. BABYLON.StateCondition = StateCondition;
  40711. })(BABYLON || (BABYLON = {}));
  40712. //# sourceMappingURL=babylon.condition.js.map
  40713. var BABYLON;
  40714. (function (BABYLON) {
  40715. var Action = /** @class */ (function () {
  40716. function Action(triggerOptions, condition) {
  40717. this.triggerOptions = triggerOptions;
  40718. this.onBeforeExecuteObservable = new BABYLON.Observable();
  40719. if (triggerOptions.parameter) {
  40720. this.trigger = triggerOptions.trigger;
  40721. this._triggerParameter = triggerOptions.parameter;
  40722. }
  40723. else {
  40724. this.trigger = triggerOptions;
  40725. }
  40726. this._nextActiveAction = this;
  40727. this._condition = condition;
  40728. }
  40729. // Methods
  40730. Action.prototype._prepare = function () {
  40731. };
  40732. Action.prototype.getTriggerParameter = function () {
  40733. return this._triggerParameter;
  40734. };
  40735. Action.prototype._executeCurrent = function (evt) {
  40736. if (this._nextActiveAction._condition) {
  40737. var condition = this._nextActiveAction._condition;
  40738. var currentRenderId = this._actionManager.getScene().getRenderId();
  40739. // We cache the current evaluation for the current frame
  40740. if (condition._evaluationId === currentRenderId) {
  40741. if (!condition._currentResult) {
  40742. return;
  40743. }
  40744. }
  40745. else {
  40746. condition._evaluationId = currentRenderId;
  40747. if (!condition.isValid()) {
  40748. condition._currentResult = false;
  40749. return;
  40750. }
  40751. condition._currentResult = true;
  40752. }
  40753. }
  40754. this.onBeforeExecuteObservable.notifyObservers(this);
  40755. this._nextActiveAction.execute(evt);
  40756. this.skipToNextActiveAction();
  40757. };
  40758. Action.prototype.execute = function (evt) {
  40759. };
  40760. Action.prototype.skipToNextActiveAction = function () {
  40761. if (this._nextActiveAction._child) {
  40762. if (!this._nextActiveAction._child._actionManager) {
  40763. this._nextActiveAction._child._actionManager = this._actionManager;
  40764. }
  40765. this._nextActiveAction = this._nextActiveAction._child;
  40766. }
  40767. else {
  40768. this._nextActiveAction = this;
  40769. }
  40770. };
  40771. Action.prototype.then = function (action) {
  40772. this._child = action;
  40773. action._actionManager = this._actionManager;
  40774. action._prepare();
  40775. return action;
  40776. };
  40777. Action.prototype._getProperty = function (propertyPath) {
  40778. return this._actionManager._getProperty(propertyPath);
  40779. };
  40780. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  40781. return this._actionManager._getEffectiveTarget(target, propertyPath);
  40782. };
  40783. Action.prototype.serialize = function (parent) {
  40784. };
  40785. // Called by BABYLON.Action objects in serialize(...). Internal use
  40786. Action.prototype._serialize = function (serializedAction, parent) {
  40787. var serializationObject = {
  40788. type: 1,
  40789. children: [],
  40790. name: serializedAction.name,
  40791. properties: serializedAction.properties || []
  40792. };
  40793. // Serialize child
  40794. if (this._child) {
  40795. this._child.serialize(serializationObject);
  40796. }
  40797. // Check if "this" has a condition
  40798. if (this._condition) {
  40799. var serializedCondition = this._condition.serialize();
  40800. serializedCondition.children.push(serializationObject);
  40801. if (parent) {
  40802. parent.children.push(serializedCondition);
  40803. }
  40804. return serializedCondition;
  40805. }
  40806. if (parent) {
  40807. parent.children.push(serializationObject);
  40808. }
  40809. return serializationObject;
  40810. };
  40811. Action._SerializeValueAsString = function (value) {
  40812. if (typeof value === "number") {
  40813. return value.toString();
  40814. }
  40815. if (typeof value === "boolean") {
  40816. return value ? "true" : "false";
  40817. }
  40818. if (value instanceof BABYLON.Vector2) {
  40819. return value.x + ", " + value.y;
  40820. }
  40821. if (value instanceof BABYLON.Vector3) {
  40822. return value.x + ", " + value.y + ", " + value.z;
  40823. }
  40824. if (value instanceof BABYLON.Color3) {
  40825. return value.r + ", " + value.g + ", " + value.b;
  40826. }
  40827. if (value instanceof BABYLON.Color4) {
  40828. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  40829. }
  40830. return value; // string
  40831. };
  40832. Action._GetTargetProperty = function (target) {
  40833. return {
  40834. name: "target",
  40835. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  40836. : target instanceof BABYLON.Light ? "LightProperties"
  40837. : target instanceof BABYLON.Camera ? "CameraProperties"
  40838. : "SceneProperties",
  40839. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  40840. };
  40841. };
  40842. return Action;
  40843. }());
  40844. BABYLON.Action = Action;
  40845. })(BABYLON || (BABYLON = {}));
  40846. //# sourceMappingURL=babylon.action.js.map
  40847. var BABYLON;
  40848. (function (BABYLON) {
  40849. /**
  40850. * ActionEvent is the event beint sent when an action is triggered.
  40851. */
  40852. var ActionEvent = /** @class */ (function () {
  40853. /**
  40854. * @param source The mesh or sprite that triggered the action.
  40855. * @param pointerX The X mouse cursor position at the time of the event
  40856. * @param pointerY The Y mouse cursor position at the time of the event
  40857. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  40858. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  40859. */
  40860. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  40861. this.source = source;
  40862. this.pointerX = pointerX;
  40863. this.pointerY = pointerY;
  40864. this.meshUnderPointer = meshUnderPointer;
  40865. this.sourceEvent = sourceEvent;
  40866. this.additionalData = additionalData;
  40867. }
  40868. /**
  40869. * Helper function to auto-create an ActionEvent from a source mesh.
  40870. * @param source The source mesh that triggered the event
  40871. * @param evt {Event} The original (browser) event
  40872. */
  40873. ActionEvent.CreateNew = function (source, evt, additionalData) {
  40874. var scene = source.getScene();
  40875. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  40876. };
  40877. /**
  40878. * Helper function to auto-create an ActionEvent from a source mesh.
  40879. * @param source The source sprite that triggered the event
  40880. * @param scene Scene associated with the sprite
  40881. * @param evt {Event} The original (browser) event
  40882. */
  40883. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  40884. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  40885. };
  40886. /**
  40887. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  40888. * @param scene the scene where the event occurred
  40889. * @param evt {Event} The original (browser) event
  40890. */
  40891. ActionEvent.CreateNewFromScene = function (scene, evt) {
  40892. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  40893. };
  40894. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  40895. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  40896. };
  40897. return ActionEvent;
  40898. }());
  40899. BABYLON.ActionEvent = ActionEvent;
  40900. /**
  40901. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  40902. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  40903. */
  40904. var ActionManager = /** @class */ (function () {
  40905. function ActionManager(scene) {
  40906. // Members
  40907. this.actions = new Array();
  40908. this.hoverCursor = '';
  40909. this._scene = scene;
  40910. scene._actionManagers.push(this);
  40911. }
  40912. Object.defineProperty(ActionManager, "NothingTrigger", {
  40913. get: function () {
  40914. return ActionManager._NothingTrigger;
  40915. },
  40916. enumerable: true,
  40917. configurable: true
  40918. });
  40919. Object.defineProperty(ActionManager, "OnPickTrigger", {
  40920. get: function () {
  40921. return ActionManager._OnPickTrigger;
  40922. },
  40923. enumerable: true,
  40924. configurable: true
  40925. });
  40926. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  40927. get: function () {
  40928. return ActionManager._OnLeftPickTrigger;
  40929. },
  40930. enumerable: true,
  40931. configurable: true
  40932. });
  40933. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  40934. get: function () {
  40935. return ActionManager._OnRightPickTrigger;
  40936. },
  40937. enumerable: true,
  40938. configurable: true
  40939. });
  40940. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  40941. get: function () {
  40942. return ActionManager._OnCenterPickTrigger;
  40943. },
  40944. enumerable: true,
  40945. configurable: true
  40946. });
  40947. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  40948. get: function () {
  40949. return ActionManager._OnPickDownTrigger;
  40950. },
  40951. enumerable: true,
  40952. configurable: true
  40953. });
  40954. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  40955. get: function () {
  40956. return ActionManager._OnDoublePickTrigger;
  40957. },
  40958. enumerable: true,
  40959. configurable: true
  40960. });
  40961. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  40962. get: function () {
  40963. return ActionManager._OnPickUpTrigger;
  40964. },
  40965. enumerable: true,
  40966. configurable: true
  40967. });
  40968. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  40969. /// This trigger will only be raised if you also declared a OnPickDown
  40970. get: function () {
  40971. return ActionManager._OnPickOutTrigger;
  40972. },
  40973. enumerable: true,
  40974. configurable: true
  40975. });
  40976. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  40977. get: function () {
  40978. return ActionManager._OnLongPressTrigger;
  40979. },
  40980. enumerable: true,
  40981. configurable: true
  40982. });
  40983. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  40984. get: function () {
  40985. return ActionManager._OnPointerOverTrigger;
  40986. },
  40987. enumerable: true,
  40988. configurable: true
  40989. });
  40990. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  40991. get: function () {
  40992. return ActionManager._OnPointerOutTrigger;
  40993. },
  40994. enumerable: true,
  40995. configurable: true
  40996. });
  40997. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  40998. get: function () {
  40999. return ActionManager._OnEveryFrameTrigger;
  41000. },
  41001. enumerable: true,
  41002. configurable: true
  41003. });
  41004. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  41005. get: function () {
  41006. return ActionManager._OnIntersectionEnterTrigger;
  41007. },
  41008. enumerable: true,
  41009. configurable: true
  41010. });
  41011. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  41012. get: function () {
  41013. return ActionManager._OnIntersectionExitTrigger;
  41014. },
  41015. enumerable: true,
  41016. configurable: true
  41017. });
  41018. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  41019. get: function () {
  41020. return ActionManager._OnKeyDownTrigger;
  41021. },
  41022. enumerable: true,
  41023. configurable: true
  41024. });
  41025. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  41026. get: function () {
  41027. return ActionManager._OnKeyUpTrigger;
  41028. },
  41029. enumerable: true,
  41030. configurable: true
  41031. });
  41032. // Methods
  41033. ActionManager.prototype.dispose = function () {
  41034. var index = this._scene._actionManagers.indexOf(this);
  41035. for (var i = 0; i < this.actions.length; i++) {
  41036. var action = this.actions[i];
  41037. ActionManager.Triggers[action.trigger]--;
  41038. if (ActionManager.Triggers[action.trigger] === 0) {
  41039. delete ActionManager.Triggers[action.trigger];
  41040. }
  41041. }
  41042. if (index > -1) {
  41043. this._scene._actionManagers.splice(index, 1);
  41044. }
  41045. };
  41046. ActionManager.prototype.getScene = function () {
  41047. return this._scene;
  41048. };
  41049. /**
  41050. * Does this action manager handles actions of any of the given triggers
  41051. * @param {number[]} triggers - the triggers to be tested
  41052. * @return {boolean} whether one (or more) of the triggers is handeled
  41053. */
  41054. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  41055. for (var index = 0; index < this.actions.length; index++) {
  41056. var action = this.actions[index];
  41057. if (triggers.indexOf(action.trigger) > -1) {
  41058. return true;
  41059. }
  41060. }
  41061. return false;
  41062. };
  41063. /**
  41064. * Does this action manager handles actions of a given trigger
  41065. * @param {number} trigger - the trigger to be tested
  41066. * @return {boolean} whether the trigger is handeled
  41067. */
  41068. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  41069. for (var index = 0; index < this.actions.length; index++) {
  41070. var action = this.actions[index];
  41071. if (action.trigger === trigger) {
  41072. return true;
  41073. }
  41074. }
  41075. return false;
  41076. };
  41077. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  41078. /**
  41079. * Does this action manager has pointer triggers
  41080. * @return {boolean} whether or not it has pointer triggers
  41081. */
  41082. get: function () {
  41083. for (var index = 0; index < this.actions.length; index++) {
  41084. var action = this.actions[index];
  41085. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  41086. return true;
  41087. }
  41088. }
  41089. return false;
  41090. },
  41091. enumerable: true,
  41092. configurable: true
  41093. });
  41094. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  41095. /**
  41096. * Does this action manager has pick triggers
  41097. * @return {boolean} whether or not it has pick triggers
  41098. */
  41099. get: function () {
  41100. for (var index = 0; index < this.actions.length; index++) {
  41101. var action = this.actions[index];
  41102. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  41103. return true;
  41104. }
  41105. }
  41106. return false;
  41107. },
  41108. enumerable: true,
  41109. configurable: true
  41110. });
  41111. Object.defineProperty(ActionManager, "HasTriggers", {
  41112. /**
  41113. * Does exist one action manager with at least one trigger
  41114. * @return {boolean} whether or not it exists one action manager with one trigger
  41115. **/
  41116. get: function () {
  41117. for (var t in ActionManager.Triggers) {
  41118. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41119. return true;
  41120. }
  41121. }
  41122. return false;
  41123. },
  41124. enumerable: true,
  41125. configurable: true
  41126. });
  41127. Object.defineProperty(ActionManager, "HasPickTriggers", {
  41128. /**
  41129. * Does exist one action manager with at least one pick trigger
  41130. * @return {boolean} whether or not it exists one action manager with one pick trigger
  41131. **/
  41132. get: function () {
  41133. for (var t in ActionManager.Triggers) {
  41134. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41135. var t_int = parseInt(t);
  41136. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  41137. return true;
  41138. }
  41139. }
  41140. }
  41141. return false;
  41142. },
  41143. enumerable: true,
  41144. configurable: true
  41145. });
  41146. /**
  41147. * Does exist one action manager that handles actions of a given trigger
  41148. * @param {number} trigger - the trigger to be tested
  41149. * @return {boolean} whether the trigger is handeled by at least one action manager
  41150. **/
  41151. ActionManager.HasSpecificTrigger = function (trigger) {
  41152. for (var t in ActionManager.Triggers) {
  41153. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41154. var t_int = parseInt(t);
  41155. if (t_int === trigger) {
  41156. return true;
  41157. }
  41158. }
  41159. }
  41160. return false;
  41161. };
  41162. /**
  41163. * Registers an action to this action manager
  41164. * @param {BABYLON.Action} action - the action to be registered
  41165. * @return {BABYLON.Action} the action amended (prepared) after registration
  41166. */
  41167. ActionManager.prototype.registerAction = function (action) {
  41168. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  41169. if (this.getScene().actionManager !== this) {
  41170. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  41171. return null;
  41172. }
  41173. }
  41174. this.actions.push(action);
  41175. if (ActionManager.Triggers[action.trigger]) {
  41176. ActionManager.Triggers[action.trigger]++;
  41177. }
  41178. else {
  41179. ActionManager.Triggers[action.trigger] = 1;
  41180. }
  41181. action._actionManager = this;
  41182. action._prepare();
  41183. return action;
  41184. };
  41185. /**
  41186. * Process a specific trigger
  41187. * @param {number} trigger - the trigger to process
  41188. * @param evt {BABYLON.ActionEvent} the event details to be processed
  41189. */
  41190. ActionManager.prototype.processTrigger = function (trigger, evt) {
  41191. for (var index = 0; index < this.actions.length; index++) {
  41192. var action = this.actions[index];
  41193. if (action.trigger === trigger) {
  41194. if (evt) {
  41195. if (trigger === ActionManager.OnKeyUpTrigger
  41196. || trigger === ActionManager.OnKeyDownTrigger) {
  41197. var parameter = action.getTriggerParameter();
  41198. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  41199. if (!parameter.toLowerCase) {
  41200. continue;
  41201. }
  41202. var lowerCase = parameter.toLowerCase();
  41203. if (lowerCase !== evt.sourceEvent.key) {
  41204. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  41205. var actualkey = String.fromCharCode(unicode).toLowerCase();
  41206. if (actualkey !== lowerCase) {
  41207. continue;
  41208. }
  41209. }
  41210. }
  41211. }
  41212. }
  41213. action._executeCurrent(evt);
  41214. }
  41215. }
  41216. };
  41217. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  41218. var properties = propertyPath.split(".");
  41219. for (var index = 0; index < properties.length - 1; index++) {
  41220. target = target[properties[index]];
  41221. }
  41222. return target;
  41223. };
  41224. ActionManager.prototype._getProperty = function (propertyPath) {
  41225. var properties = propertyPath.split(".");
  41226. return properties[properties.length - 1];
  41227. };
  41228. ActionManager.prototype.serialize = function (name) {
  41229. var root = {
  41230. children: new Array(),
  41231. name: name,
  41232. type: 3,
  41233. properties: new Array() // Empty for root but required
  41234. };
  41235. for (var i = 0; i < this.actions.length; i++) {
  41236. var triggerObject = {
  41237. type: 0,
  41238. children: new Array(),
  41239. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  41240. properties: new Array()
  41241. };
  41242. var triggerOptions = this.actions[i].triggerOptions;
  41243. if (triggerOptions && typeof triggerOptions !== "number") {
  41244. if (triggerOptions.parameter instanceof BABYLON.Node) {
  41245. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  41246. }
  41247. else {
  41248. var parameter = {};
  41249. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  41250. if (triggerOptions.parameter.mesh) {
  41251. parameter._meshId = triggerOptions.parameter.mesh.id;
  41252. }
  41253. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  41254. }
  41255. }
  41256. // Serialize child action, recursively
  41257. this.actions[i].serialize(triggerObject);
  41258. // Add serialized trigger
  41259. root.children.push(triggerObject);
  41260. }
  41261. return root;
  41262. };
  41263. ActionManager.Parse = function (parsedActions, object, scene) {
  41264. var actionManager = new BABYLON.ActionManager(scene);
  41265. if (object === null)
  41266. scene.actionManager = actionManager;
  41267. else
  41268. object.actionManager = actionManager;
  41269. // instanciate a new object
  41270. var instanciate = function (name, params) {
  41271. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  41272. newInstance.constructor.apply(newInstance, params);
  41273. return newInstance;
  41274. };
  41275. var parseParameter = function (name, value, target, propertyPath) {
  41276. if (propertyPath === null) {
  41277. // String, boolean or float
  41278. var floatValue = parseFloat(value);
  41279. if (value === "true" || value === "false")
  41280. return value === "true";
  41281. else
  41282. return isNaN(floatValue) ? value : floatValue;
  41283. }
  41284. var effectiveTarget = propertyPath.split(".");
  41285. var values = value.split(",");
  41286. // Get effective Target
  41287. for (var i = 0; i < effectiveTarget.length; i++) {
  41288. target = target[effectiveTarget[i]];
  41289. }
  41290. // Return appropriate value with its type
  41291. if (typeof (target) === "boolean")
  41292. return values[0] === "true";
  41293. if (typeof (target) === "string")
  41294. return values[0];
  41295. // Parameters with multiple values such as Vector3 etc.
  41296. var split = new Array();
  41297. for (var i = 0; i < values.length; i++)
  41298. split.push(parseFloat(values[i]));
  41299. if (target instanceof BABYLON.Vector3)
  41300. return BABYLON.Vector3.FromArray(split);
  41301. if (target instanceof BABYLON.Vector4)
  41302. return BABYLON.Vector4.FromArray(split);
  41303. if (target instanceof BABYLON.Color3)
  41304. return BABYLON.Color3.FromArray(split);
  41305. if (target instanceof BABYLON.Color4)
  41306. return BABYLON.Color4.FromArray(split);
  41307. return parseFloat(values[0]);
  41308. };
  41309. // traverse graph per trigger
  41310. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  41311. if (combineArray === void 0) { combineArray = null; }
  41312. if (parsedAction.detached)
  41313. return;
  41314. var parameters = new Array();
  41315. var target = null;
  41316. var propertyPath = null;
  41317. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  41318. // Parameters
  41319. if (parsedAction.type === 2)
  41320. parameters.push(actionManager);
  41321. else
  41322. parameters.push(trigger);
  41323. if (combine) {
  41324. var actions = new Array();
  41325. for (var j = 0; j < parsedAction.combine.length; j++) {
  41326. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  41327. }
  41328. parameters.push(actions);
  41329. }
  41330. else {
  41331. for (var i = 0; i < parsedAction.properties.length; i++) {
  41332. var value = parsedAction.properties[i].value;
  41333. var name = parsedAction.properties[i].name;
  41334. var targetType = parsedAction.properties[i].targetType;
  41335. if (name === "target")
  41336. if (targetType !== null && targetType === "SceneProperties")
  41337. value = target = scene;
  41338. else
  41339. value = target = scene.getNodeByName(value);
  41340. else if (name === "parent")
  41341. value = scene.getNodeByName(value);
  41342. else if (name === "sound")
  41343. value = scene.getSoundByName(value);
  41344. else if (name !== "propertyPath") {
  41345. if (parsedAction.type === 2 && name === "operator")
  41346. value = BABYLON.ValueCondition[value];
  41347. else
  41348. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  41349. }
  41350. else {
  41351. propertyPath = value;
  41352. }
  41353. parameters.push(value);
  41354. }
  41355. }
  41356. if (combineArray === null) {
  41357. parameters.push(condition);
  41358. }
  41359. else {
  41360. parameters.push(null);
  41361. }
  41362. // If interpolate value action
  41363. if (parsedAction.name === "InterpolateValueAction") {
  41364. var param = parameters[parameters.length - 2];
  41365. parameters[parameters.length - 1] = param;
  41366. parameters[parameters.length - 2] = condition;
  41367. }
  41368. // Action or condition(s) and not CombineAction
  41369. var newAction = instanciate(parsedAction.name, parameters);
  41370. if (newAction instanceof BABYLON.Condition && condition !== null) {
  41371. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  41372. if (action)
  41373. action.then(nothing);
  41374. else
  41375. actionManager.registerAction(nothing);
  41376. action = nothing;
  41377. }
  41378. if (combineArray === null) {
  41379. if (newAction instanceof BABYLON.Condition) {
  41380. condition = newAction;
  41381. newAction = action;
  41382. }
  41383. else {
  41384. condition = null;
  41385. if (action)
  41386. action.then(newAction);
  41387. else
  41388. actionManager.registerAction(newAction);
  41389. }
  41390. }
  41391. else {
  41392. combineArray.push(newAction);
  41393. }
  41394. for (var i = 0; i < parsedAction.children.length; i++)
  41395. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  41396. };
  41397. // triggers
  41398. for (var i = 0; i < parsedActions.children.length; i++) {
  41399. var triggerParams;
  41400. var trigger = parsedActions.children[i];
  41401. if (trigger.properties.length > 0) {
  41402. var param = trigger.properties[0].value;
  41403. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  41404. if (value._meshId) {
  41405. value.mesh = scene.getMeshByID(value._meshId);
  41406. }
  41407. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  41408. }
  41409. else
  41410. triggerParams = ActionManager[trigger.name];
  41411. for (var j = 0; j < trigger.children.length; j++) {
  41412. if (!trigger.detached)
  41413. traverse(trigger.children[j], triggerParams, null, null);
  41414. }
  41415. }
  41416. };
  41417. ActionManager.GetTriggerName = function (trigger) {
  41418. switch (trigger) {
  41419. case 0: return "NothingTrigger";
  41420. case 1: return "OnPickTrigger";
  41421. case 2: return "OnLeftPickTrigger";
  41422. case 3: return "OnRightPickTrigger";
  41423. case 4: return "OnCenterPickTrigger";
  41424. case 5: return "OnPickDownTrigger";
  41425. case 6: return "OnPickUpTrigger";
  41426. case 7: return "OnLongPressTrigger";
  41427. case 8: return "OnPointerOverTrigger";
  41428. case 9: return "OnPointerOutTrigger";
  41429. case 10: return "OnEveryFrameTrigger";
  41430. case 11: return "OnIntersectionEnterTrigger";
  41431. case 12: return "OnIntersectionExitTrigger";
  41432. case 13: return "OnKeyDownTrigger";
  41433. case 14: return "OnKeyUpTrigger";
  41434. case 15: return "OnPickOutTrigger";
  41435. default: return "";
  41436. }
  41437. };
  41438. // Statics
  41439. ActionManager._NothingTrigger = 0;
  41440. ActionManager._OnPickTrigger = 1;
  41441. ActionManager._OnLeftPickTrigger = 2;
  41442. ActionManager._OnRightPickTrigger = 3;
  41443. ActionManager._OnCenterPickTrigger = 4;
  41444. ActionManager._OnPickDownTrigger = 5;
  41445. ActionManager._OnDoublePickTrigger = 6;
  41446. ActionManager._OnPickUpTrigger = 7;
  41447. ActionManager._OnLongPressTrigger = 8;
  41448. ActionManager._OnPointerOverTrigger = 9;
  41449. ActionManager._OnPointerOutTrigger = 10;
  41450. ActionManager._OnEveryFrameTrigger = 11;
  41451. ActionManager._OnIntersectionEnterTrigger = 12;
  41452. ActionManager._OnIntersectionExitTrigger = 13;
  41453. ActionManager._OnKeyDownTrigger = 14;
  41454. ActionManager._OnKeyUpTrigger = 15;
  41455. ActionManager._OnPickOutTrigger = 16;
  41456. ActionManager.Triggers = {};
  41457. return ActionManager;
  41458. }());
  41459. BABYLON.ActionManager = ActionManager;
  41460. })(BABYLON || (BABYLON = {}));
  41461. //# sourceMappingURL=babylon.actionManager.js.map
  41462. var BABYLON;
  41463. (function (BABYLON) {
  41464. var InterpolateValueAction = /** @class */ (function (_super) {
  41465. __extends(InterpolateValueAction, _super);
  41466. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  41467. if (duration === void 0) { duration = 1000; }
  41468. var _this = _super.call(this, triggerOptions, condition) || this;
  41469. _this.propertyPath = propertyPath;
  41470. _this.value = value;
  41471. _this.duration = duration;
  41472. _this.stopOtherAnimations = stopOtherAnimations;
  41473. _this.onInterpolationDone = onInterpolationDone;
  41474. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  41475. _this._target = _this._effectiveTarget = target;
  41476. return _this;
  41477. }
  41478. InterpolateValueAction.prototype._prepare = function () {
  41479. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  41480. this._property = this._getProperty(this.propertyPath);
  41481. };
  41482. InterpolateValueAction.prototype.execute = function () {
  41483. var _this = this;
  41484. var scene = this._actionManager.getScene();
  41485. var keys = [
  41486. {
  41487. frame: 0,
  41488. value: this._effectiveTarget[this._property]
  41489. }, {
  41490. frame: 100,
  41491. value: this.value
  41492. }
  41493. ];
  41494. var dataType;
  41495. if (typeof this.value === "number") {
  41496. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  41497. }
  41498. else if (this.value instanceof BABYLON.Color3) {
  41499. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  41500. }
  41501. else if (this.value instanceof BABYLON.Vector3) {
  41502. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  41503. }
  41504. else if (this.value instanceof BABYLON.Matrix) {
  41505. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  41506. }
  41507. else if (this.value instanceof BABYLON.Quaternion) {
  41508. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  41509. }
  41510. else {
  41511. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  41512. return;
  41513. }
  41514. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  41515. animation.setKeys(keys);
  41516. if (this.stopOtherAnimations) {
  41517. scene.stopAnimation(this._effectiveTarget);
  41518. }
  41519. var wrapper = function () {
  41520. _this.onInterpolationDoneObservable.notifyObservers(_this);
  41521. if (_this.onInterpolationDone) {
  41522. _this.onInterpolationDone();
  41523. }
  41524. };
  41525. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  41526. };
  41527. InterpolateValueAction.prototype.serialize = function (parent) {
  41528. return _super.prototype._serialize.call(this, {
  41529. name: "InterpolateValueAction",
  41530. properties: [
  41531. BABYLON.Action._GetTargetProperty(this._target),
  41532. { name: "propertyPath", value: this.propertyPath },
  41533. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  41534. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  41535. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  41536. ]
  41537. }, parent);
  41538. };
  41539. return InterpolateValueAction;
  41540. }(BABYLON.Action));
  41541. BABYLON.InterpolateValueAction = InterpolateValueAction;
  41542. })(BABYLON || (BABYLON = {}));
  41543. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  41544. var BABYLON;
  41545. (function (BABYLON) {
  41546. var SwitchBooleanAction = /** @class */ (function (_super) {
  41547. __extends(SwitchBooleanAction, _super);
  41548. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  41549. var _this = _super.call(this, triggerOptions, condition) || this;
  41550. _this.propertyPath = propertyPath;
  41551. _this._target = _this._effectiveTarget = target;
  41552. return _this;
  41553. }
  41554. SwitchBooleanAction.prototype._prepare = function () {
  41555. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  41556. this._property = this._getProperty(this.propertyPath);
  41557. };
  41558. SwitchBooleanAction.prototype.execute = function () {
  41559. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  41560. };
  41561. SwitchBooleanAction.prototype.serialize = function (parent) {
  41562. return _super.prototype._serialize.call(this, {
  41563. name: "SwitchBooleanAction",
  41564. properties: [
  41565. BABYLON.Action._GetTargetProperty(this._target),
  41566. { name: "propertyPath", value: this.propertyPath }
  41567. ]
  41568. }, parent);
  41569. };
  41570. return SwitchBooleanAction;
  41571. }(BABYLON.Action));
  41572. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  41573. var SetStateAction = /** @class */ (function (_super) {
  41574. __extends(SetStateAction, _super);
  41575. function SetStateAction(triggerOptions, target, value, condition) {
  41576. var _this = _super.call(this, triggerOptions, condition) || this;
  41577. _this.value = value;
  41578. _this._target = target;
  41579. return _this;
  41580. }
  41581. SetStateAction.prototype.execute = function () {
  41582. this._target.state = this.value;
  41583. };
  41584. SetStateAction.prototype.serialize = function (parent) {
  41585. return _super.prototype._serialize.call(this, {
  41586. name: "SetStateAction",
  41587. properties: [
  41588. BABYLON.Action._GetTargetProperty(this._target),
  41589. { name: "value", value: this.value }
  41590. ]
  41591. }, parent);
  41592. };
  41593. return SetStateAction;
  41594. }(BABYLON.Action));
  41595. BABYLON.SetStateAction = SetStateAction;
  41596. var SetValueAction = /** @class */ (function (_super) {
  41597. __extends(SetValueAction, _super);
  41598. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  41599. var _this = _super.call(this, triggerOptions, condition) || this;
  41600. _this.propertyPath = propertyPath;
  41601. _this.value = value;
  41602. _this._target = _this._effectiveTarget = target;
  41603. return _this;
  41604. }
  41605. SetValueAction.prototype._prepare = function () {
  41606. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  41607. this._property = this._getProperty(this.propertyPath);
  41608. };
  41609. SetValueAction.prototype.execute = function () {
  41610. this._effectiveTarget[this._property] = this.value;
  41611. if (this._target.markAsDirty) {
  41612. this._target.markAsDirty(this._property);
  41613. }
  41614. };
  41615. SetValueAction.prototype.serialize = function (parent) {
  41616. return _super.prototype._serialize.call(this, {
  41617. name: "SetValueAction",
  41618. properties: [
  41619. BABYLON.Action._GetTargetProperty(this._target),
  41620. { name: "propertyPath", value: this.propertyPath },
  41621. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  41622. ]
  41623. }, parent);
  41624. };
  41625. return SetValueAction;
  41626. }(BABYLON.Action));
  41627. BABYLON.SetValueAction = SetValueAction;
  41628. var IncrementValueAction = /** @class */ (function (_super) {
  41629. __extends(IncrementValueAction, _super);
  41630. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  41631. var _this = _super.call(this, triggerOptions, condition) || this;
  41632. _this.propertyPath = propertyPath;
  41633. _this.value = value;
  41634. _this._target = _this._effectiveTarget = target;
  41635. return _this;
  41636. }
  41637. IncrementValueAction.prototype._prepare = function () {
  41638. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  41639. this._property = this._getProperty(this.propertyPath);
  41640. if (typeof this._effectiveTarget[this._property] !== "number") {
  41641. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  41642. }
  41643. };
  41644. IncrementValueAction.prototype.execute = function () {
  41645. this._effectiveTarget[this._property] += this.value;
  41646. if (this._target.markAsDirty) {
  41647. this._target.markAsDirty(this._property);
  41648. }
  41649. };
  41650. IncrementValueAction.prototype.serialize = function (parent) {
  41651. return _super.prototype._serialize.call(this, {
  41652. name: "IncrementValueAction",
  41653. properties: [
  41654. BABYLON.Action._GetTargetProperty(this._target),
  41655. { name: "propertyPath", value: this.propertyPath },
  41656. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  41657. ]
  41658. }, parent);
  41659. };
  41660. return IncrementValueAction;
  41661. }(BABYLON.Action));
  41662. BABYLON.IncrementValueAction = IncrementValueAction;
  41663. var PlayAnimationAction = /** @class */ (function (_super) {
  41664. __extends(PlayAnimationAction, _super);
  41665. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  41666. var _this = _super.call(this, triggerOptions, condition) || this;
  41667. _this.from = from;
  41668. _this.to = to;
  41669. _this.loop = loop;
  41670. _this._target = target;
  41671. return _this;
  41672. }
  41673. PlayAnimationAction.prototype._prepare = function () {
  41674. };
  41675. PlayAnimationAction.prototype.execute = function () {
  41676. var scene = this._actionManager.getScene();
  41677. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  41678. };
  41679. PlayAnimationAction.prototype.serialize = function (parent) {
  41680. return _super.prototype._serialize.call(this, {
  41681. name: "PlayAnimationAction",
  41682. properties: [
  41683. BABYLON.Action._GetTargetProperty(this._target),
  41684. { name: "from", value: String(this.from) },
  41685. { name: "to", value: String(this.to) },
  41686. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  41687. ]
  41688. }, parent);
  41689. };
  41690. return PlayAnimationAction;
  41691. }(BABYLON.Action));
  41692. BABYLON.PlayAnimationAction = PlayAnimationAction;
  41693. var StopAnimationAction = /** @class */ (function (_super) {
  41694. __extends(StopAnimationAction, _super);
  41695. function StopAnimationAction(triggerOptions, target, condition) {
  41696. var _this = _super.call(this, triggerOptions, condition) || this;
  41697. _this._target = target;
  41698. return _this;
  41699. }
  41700. StopAnimationAction.prototype._prepare = function () {
  41701. };
  41702. StopAnimationAction.prototype.execute = function () {
  41703. var scene = this._actionManager.getScene();
  41704. scene.stopAnimation(this._target);
  41705. };
  41706. StopAnimationAction.prototype.serialize = function (parent) {
  41707. return _super.prototype._serialize.call(this, {
  41708. name: "StopAnimationAction",
  41709. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  41710. }, parent);
  41711. };
  41712. return StopAnimationAction;
  41713. }(BABYLON.Action));
  41714. BABYLON.StopAnimationAction = StopAnimationAction;
  41715. var DoNothingAction = /** @class */ (function (_super) {
  41716. __extends(DoNothingAction, _super);
  41717. function DoNothingAction(triggerOptions, condition) {
  41718. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  41719. return _super.call(this, triggerOptions, condition) || this;
  41720. }
  41721. DoNothingAction.prototype.execute = function () {
  41722. };
  41723. DoNothingAction.prototype.serialize = function (parent) {
  41724. return _super.prototype._serialize.call(this, {
  41725. name: "DoNothingAction",
  41726. properties: []
  41727. }, parent);
  41728. };
  41729. return DoNothingAction;
  41730. }(BABYLON.Action));
  41731. BABYLON.DoNothingAction = DoNothingAction;
  41732. var CombineAction = /** @class */ (function (_super) {
  41733. __extends(CombineAction, _super);
  41734. function CombineAction(triggerOptions, children, condition) {
  41735. var _this = _super.call(this, triggerOptions, condition) || this;
  41736. _this.children = children;
  41737. return _this;
  41738. }
  41739. CombineAction.prototype._prepare = function () {
  41740. for (var index = 0; index < this.children.length; index++) {
  41741. this.children[index]._actionManager = this._actionManager;
  41742. this.children[index]._prepare();
  41743. }
  41744. };
  41745. CombineAction.prototype.execute = function (evt) {
  41746. for (var index = 0; index < this.children.length; index++) {
  41747. this.children[index].execute(evt);
  41748. }
  41749. };
  41750. CombineAction.prototype.serialize = function (parent) {
  41751. var serializationObject = _super.prototype._serialize.call(this, {
  41752. name: "CombineAction",
  41753. properties: [],
  41754. combine: []
  41755. }, parent);
  41756. for (var i = 0; i < this.children.length; i++) {
  41757. serializationObject.combine.push(this.children[i].serialize(null));
  41758. }
  41759. return serializationObject;
  41760. };
  41761. return CombineAction;
  41762. }(BABYLON.Action));
  41763. BABYLON.CombineAction = CombineAction;
  41764. var ExecuteCodeAction = /** @class */ (function (_super) {
  41765. __extends(ExecuteCodeAction, _super);
  41766. function ExecuteCodeAction(triggerOptions, func, condition) {
  41767. var _this = _super.call(this, triggerOptions, condition) || this;
  41768. _this.func = func;
  41769. return _this;
  41770. }
  41771. ExecuteCodeAction.prototype.execute = function (evt) {
  41772. this.func(evt);
  41773. };
  41774. return ExecuteCodeAction;
  41775. }(BABYLON.Action));
  41776. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  41777. var SetParentAction = /** @class */ (function (_super) {
  41778. __extends(SetParentAction, _super);
  41779. function SetParentAction(triggerOptions, target, parent, condition) {
  41780. var _this = _super.call(this, triggerOptions, condition) || this;
  41781. _this._target = target;
  41782. _this._parent = parent;
  41783. return _this;
  41784. }
  41785. SetParentAction.prototype._prepare = function () {
  41786. };
  41787. SetParentAction.prototype.execute = function () {
  41788. if (this._target.parent === this._parent) {
  41789. return;
  41790. }
  41791. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  41792. invertParentWorldMatrix.invert();
  41793. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  41794. this._target.parent = this._parent;
  41795. };
  41796. SetParentAction.prototype.serialize = function (parent) {
  41797. return _super.prototype._serialize.call(this, {
  41798. name: "SetParentAction",
  41799. properties: [
  41800. BABYLON.Action._GetTargetProperty(this._target),
  41801. BABYLON.Action._GetTargetProperty(this._parent),
  41802. ]
  41803. }, parent);
  41804. };
  41805. return SetParentAction;
  41806. }(BABYLON.Action));
  41807. BABYLON.SetParentAction = SetParentAction;
  41808. var PlaySoundAction = /** @class */ (function (_super) {
  41809. __extends(PlaySoundAction, _super);
  41810. function PlaySoundAction(triggerOptions, sound, condition) {
  41811. var _this = _super.call(this, triggerOptions, condition) || this;
  41812. _this._sound = sound;
  41813. return _this;
  41814. }
  41815. PlaySoundAction.prototype._prepare = function () {
  41816. };
  41817. PlaySoundAction.prototype.execute = function () {
  41818. if (this._sound !== undefined)
  41819. this._sound.play();
  41820. };
  41821. PlaySoundAction.prototype.serialize = function (parent) {
  41822. return _super.prototype._serialize.call(this, {
  41823. name: "PlaySoundAction",
  41824. properties: [{ name: "sound", value: this._sound.name }]
  41825. }, parent);
  41826. };
  41827. return PlaySoundAction;
  41828. }(BABYLON.Action));
  41829. BABYLON.PlaySoundAction = PlaySoundAction;
  41830. var StopSoundAction = /** @class */ (function (_super) {
  41831. __extends(StopSoundAction, _super);
  41832. function StopSoundAction(triggerOptions, sound, condition) {
  41833. var _this = _super.call(this, triggerOptions, condition) || this;
  41834. _this._sound = sound;
  41835. return _this;
  41836. }
  41837. StopSoundAction.prototype._prepare = function () {
  41838. };
  41839. StopSoundAction.prototype.execute = function () {
  41840. if (this._sound !== undefined)
  41841. this._sound.stop();
  41842. };
  41843. StopSoundAction.prototype.serialize = function (parent) {
  41844. return _super.prototype._serialize.call(this, {
  41845. name: "StopSoundAction",
  41846. properties: [{ name: "sound", value: this._sound.name }]
  41847. }, parent);
  41848. };
  41849. return StopSoundAction;
  41850. }(BABYLON.Action));
  41851. BABYLON.StopSoundAction = StopSoundAction;
  41852. })(BABYLON || (BABYLON = {}));
  41853. //# sourceMappingURL=babylon.directActions.js.map
  41854. var BABYLON;
  41855. (function (BABYLON) {
  41856. var SpriteManager = /** @class */ (function () {
  41857. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  41858. if (epsilon === void 0) { epsilon = 0.01; }
  41859. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41860. this.name = name;
  41861. this.sprites = new Array();
  41862. this.renderingGroupId = 0;
  41863. this.layerMask = 0x0FFFFFFF;
  41864. this.fogEnabled = true;
  41865. this.isPickable = false;
  41866. /**
  41867. * An event triggered when the manager is disposed.
  41868. * @type {BABYLON.Observable}
  41869. */
  41870. this.onDisposeObservable = new BABYLON.Observable();
  41871. this._vertexBuffers = {};
  41872. this._capacity = capacity;
  41873. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  41874. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41875. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41876. if (cellSize.width && cellSize.height) {
  41877. this.cellWidth = cellSize.width;
  41878. this.cellHeight = cellSize.height;
  41879. }
  41880. else if (cellSize !== undefined) {
  41881. this.cellWidth = cellSize;
  41882. this.cellHeight = cellSize;
  41883. }
  41884. else {
  41885. return;
  41886. }
  41887. this._epsilon = epsilon;
  41888. this._scene = scene;
  41889. this._scene.spriteManagers.push(this);
  41890. var indices = [];
  41891. var index = 0;
  41892. for (var count = 0; count < capacity; count++) {
  41893. indices.push(index);
  41894. indices.push(index + 1);
  41895. indices.push(index + 2);
  41896. indices.push(index);
  41897. indices.push(index + 2);
  41898. indices.push(index + 3);
  41899. index += 4;
  41900. }
  41901. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  41902. // VBO
  41903. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  41904. this._vertexData = new Float32Array(capacity * 16 * 4);
  41905. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  41906. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  41907. var options = this._buffer.createVertexBuffer("options", 4, 4);
  41908. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  41909. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  41910. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  41911. this._vertexBuffers["options"] = options;
  41912. this._vertexBuffers["cellInfo"] = cellInfo;
  41913. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  41914. // Effects
  41915. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  41916. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  41917. }
  41918. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  41919. set: function (callback) {
  41920. if (this._onDisposeObserver) {
  41921. this.onDisposeObservable.remove(this._onDisposeObserver);
  41922. }
  41923. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  41924. },
  41925. enumerable: true,
  41926. configurable: true
  41927. });
  41928. Object.defineProperty(SpriteManager.prototype, "texture", {
  41929. get: function () {
  41930. return this._spriteTexture;
  41931. },
  41932. set: function (value) {
  41933. this._spriteTexture = value;
  41934. },
  41935. enumerable: true,
  41936. configurable: true
  41937. });
  41938. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  41939. var arrayOffset = index * 16;
  41940. if (offsetX === 0)
  41941. offsetX = this._epsilon;
  41942. else if (offsetX === 1)
  41943. offsetX = 1 - this._epsilon;
  41944. if (offsetY === 0)
  41945. offsetY = this._epsilon;
  41946. else if (offsetY === 1)
  41947. offsetY = 1 - this._epsilon;
  41948. this._vertexData[arrayOffset] = sprite.position.x;
  41949. this._vertexData[arrayOffset + 1] = sprite.position.y;
  41950. this._vertexData[arrayOffset + 2] = sprite.position.z;
  41951. this._vertexData[arrayOffset + 3] = sprite.angle;
  41952. this._vertexData[arrayOffset + 4] = sprite.width;
  41953. this._vertexData[arrayOffset + 5] = sprite.height;
  41954. this._vertexData[arrayOffset + 6] = offsetX;
  41955. this._vertexData[arrayOffset + 7] = offsetY;
  41956. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  41957. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  41958. var offset = (sprite.cellIndex / rowSize) >> 0;
  41959. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  41960. this._vertexData[arrayOffset + 11] = offset;
  41961. // Color
  41962. this._vertexData[arrayOffset + 12] = sprite.color.r;
  41963. this._vertexData[arrayOffset + 13] = sprite.color.g;
  41964. this._vertexData[arrayOffset + 14] = sprite.color.b;
  41965. this._vertexData[arrayOffset + 15] = sprite.color.a;
  41966. };
  41967. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  41968. var count = Math.min(this._capacity, this.sprites.length);
  41969. var min = BABYLON.Vector3.Zero();
  41970. var max = BABYLON.Vector3.Zero();
  41971. var distance = Number.MAX_VALUE;
  41972. var currentSprite;
  41973. var cameraSpacePosition = BABYLON.Vector3.Zero();
  41974. var cameraView = camera.getViewMatrix();
  41975. for (var index = 0; index < count; index++) {
  41976. var sprite = this.sprites[index];
  41977. if (!sprite) {
  41978. continue;
  41979. }
  41980. if (predicate) {
  41981. if (!predicate(sprite)) {
  41982. continue;
  41983. }
  41984. }
  41985. else if (!sprite.isPickable) {
  41986. continue;
  41987. }
  41988. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  41989. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  41990. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  41991. if (ray.intersectsBoxMinMax(min, max)) {
  41992. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  41993. if (distance > currentDistance) {
  41994. distance = currentDistance;
  41995. currentSprite = sprite;
  41996. if (fastCheck) {
  41997. break;
  41998. }
  41999. }
  42000. }
  42001. }
  42002. if (currentSprite) {
  42003. var result = new BABYLON.PickingInfo();
  42004. result.hit = true;
  42005. result.pickedSprite = currentSprite;
  42006. result.distance = distance;
  42007. return result;
  42008. }
  42009. return null;
  42010. };
  42011. SpriteManager.prototype.render = function () {
  42012. // Check
  42013. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  42014. return;
  42015. var engine = this._scene.getEngine();
  42016. var baseSize = this._spriteTexture.getBaseSize();
  42017. // Sprites
  42018. var deltaTime = engine.getDeltaTime();
  42019. var max = Math.min(this._capacity, this.sprites.length);
  42020. var rowSize = baseSize.width / this.cellWidth;
  42021. var offset = 0;
  42022. for (var index = 0; index < max; index++) {
  42023. var sprite = this.sprites[index];
  42024. if (!sprite) {
  42025. continue;
  42026. }
  42027. sprite._animate(deltaTime);
  42028. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  42029. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  42030. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  42031. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  42032. }
  42033. this._buffer.update(this._vertexData);
  42034. // Render
  42035. var effect = this._effectBase;
  42036. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  42037. effect = this._effectFog;
  42038. }
  42039. engine.enableEffect(effect);
  42040. var viewMatrix = this._scene.getViewMatrix();
  42041. effect.setTexture("diffuseSampler", this._spriteTexture);
  42042. effect.setMatrix("view", viewMatrix);
  42043. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  42044. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  42045. // Fog
  42046. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  42047. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  42048. effect.setColor3("vFogColor", this._scene.fogColor);
  42049. }
  42050. // VBOs
  42051. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  42052. // Draw order
  42053. engine.setDepthFunctionToLessOrEqual();
  42054. effect.setBool("alphaTest", true);
  42055. engine.setColorWrite(false);
  42056. engine.draw(true, 0, max * 6);
  42057. engine.setColorWrite(true);
  42058. effect.setBool("alphaTest", false);
  42059. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  42060. engine.draw(true, 0, max * 6);
  42061. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  42062. };
  42063. SpriteManager.prototype.dispose = function () {
  42064. if (this._buffer) {
  42065. this._buffer.dispose();
  42066. this._buffer = null;
  42067. }
  42068. if (this._indexBuffer) {
  42069. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  42070. this._indexBuffer = null;
  42071. }
  42072. if (this._spriteTexture) {
  42073. this._spriteTexture.dispose();
  42074. this._spriteTexture = null;
  42075. }
  42076. // Remove from scene
  42077. var index = this._scene.spriteManagers.indexOf(this);
  42078. this._scene.spriteManagers.splice(index, 1);
  42079. // Callback
  42080. this.onDisposeObservable.notifyObservers(this);
  42081. this.onDisposeObservable.clear();
  42082. };
  42083. return SpriteManager;
  42084. }());
  42085. BABYLON.SpriteManager = SpriteManager;
  42086. })(BABYLON || (BABYLON = {}));
  42087. //# sourceMappingURL=babylon.spriteManager.js.map
  42088. var BABYLON;
  42089. (function (BABYLON) {
  42090. var Sprite = /** @class */ (function () {
  42091. function Sprite(name, manager) {
  42092. this.name = name;
  42093. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  42094. this.width = 1.0;
  42095. this.height = 1.0;
  42096. this.angle = 0;
  42097. this.cellIndex = 0;
  42098. this.invertU = 0;
  42099. this.invertV = 0;
  42100. this.animations = new Array();
  42101. this.isPickable = false;
  42102. this._animationStarted = false;
  42103. this._loopAnimation = false;
  42104. this._fromIndex = 0;
  42105. this._toIndex = 0;
  42106. this._delay = 0;
  42107. this._direction = 1;
  42108. this._time = 0;
  42109. this._manager = manager;
  42110. this._manager.sprites.push(this);
  42111. this.position = BABYLON.Vector3.Zero();
  42112. }
  42113. Object.defineProperty(Sprite.prototype, "size", {
  42114. get: function () {
  42115. return this.width;
  42116. },
  42117. set: function (value) {
  42118. this.width = value;
  42119. this.height = value;
  42120. },
  42121. enumerable: true,
  42122. configurable: true
  42123. });
  42124. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  42125. this._fromIndex = from;
  42126. this._toIndex = to;
  42127. this._loopAnimation = loop;
  42128. this._delay = delay;
  42129. this._animationStarted = true;
  42130. this._direction = from < to ? 1 : -1;
  42131. this.cellIndex = from;
  42132. this._time = 0;
  42133. this._onAnimationEnd = onAnimationEnd;
  42134. };
  42135. Sprite.prototype.stopAnimation = function () {
  42136. this._animationStarted = false;
  42137. };
  42138. Sprite.prototype._animate = function (deltaTime) {
  42139. if (!this._animationStarted)
  42140. return;
  42141. this._time += deltaTime;
  42142. if (this._time > this._delay) {
  42143. this._time = this._time % this._delay;
  42144. this.cellIndex += this._direction;
  42145. if (this.cellIndex > this._toIndex) {
  42146. if (this._loopAnimation) {
  42147. this.cellIndex = this._fromIndex;
  42148. }
  42149. else {
  42150. this.cellIndex = this._toIndex;
  42151. this._animationStarted = false;
  42152. if (this._onAnimationEnd) {
  42153. this._onAnimationEnd();
  42154. }
  42155. if (this.disposeWhenFinishedAnimating) {
  42156. this.dispose();
  42157. }
  42158. }
  42159. }
  42160. }
  42161. };
  42162. Sprite.prototype.dispose = function () {
  42163. for (var i = 0; i < this._manager.sprites.length; i++) {
  42164. if (this._manager.sprites[i] == this) {
  42165. this._manager.sprites.splice(i, 1);
  42166. }
  42167. }
  42168. };
  42169. return Sprite;
  42170. }());
  42171. BABYLON.Sprite = Sprite;
  42172. })(BABYLON || (BABYLON = {}));
  42173. //# sourceMappingURL=babylon.sprite.js.map
  42174. var BABYLON;
  42175. (function (BABYLON) {
  42176. var IntersectionInfo = /** @class */ (function () {
  42177. function IntersectionInfo(bu, bv, distance) {
  42178. this.bu = bu;
  42179. this.bv = bv;
  42180. this.distance = distance;
  42181. this.faceId = 0;
  42182. this.subMeshId = 0;
  42183. }
  42184. return IntersectionInfo;
  42185. }());
  42186. BABYLON.IntersectionInfo = IntersectionInfo;
  42187. var PickingInfo = /** @class */ (function () {
  42188. function PickingInfo() {
  42189. this.hit = false;
  42190. this.distance = 0;
  42191. this.pickedPoint = null;
  42192. this.pickedMesh = null;
  42193. this.bu = 0;
  42194. this.bv = 0;
  42195. this.faceId = -1;
  42196. this.subMeshId = 0;
  42197. this.pickedSprite = null;
  42198. }
  42199. // Methods
  42200. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  42201. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  42202. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  42203. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  42204. return null;
  42205. }
  42206. var indices = this.pickedMesh.getIndices();
  42207. if (!indices) {
  42208. return null;
  42209. }
  42210. var result;
  42211. if (useVerticesNormals) {
  42212. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  42213. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  42214. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  42215. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  42216. normal0 = normal0.scale(this.bu);
  42217. normal1 = normal1.scale(this.bv);
  42218. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  42219. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  42220. }
  42221. else {
  42222. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42223. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  42224. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  42225. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  42226. var p1p2 = vertex1.subtract(vertex2);
  42227. var p3p2 = vertex3.subtract(vertex2);
  42228. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  42229. }
  42230. if (useWorldCoordinates) {
  42231. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  42232. }
  42233. return BABYLON.Vector3.Normalize(result);
  42234. };
  42235. PickingInfo.prototype.getTextureCoordinates = function () {
  42236. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  42237. return null;
  42238. }
  42239. var indices = this.pickedMesh.getIndices();
  42240. if (!indices) {
  42241. return null;
  42242. }
  42243. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42244. if (!uvs) {
  42245. return null;
  42246. }
  42247. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  42248. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  42249. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  42250. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  42251. uv1 = uv1.scale(this.bu);
  42252. uv2 = uv2.scale(this.bv);
  42253. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  42254. };
  42255. return PickingInfo;
  42256. }());
  42257. BABYLON.PickingInfo = PickingInfo;
  42258. })(BABYLON || (BABYLON = {}));
  42259. //# sourceMappingURL=babylon.pickingInfo.js.map
  42260. var BABYLON;
  42261. (function (BABYLON) {
  42262. var Ray = /** @class */ (function () {
  42263. function Ray(origin, direction, length) {
  42264. if (length === void 0) { length = Number.MAX_VALUE; }
  42265. this.origin = origin;
  42266. this.direction = direction;
  42267. this.length = length;
  42268. }
  42269. // Methods
  42270. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  42271. var d = 0.0;
  42272. var maxValue = Number.MAX_VALUE;
  42273. var inv;
  42274. var min;
  42275. var max;
  42276. var temp;
  42277. if (Math.abs(this.direction.x) < 0.0000001) {
  42278. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  42279. return false;
  42280. }
  42281. }
  42282. else {
  42283. inv = 1.0 / this.direction.x;
  42284. min = (minimum.x - this.origin.x) * inv;
  42285. max = (maximum.x - this.origin.x) * inv;
  42286. if (max === -Infinity) {
  42287. max = Infinity;
  42288. }
  42289. if (min > max) {
  42290. temp = min;
  42291. min = max;
  42292. max = temp;
  42293. }
  42294. d = Math.max(min, d);
  42295. maxValue = Math.min(max, maxValue);
  42296. if (d > maxValue) {
  42297. return false;
  42298. }
  42299. }
  42300. if (Math.abs(this.direction.y) < 0.0000001) {
  42301. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  42302. return false;
  42303. }
  42304. }
  42305. else {
  42306. inv = 1.0 / this.direction.y;
  42307. min = (minimum.y - this.origin.y) * inv;
  42308. max = (maximum.y - this.origin.y) * inv;
  42309. if (max === -Infinity) {
  42310. max = Infinity;
  42311. }
  42312. if (min > max) {
  42313. temp = min;
  42314. min = max;
  42315. max = temp;
  42316. }
  42317. d = Math.max(min, d);
  42318. maxValue = Math.min(max, maxValue);
  42319. if (d > maxValue) {
  42320. return false;
  42321. }
  42322. }
  42323. if (Math.abs(this.direction.z) < 0.0000001) {
  42324. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  42325. return false;
  42326. }
  42327. }
  42328. else {
  42329. inv = 1.0 / this.direction.z;
  42330. min = (minimum.z - this.origin.z) * inv;
  42331. max = (maximum.z - this.origin.z) * inv;
  42332. if (max === -Infinity) {
  42333. max = Infinity;
  42334. }
  42335. if (min > max) {
  42336. temp = min;
  42337. min = max;
  42338. max = temp;
  42339. }
  42340. d = Math.max(min, d);
  42341. maxValue = Math.min(max, maxValue);
  42342. if (d > maxValue) {
  42343. return false;
  42344. }
  42345. }
  42346. return true;
  42347. };
  42348. Ray.prototype.intersectsBox = function (box) {
  42349. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  42350. };
  42351. Ray.prototype.intersectsSphere = function (sphere) {
  42352. var x = sphere.center.x - this.origin.x;
  42353. var y = sphere.center.y - this.origin.y;
  42354. var z = sphere.center.z - this.origin.z;
  42355. var pyth = (x * x) + (y * y) + (z * z);
  42356. var rr = sphere.radius * sphere.radius;
  42357. if (pyth <= rr) {
  42358. return true;
  42359. }
  42360. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  42361. if (dot < 0.0) {
  42362. return false;
  42363. }
  42364. var temp = pyth - (dot * dot);
  42365. return temp <= rr;
  42366. };
  42367. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  42368. if (!this._edge1) {
  42369. this._edge1 = BABYLON.Vector3.Zero();
  42370. this._edge2 = BABYLON.Vector3.Zero();
  42371. this._pvec = BABYLON.Vector3.Zero();
  42372. this._tvec = BABYLON.Vector3.Zero();
  42373. this._qvec = BABYLON.Vector3.Zero();
  42374. }
  42375. vertex1.subtractToRef(vertex0, this._edge1);
  42376. vertex2.subtractToRef(vertex0, this._edge2);
  42377. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  42378. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  42379. if (det === 0) {
  42380. return null;
  42381. }
  42382. var invdet = 1 / det;
  42383. this.origin.subtractToRef(vertex0, this._tvec);
  42384. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  42385. if (bu < 0 || bu > 1.0) {
  42386. return null;
  42387. }
  42388. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  42389. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  42390. if (bv < 0 || bu + bv > 1.0) {
  42391. return null;
  42392. }
  42393. //check if the distance is longer than the predefined length.
  42394. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  42395. if (distance > this.length) {
  42396. return null;
  42397. }
  42398. return new BABYLON.IntersectionInfo(bu, bv, distance);
  42399. };
  42400. Ray.prototype.intersectsPlane = function (plane) {
  42401. var distance;
  42402. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  42403. if (Math.abs(result1) < 9.99999997475243E-07) {
  42404. return null;
  42405. }
  42406. else {
  42407. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  42408. distance = (-plane.d - result2) / result1;
  42409. if (distance < 0.0) {
  42410. if (distance < -9.99999997475243E-07) {
  42411. return null;
  42412. }
  42413. else {
  42414. return 0;
  42415. }
  42416. }
  42417. return distance;
  42418. }
  42419. };
  42420. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  42421. var tm = BABYLON.Tmp.Matrix[0];
  42422. mesh.getWorldMatrix().invertToRef(tm);
  42423. if (this._tmpRay) {
  42424. Ray.TransformToRef(this, tm, this._tmpRay);
  42425. }
  42426. else {
  42427. this._tmpRay = Ray.Transform(this, tm);
  42428. }
  42429. return mesh.intersects(this._tmpRay, fastCheck);
  42430. };
  42431. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  42432. if (results) {
  42433. results.length = 0;
  42434. }
  42435. else {
  42436. results = [];
  42437. }
  42438. for (var i = 0; i < meshes.length; i++) {
  42439. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  42440. if (pickInfo.hit) {
  42441. results.push(pickInfo);
  42442. }
  42443. }
  42444. results.sort(this._comparePickingInfo);
  42445. return results;
  42446. };
  42447. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  42448. if (pickingInfoA.distance < pickingInfoB.distance) {
  42449. return -1;
  42450. }
  42451. else if (pickingInfoA.distance > pickingInfoB.distance) {
  42452. return 1;
  42453. }
  42454. else {
  42455. return 0;
  42456. }
  42457. };
  42458. /**
  42459. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  42460. * @param sega the first point of the segment to test the intersection against
  42461. * @param segb the second point of the segment to test the intersection against
  42462. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  42463. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  42464. */
  42465. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  42466. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  42467. var u = segb.subtract(sega);
  42468. var v = rsegb.subtract(this.origin);
  42469. var w = sega.subtract(this.origin);
  42470. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  42471. var b = BABYLON.Vector3.Dot(u, v);
  42472. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  42473. var d = BABYLON.Vector3.Dot(u, w);
  42474. var e = BABYLON.Vector3.Dot(v, w);
  42475. var D = a * c - b * b; // always >= 0
  42476. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  42477. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  42478. // compute the line parameters of the two closest points
  42479. if (D < Ray.smallnum) {
  42480. sN = 0.0; // force using point P0 on segment S1
  42481. sD = 1.0; // to prevent possible division by 0.0 later
  42482. tN = e;
  42483. tD = c;
  42484. }
  42485. else {
  42486. sN = (b * e - c * d);
  42487. tN = (a * e - b * d);
  42488. if (sN < 0.0) {
  42489. sN = 0.0;
  42490. tN = e;
  42491. tD = c;
  42492. }
  42493. else if (sN > sD) {
  42494. sN = sD;
  42495. tN = e + b;
  42496. tD = c;
  42497. }
  42498. }
  42499. if (tN < 0.0) {
  42500. tN = 0.0;
  42501. // recompute sc for this edge
  42502. if (-d < 0.0) {
  42503. sN = 0.0;
  42504. }
  42505. else if (-d > a)
  42506. sN = sD;
  42507. else {
  42508. sN = -d;
  42509. sD = a;
  42510. }
  42511. }
  42512. else if (tN > tD) {
  42513. tN = tD;
  42514. // recompute sc for this edge
  42515. if ((-d + b) < 0.0) {
  42516. sN = 0;
  42517. }
  42518. else if ((-d + b) > a) {
  42519. sN = sD;
  42520. }
  42521. else {
  42522. sN = (-d + b);
  42523. sD = a;
  42524. }
  42525. }
  42526. // finally do the division to get sc and tc
  42527. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  42528. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  42529. // get the difference of the two closest points
  42530. var qtc = v.multiplyByFloats(tc, tc, tc);
  42531. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  42532. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  42533. if (isIntersected) {
  42534. return qtc.length();
  42535. }
  42536. return -1;
  42537. };
  42538. // Statics
  42539. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  42540. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  42541. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  42542. var direction = end.subtract(start);
  42543. direction.normalize();
  42544. return new Ray(start, direction);
  42545. };
  42546. /**
  42547. * 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
  42548. * transformed to the given world matrix.
  42549. * @param origin The origin point
  42550. * @param end The end point
  42551. * @param world a matrix to transform the ray to. Default is the identity matrix.
  42552. */
  42553. Ray.CreateNewFromTo = function (origin, end, world) {
  42554. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  42555. var direction = end.subtract(origin);
  42556. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  42557. direction.normalize();
  42558. return Ray.Transform(new Ray(origin, direction, length), world);
  42559. };
  42560. Ray.Transform = function (ray, matrix) {
  42561. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  42562. Ray.TransformToRef(ray, matrix, result);
  42563. return result;
  42564. };
  42565. Ray.TransformToRef = function (ray, matrix, result) {
  42566. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  42567. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  42568. result.length = ray.length;
  42569. var dir = result.direction;
  42570. var len = dir.length();
  42571. if (!(len === 0 || len === 1)) {
  42572. var num = 1.0 / len;
  42573. dir.x *= num;
  42574. dir.y *= num;
  42575. dir.z *= num;
  42576. result.length *= len;
  42577. }
  42578. };
  42579. Ray.smallnum = 0.00000001;
  42580. Ray.rayl = 10e8;
  42581. return Ray;
  42582. }());
  42583. BABYLON.Ray = Ray;
  42584. })(BABYLON || (BABYLON = {}));
  42585. //# sourceMappingURL=babylon.ray.js.map
  42586. var BABYLON;
  42587. (function (BABYLON) {
  42588. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  42589. if (boxMin.x > sphereCenter.x + sphereRadius)
  42590. return false;
  42591. if (sphereCenter.x - sphereRadius > boxMax.x)
  42592. return false;
  42593. if (boxMin.y > sphereCenter.y + sphereRadius)
  42594. return false;
  42595. if (sphereCenter.y - sphereRadius > boxMax.y)
  42596. return false;
  42597. if (boxMin.z > sphereCenter.z + sphereRadius)
  42598. return false;
  42599. if (sphereCenter.z - sphereRadius > boxMax.z)
  42600. return false;
  42601. return true;
  42602. };
  42603. var getLowestRoot = (function () {
  42604. var result = { root: 0, found: false };
  42605. return function (a, b, c, maxR) {
  42606. result.root = 0;
  42607. result.found = false;
  42608. var determinant = b * b - 4.0 * a * c;
  42609. if (determinant < 0)
  42610. return result;
  42611. var sqrtD = Math.sqrt(determinant);
  42612. var r1 = (-b - sqrtD) / (2.0 * a);
  42613. var r2 = (-b + sqrtD) / (2.0 * a);
  42614. if (r1 > r2) {
  42615. var temp = r2;
  42616. r2 = r1;
  42617. r1 = temp;
  42618. }
  42619. if (r1 > 0 && r1 < maxR) {
  42620. result.root = r1;
  42621. result.found = true;
  42622. return result;
  42623. }
  42624. if (r2 > 0 && r2 < maxR) {
  42625. result.root = r2;
  42626. result.found = true;
  42627. return result;
  42628. }
  42629. return result;
  42630. };
  42631. })();
  42632. var Collider = /** @class */ (function () {
  42633. function Collider() {
  42634. this.radius = BABYLON.Vector3.One();
  42635. this.retry = 0;
  42636. this.basePointWorld = BABYLON.Vector3.Zero();
  42637. this.velocityWorld = BABYLON.Vector3.Zero();
  42638. this.normalizedVelocity = BABYLON.Vector3.Zero();
  42639. this._collisionPoint = BABYLON.Vector3.Zero();
  42640. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  42641. this._tempVector = BABYLON.Vector3.Zero();
  42642. this._tempVector2 = BABYLON.Vector3.Zero();
  42643. this._tempVector3 = BABYLON.Vector3.Zero();
  42644. this._tempVector4 = BABYLON.Vector3.Zero();
  42645. this._edge = BABYLON.Vector3.Zero();
  42646. this._baseToVertex = BABYLON.Vector3.Zero();
  42647. this._destinationPoint = BABYLON.Vector3.Zero();
  42648. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  42649. this._displacementVector = BABYLON.Vector3.Zero();
  42650. this._collisionMask = -1;
  42651. }
  42652. Object.defineProperty(Collider.prototype, "collisionMask", {
  42653. get: function () {
  42654. return this._collisionMask;
  42655. },
  42656. set: function (mask) {
  42657. this._collisionMask = !isNaN(mask) ? mask : -1;
  42658. },
  42659. enumerable: true,
  42660. configurable: true
  42661. });
  42662. // Methods
  42663. Collider.prototype._initialize = function (source, dir, e) {
  42664. this.velocity = dir;
  42665. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  42666. this.basePoint = source;
  42667. source.multiplyToRef(this.radius, this.basePointWorld);
  42668. dir.multiplyToRef(this.radius, this.velocityWorld);
  42669. this.velocityWorldLength = this.velocityWorld.length();
  42670. this.epsilon = e;
  42671. this.collisionFound = false;
  42672. };
  42673. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  42674. pa.subtractToRef(point, this._tempVector);
  42675. pb.subtractToRef(point, this._tempVector2);
  42676. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  42677. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  42678. if (d < 0)
  42679. return false;
  42680. pc.subtractToRef(point, this._tempVector3);
  42681. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  42682. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  42683. if (d < 0)
  42684. return false;
  42685. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  42686. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  42687. return d >= 0;
  42688. };
  42689. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  42690. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  42691. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  42692. if (distance > this.velocityWorldLength + max + sphereRadius) {
  42693. return false;
  42694. }
  42695. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  42696. return false;
  42697. return true;
  42698. };
  42699. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  42700. var t0;
  42701. var embeddedInPlane = false;
  42702. //defensive programming, actually not needed.
  42703. if (!trianglePlaneArray) {
  42704. trianglePlaneArray = [];
  42705. }
  42706. if (!trianglePlaneArray[faceIndex]) {
  42707. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  42708. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  42709. }
  42710. var trianglePlane = trianglePlaneArray[faceIndex];
  42711. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  42712. return;
  42713. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  42714. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  42715. if (normalDotVelocity == 0) {
  42716. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  42717. return;
  42718. embeddedInPlane = true;
  42719. t0 = 0;
  42720. }
  42721. else {
  42722. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  42723. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  42724. if (t0 > t1) {
  42725. var temp = t1;
  42726. t1 = t0;
  42727. t0 = temp;
  42728. }
  42729. if (t0 > 1.0 || t1 < 0.0)
  42730. return;
  42731. if (t0 < 0)
  42732. t0 = 0;
  42733. if (t0 > 1.0)
  42734. t0 = 1.0;
  42735. }
  42736. this._collisionPoint.copyFromFloats(0, 0, 0);
  42737. var found = false;
  42738. var t = 1.0;
  42739. if (!embeddedInPlane) {
  42740. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  42741. this.velocity.scaleToRef(t0, this._tempVector);
  42742. this._planeIntersectionPoint.addInPlace(this._tempVector);
  42743. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  42744. found = true;
  42745. t = t0;
  42746. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  42747. }
  42748. }
  42749. if (!found) {
  42750. var velocitySquaredLength = this.velocity.lengthSquared();
  42751. var a = velocitySquaredLength;
  42752. this.basePoint.subtractToRef(p1, this._tempVector);
  42753. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  42754. var c = this._tempVector.lengthSquared() - 1.0;
  42755. var lowestRoot = getLowestRoot(a, b, c, t);
  42756. if (lowestRoot.found) {
  42757. t = lowestRoot.root;
  42758. found = true;
  42759. this._collisionPoint.copyFrom(p1);
  42760. }
  42761. this.basePoint.subtractToRef(p2, this._tempVector);
  42762. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  42763. c = this._tempVector.lengthSquared() - 1.0;
  42764. lowestRoot = getLowestRoot(a, b, c, t);
  42765. if (lowestRoot.found) {
  42766. t = lowestRoot.root;
  42767. found = true;
  42768. this._collisionPoint.copyFrom(p2);
  42769. }
  42770. this.basePoint.subtractToRef(p3, this._tempVector);
  42771. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  42772. c = this._tempVector.lengthSquared() - 1.0;
  42773. lowestRoot = getLowestRoot(a, b, c, t);
  42774. if (lowestRoot.found) {
  42775. t = lowestRoot.root;
  42776. found = true;
  42777. this._collisionPoint.copyFrom(p3);
  42778. }
  42779. p2.subtractToRef(p1, this._edge);
  42780. p1.subtractToRef(this.basePoint, this._baseToVertex);
  42781. var edgeSquaredLength = this._edge.lengthSquared();
  42782. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  42783. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  42784. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  42785. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  42786. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  42787. lowestRoot = getLowestRoot(a, b, c, t);
  42788. if (lowestRoot.found) {
  42789. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  42790. if (f >= 0.0 && f <= 1.0) {
  42791. t = lowestRoot.root;
  42792. found = true;
  42793. this._edge.scaleInPlace(f);
  42794. p1.addToRef(this._edge, this._collisionPoint);
  42795. }
  42796. }
  42797. p3.subtractToRef(p2, this._edge);
  42798. p2.subtractToRef(this.basePoint, this._baseToVertex);
  42799. edgeSquaredLength = this._edge.lengthSquared();
  42800. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  42801. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  42802. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  42803. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  42804. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  42805. lowestRoot = getLowestRoot(a, b, c, t);
  42806. if (lowestRoot.found) {
  42807. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  42808. if (f >= 0.0 && f <= 1.0) {
  42809. t = lowestRoot.root;
  42810. found = true;
  42811. this._edge.scaleInPlace(f);
  42812. p2.addToRef(this._edge, this._collisionPoint);
  42813. }
  42814. }
  42815. p1.subtractToRef(p3, this._edge);
  42816. p3.subtractToRef(this.basePoint, this._baseToVertex);
  42817. edgeSquaredLength = this._edge.lengthSquared();
  42818. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  42819. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  42820. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  42821. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  42822. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  42823. lowestRoot = getLowestRoot(a, b, c, t);
  42824. if (lowestRoot.found) {
  42825. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  42826. if (f >= 0.0 && f <= 1.0) {
  42827. t = lowestRoot.root;
  42828. found = true;
  42829. this._edge.scaleInPlace(f);
  42830. p3.addToRef(this._edge, this._collisionPoint);
  42831. }
  42832. }
  42833. }
  42834. if (found) {
  42835. var distToCollision = t * this.velocity.length();
  42836. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  42837. if (!this.intersectionPoint) {
  42838. this.intersectionPoint = this._collisionPoint.clone();
  42839. }
  42840. else {
  42841. this.intersectionPoint.copyFrom(this._collisionPoint);
  42842. }
  42843. this.nearestDistance = distToCollision;
  42844. this.collisionFound = true;
  42845. }
  42846. }
  42847. };
  42848. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  42849. for (var i = indexStart; i < indexEnd; i += 3) {
  42850. var p1 = pts[indices[i] - decal];
  42851. var p2 = pts[indices[i + 1] - decal];
  42852. var p3 = pts[indices[i + 2] - decal];
  42853. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  42854. }
  42855. };
  42856. Collider.prototype._getResponse = function (pos, vel) {
  42857. pos.addToRef(vel, this._destinationPoint);
  42858. vel.scaleInPlace((this.nearestDistance / vel.length()));
  42859. this.basePoint.addToRef(vel, pos);
  42860. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  42861. this._slidePlaneNormal.normalize();
  42862. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  42863. pos.addInPlace(this._displacementVector);
  42864. this.intersectionPoint.addInPlace(this._displacementVector);
  42865. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  42866. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  42867. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  42868. };
  42869. return Collider;
  42870. }());
  42871. BABYLON.Collider = Collider;
  42872. })(BABYLON || (BABYLON = {}));
  42873. //# sourceMappingURL=babylon.collider.js.map
  42874. var BABYLON;
  42875. (function (BABYLON) {
  42876. //WebWorker code will be inserted to this variable.
  42877. BABYLON.CollisionWorker = "";
  42878. var WorkerTaskType;
  42879. (function (WorkerTaskType) {
  42880. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  42881. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  42882. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  42883. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  42884. var WorkerReplyType;
  42885. (function (WorkerReplyType) {
  42886. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  42887. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  42888. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  42889. var CollisionCoordinatorWorker = /** @class */ (function () {
  42890. function CollisionCoordinatorWorker() {
  42891. var _this = this;
  42892. this._scaledPosition = BABYLON.Vector3.Zero();
  42893. this._scaledVelocity = BABYLON.Vector3.Zero();
  42894. this.onMeshUpdated = function (mesh) {
  42895. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  42896. };
  42897. this.onGeometryUpdated = function (geometry) {
  42898. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  42899. };
  42900. this._afterRender = function () {
  42901. if (!_this._init)
  42902. return;
  42903. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  42904. return;
  42905. }
  42906. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  42907. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  42908. if (_this._runningUpdated > 4) {
  42909. return;
  42910. }
  42911. ++_this._runningUpdated;
  42912. var payload = {
  42913. updatedMeshes: _this._addUpdateMeshesList,
  42914. updatedGeometries: _this._addUpdateGeometriesList,
  42915. removedGeometries: _this._toRemoveGeometryArray,
  42916. removedMeshes: _this._toRemoveMeshesArray
  42917. };
  42918. var message = {
  42919. payload: payload,
  42920. taskType: WorkerTaskType.UPDATE
  42921. };
  42922. var serializable = [];
  42923. for (var id in payload.updatedGeometries) {
  42924. if (payload.updatedGeometries.hasOwnProperty(id)) {
  42925. //prepare transferables
  42926. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  42927. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  42928. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  42929. }
  42930. }
  42931. _this._worker.postMessage(message, serializable);
  42932. _this._addUpdateMeshesList = {};
  42933. _this._addUpdateGeometriesList = {};
  42934. _this._toRemoveGeometryArray = [];
  42935. _this._toRemoveMeshesArray = [];
  42936. };
  42937. this._onMessageFromWorker = function (e) {
  42938. var returnData = e.data;
  42939. if (returnData.error != WorkerReplyType.SUCCESS) {
  42940. //TODO what errors can be returned from the worker?
  42941. BABYLON.Tools.Warn("error returned from worker!");
  42942. return;
  42943. }
  42944. switch (returnData.taskType) {
  42945. case WorkerTaskType.INIT:
  42946. _this._init = true;
  42947. //Update the worked with ALL of the scene's current state
  42948. _this._scene.meshes.forEach(function (mesh) {
  42949. _this.onMeshAdded(mesh);
  42950. });
  42951. _this._scene.getGeometries().forEach(function (geometry) {
  42952. _this.onGeometryAdded(geometry);
  42953. });
  42954. break;
  42955. case WorkerTaskType.UPDATE:
  42956. _this._runningUpdated--;
  42957. break;
  42958. case WorkerTaskType.COLLIDE:
  42959. _this._runningCollisionTask = false;
  42960. var returnPayload = returnData.payload;
  42961. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  42962. return;
  42963. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  42964. if (callback) {
  42965. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  42966. if (mesh) {
  42967. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  42968. }
  42969. }
  42970. //cleanup
  42971. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  42972. break;
  42973. }
  42974. };
  42975. this._collisionsCallbackArray = [];
  42976. this._init = false;
  42977. this._runningUpdated = 0;
  42978. this._runningCollisionTask = false;
  42979. this._addUpdateMeshesList = {};
  42980. this._addUpdateGeometriesList = {};
  42981. this._toRemoveGeometryArray = [];
  42982. this._toRemoveMeshesArray = [];
  42983. }
  42984. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  42985. if (!this._init)
  42986. return;
  42987. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  42988. return;
  42989. position.divideToRef(collider.radius, this._scaledPosition);
  42990. displacement.divideToRef(collider.radius, this._scaledVelocity);
  42991. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  42992. var payload = {
  42993. collider: {
  42994. position: this._scaledPosition.asArray(),
  42995. velocity: this._scaledVelocity.asArray(),
  42996. radius: collider.radius.asArray()
  42997. },
  42998. collisionId: collisionIndex,
  42999. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  43000. maximumRetry: maximumRetry
  43001. };
  43002. var message = {
  43003. payload: payload,
  43004. taskType: WorkerTaskType.COLLIDE
  43005. };
  43006. this._worker.postMessage(message);
  43007. };
  43008. CollisionCoordinatorWorker.prototype.init = function (scene) {
  43009. this._scene = scene;
  43010. this._scene.registerAfterRender(this._afterRender);
  43011. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  43012. this._worker = new Worker(workerUrl);
  43013. this._worker.onmessage = this._onMessageFromWorker;
  43014. var message = {
  43015. payload: {},
  43016. taskType: WorkerTaskType.INIT
  43017. };
  43018. this._worker.postMessage(message);
  43019. };
  43020. CollisionCoordinatorWorker.prototype.destroy = function () {
  43021. this._scene.unregisterAfterRender(this._afterRender);
  43022. this._worker.terminate();
  43023. };
  43024. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  43025. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  43026. this.onMeshUpdated(mesh);
  43027. };
  43028. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  43029. this._toRemoveMeshesArray.push(mesh.uniqueId);
  43030. };
  43031. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  43032. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  43033. geometry.onGeometryUpdated = this.onGeometryUpdated;
  43034. this.onGeometryUpdated(geometry);
  43035. };
  43036. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  43037. this._toRemoveGeometryArray.push(geometry.id);
  43038. };
  43039. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  43040. var submeshes = [];
  43041. if (mesh.subMeshes) {
  43042. submeshes = mesh.subMeshes.map(function (sm, idx) {
  43043. return {
  43044. position: idx,
  43045. verticesStart: sm.verticesStart,
  43046. verticesCount: sm.verticesCount,
  43047. indexStart: sm.indexStart,
  43048. indexCount: sm.indexCount,
  43049. hasMaterial: !!sm.getMaterial(),
  43050. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  43051. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  43052. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  43053. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  43054. };
  43055. });
  43056. }
  43057. var geometryId = null;
  43058. if (mesh instanceof BABYLON.Mesh) {
  43059. geometryId = mesh.geometry ? mesh.geometry.id : null;
  43060. }
  43061. else if (mesh instanceof BABYLON.InstancedMesh) {
  43062. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  43063. }
  43064. return {
  43065. uniqueId: mesh.uniqueId,
  43066. id: mesh.id,
  43067. name: mesh.name,
  43068. geometryId: geometryId,
  43069. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  43070. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  43071. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  43072. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  43073. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  43074. subMeshes: submeshes,
  43075. checkCollisions: mesh.checkCollisions
  43076. };
  43077. };
  43078. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  43079. return {
  43080. id: geometry.id,
  43081. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  43082. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  43083. indices: new Uint32Array(geometry.getIndices() || []),
  43084. };
  43085. };
  43086. return CollisionCoordinatorWorker;
  43087. }());
  43088. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  43089. var CollisionCoordinatorLegacy = /** @class */ (function () {
  43090. function CollisionCoordinatorLegacy() {
  43091. this._scaledPosition = BABYLON.Vector3.Zero();
  43092. this._scaledVelocity = BABYLON.Vector3.Zero();
  43093. this._finalPosition = BABYLON.Vector3.Zero();
  43094. }
  43095. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  43096. position.divideToRef(collider.radius, this._scaledPosition);
  43097. displacement.divideToRef(collider.radius, this._scaledVelocity);
  43098. collider.collidedMesh = null;
  43099. collider.retry = 0;
  43100. collider.initialVelocity = this._scaledVelocity;
  43101. collider.initialPosition = this._scaledPosition;
  43102. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  43103. this._finalPosition.multiplyInPlace(collider.radius);
  43104. //run the callback
  43105. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  43106. };
  43107. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  43108. this._scene = scene;
  43109. };
  43110. CollisionCoordinatorLegacy.prototype.destroy = function () {
  43111. //Legacy need no destruction method.
  43112. };
  43113. //No update in legacy mode
  43114. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  43115. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  43116. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  43117. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  43118. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  43119. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  43120. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  43121. if (excludedMesh === void 0) { excludedMesh = null; }
  43122. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  43123. if (collider.retry >= maximumRetry) {
  43124. finalPosition.copyFrom(position);
  43125. return;
  43126. }
  43127. // Check if this is a mesh else camera or -1
  43128. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  43129. collider._initialize(position, velocity, closeDistance);
  43130. // Check all meshes
  43131. for (var index = 0; index < this._scene.meshes.length; index++) {
  43132. var mesh = this._scene.meshes[index];
  43133. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  43134. mesh._checkCollision(collider);
  43135. }
  43136. }
  43137. if (!collider.collisionFound) {
  43138. position.addToRef(velocity, finalPosition);
  43139. return;
  43140. }
  43141. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  43142. collider._getResponse(position, velocity);
  43143. }
  43144. if (velocity.length() <= closeDistance) {
  43145. finalPosition.copyFrom(position);
  43146. return;
  43147. }
  43148. collider.retry++;
  43149. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  43150. };
  43151. return CollisionCoordinatorLegacy;
  43152. }());
  43153. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  43154. })(BABYLON || (BABYLON = {}));
  43155. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  43156. var BABYLON;
  43157. (function (BABYLON) {
  43158. var Particle = /** @class */ (function () {
  43159. function Particle(particleSystem) {
  43160. this.particleSystem = particleSystem;
  43161. this.position = BABYLON.Vector3.Zero();
  43162. this.direction = BABYLON.Vector3.Zero();
  43163. this.color = new BABYLON.Color4(0, 0, 0, 0);
  43164. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  43165. this.lifeTime = 1.0;
  43166. this.age = 0;
  43167. this.size = 0;
  43168. this.angle = 0;
  43169. this.angularSpeed = 0;
  43170. this._currentFrameCounter = 0;
  43171. this.cellIndex = 0;
  43172. if (!this.particleSystem.isAnimationSheetEnabled) {
  43173. return;
  43174. }
  43175. this.cellIndex = this.particleSystem.startSpriteCellID;
  43176. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  43177. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  43178. }
  43179. else {
  43180. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  43181. }
  43182. }
  43183. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  43184. // (ageOffset / scaledUpdateSpeed) / available cells
  43185. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  43186. this._currentFrameCounter += scaledUpdateSpeed;
  43187. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  43188. this._currentFrameCounter = 0;
  43189. this.cellIndex++;
  43190. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  43191. this.cellIndex = this.particleSystem.endSpriteCellID;
  43192. }
  43193. }
  43194. };
  43195. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  43196. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  43197. this.cellIndex++;
  43198. this._currentFrameCounter = 0;
  43199. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  43200. if (this.particleSystem.spriteCellLoop) {
  43201. this.cellIndex = this.particleSystem.startSpriteCellID;
  43202. }
  43203. else {
  43204. this.cellIndex = this.particleSystem.endSpriteCellID;
  43205. }
  43206. }
  43207. }
  43208. else {
  43209. this._currentFrameCounter++;
  43210. }
  43211. };
  43212. Particle.prototype.copyTo = function (other) {
  43213. other.position.copyFrom(this.position);
  43214. other.direction.copyFrom(this.direction);
  43215. other.color.copyFrom(this.color);
  43216. other.colorStep.copyFrom(this.colorStep);
  43217. other.lifeTime = this.lifeTime;
  43218. other.age = this.age;
  43219. other.size = this.size;
  43220. other.angle = this.angle;
  43221. other.angularSpeed = this.angularSpeed;
  43222. other.particleSystem = this.particleSystem;
  43223. other.cellIndex = this.cellIndex;
  43224. };
  43225. return Particle;
  43226. }());
  43227. BABYLON.Particle = Particle;
  43228. })(BABYLON || (BABYLON = {}));
  43229. //# sourceMappingURL=babylon.particle.js.map
  43230. var BABYLON;
  43231. (function (BABYLON) {
  43232. var randomNumber = function (min, max) {
  43233. if (min === max) {
  43234. return (min);
  43235. }
  43236. var random = Math.random();
  43237. return ((random * (max - min)) + min);
  43238. };
  43239. var ParticleSystem = /** @class */ (function () {
  43240. // end of sheet animation
  43241. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  43242. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  43243. if (epsilon === void 0) { epsilon = 0.01; }
  43244. var _this = this;
  43245. this.name = name;
  43246. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  43247. // Members
  43248. this.animations = [];
  43249. this.renderingGroupId = 0;
  43250. this.emitter = null;
  43251. this.emitRate = 10;
  43252. this.manualEmitCount = -1;
  43253. this.updateSpeed = 0.01;
  43254. this.targetStopDuration = 0;
  43255. this.disposeOnStop = false;
  43256. this.minEmitPower = 1;
  43257. this.maxEmitPower = 1;
  43258. this.minLifeTime = 1;
  43259. this.maxLifeTime = 1;
  43260. this.minSize = 1;
  43261. this.maxSize = 1;
  43262. this.minAngularSpeed = 0;
  43263. this.maxAngularSpeed = 0;
  43264. this.layerMask = 0x0FFFFFFF;
  43265. this.customShader = null;
  43266. this.preventAutoStart = false;
  43267. /**
  43268. * An event triggered when the system is disposed.
  43269. * @type {BABYLON.Observable}
  43270. */
  43271. this.onDisposeObservable = new BABYLON.Observable();
  43272. this.onAnimationEnd = null;
  43273. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  43274. this.forceDepthWrite = false;
  43275. this.gravity = BABYLON.Vector3.Zero();
  43276. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  43277. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  43278. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  43279. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  43280. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  43281. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  43282. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  43283. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  43284. this.particles = new Array();
  43285. this._stockParticles = new Array();
  43286. this._newPartsExcess = 0;
  43287. this._vertexBuffers = {};
  43288. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  43289. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  43290. this._scaledDirection = BABYLON.Vector3.Zero();
  43291. this._scaledGravity = BABYLON.Vector3.Zero();
  43292. this._currentRenderId = -1;
  43293. this._started = false;
  43294. this._stopped = false;
  43295. this._actualFrame = 0;
  43296. // sheet animation
  43297. this.startSpriteCellID = 0;
  43298. this.endSpriteCellID = 0;
  43299. this.spriteCellLoop = true;
  43300. this.spriteCellChangeSpeed = 0;
  43301. this.spriteCellWidth = 0;
  43302. this.spriteCellHeight = 0;
  43303. this._vertexBufferSize = 11;
  43304. this.appendParticleVertexes = null;
  43305. this.id = name;
  43306. this._capacity = capacity;
  43307. this._epsilon = epsilon;
  43308. if (_isAnimationSheetEnabled) {
  43309. this._vertexBufferSize = 12;
  43310. }
  43311. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  43312. this._customEffect = customEffect;
  43313. scene.particleSystems.push(this);
  43314. this._createIndexBuffer();
  43315. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  43316. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  43317. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  43318. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  43319. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  43320. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  43321. if (this._isAnimationSheetEnabled) {
  43322. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  43323. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  43324. }
  43325. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  43326. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  43327. this._vertexBuffers["options"] = options;
  43328. // Default behaviors
  43329. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  43330. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  43331. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  43332. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  43333. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  43334. };
  43335. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  43336. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  43337. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  43338. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  43339. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  43340. };
  43341. this.updateFunction = function (particles) {
  43342. for (var index = 0; index < particles.length; index++) {
  43343. var particle = particles[index];
  43344. particle.age += _this._scaledUpdateSpeed;
  43345. if (particle.age >= particle.lifeTime) {
  43346. _this.recycleParticle(particle);
  43347. index--;
  43348. continue;
  43349. }
  43350. else {
  43351. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  43352. particle.color.addInPlace(_this._scaledColorStep);
  43353. if (particle.color.a < 0)
  43354. particle.color.a = 0;
  43355. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  43356. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  43357. particle.position.addInPlace(_this._scaledDirection);
  43358. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  43359. particle.direction.addInPlace(_this._scaledGravity);
  43360. if (_this._isAnimationSheetEnabled) {
  43361. particle.updateCellIndex(_this._scaledUpdateSpeed);
  43362. }
  43363. }
  43364. }
  43365. };
  43366. }
  43367. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  43368. set: function (callback) {
  43369. if (this._onDisposeObserver) {
  43370. this.onDisposeObservable.remove(this._onDisposeObserver);
  43371. }
  43372. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  43373. },
  43374. enumerable: true,
  43375. configurable: true
  43376. });
  43377. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  43378. get: function () {
  43379. return this._isAnimationSheetEnabled;
  43380. },
  43381. enumerable: true,
  43382. configurable: true
  43383. });
  43384. ParticleSystem.prototype._createIndexBuffer = function () {
  43385. var indices = [];
  43386. var index = 0;
  43387. for (var count = 0; count < this._capacity; count++) {
  43388. indices.push(index);
  43389. indices.push(index + 1);
  43390. indices.push(index + 2);
  43391. indices.push(index);
  43392. indices.push(index + 2);
  43393. indices.push(index + 3);
  43394. index += 4;
  43395. }
  43396. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  43397. };
  43398. ParticleSystem.prototype.recycleParticle = function (particle) {
  43399. var lastParticle = this.particles.pop();
  43400. if (lastParticle !== particle) {
  43401. lastParticle.copyTo(particle);
  43402. this._stockParticles.push(lastParticle);
  43403. }
  43404. };
  43405. ParticleSystem.prototype.getCapacity = function () {
  43406. return this._capacity;
  43407. };
  43408. ParticleSystem.prototype.isAlive = function () {
  43409. return this._alive;
  43410. };
  43411. ParticleSystem.prototype.isStarted = function () {
  43412. return this._started;
  43413. };
  43414. ParticleSystem.prototype.start = function () {
  43415. this._started = true;
  43416. this._stopped = false;
  43417. this._actualFrame = 0;
  43418. };
  43419. ParticleSystem.prototype.stop = function () {
  43420. this._stopped = true;
  43421. };
  43422. // animation sheet
  43423. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  43424. var offset = index * this._vertexBufferSize;
  43425. this._vertexData[offset] = particle.position.x;
  43426. this._vertexData[offset + 1] = particle.position.y;
  43427. this._vertexData[offset + 2] = particle.position.z;
  43428. this._vertexData[offset + 3] = particle.color.r;
  43429. this._vertexData[offset + 4] = particle.color.g;
  43430. this._vertexData[offset + 5] = particle.color.b;
  43431. this._vertexData[offset + 6] = particle.color.a;
  43432. this._vertexData[offset + 7] = particle.angle;
  43433. this._vertexData[offset + 8] = particle.size;
  43434. this._vertexData[offset + 9] = offsetX;
  43435. this._vertexData[offset + 10] = offsetY;
  43436. };
  43437. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  43438. if (offsetX === 0)
  43439. offsetX = this._epsilon;
  43440. else if (offsetX === 1)
  43441. offsetX = 1 - this._epsilon;
  43442. if (offsetY === 0)
  43443. offsetY = this._epsilon;
  43444. else if (offsetY === 1)
  43445. offsetY = 1 - this._epsilon;
  43446. var offset = index * this._vertexBufferSize;
  43447. this._vertexData[offset] = particle.position.x;
  43448. this._vertexData[offset + 1] = particle.position.y;
  43449. this._vertexData[offset + 2] = particle.position.z;
  43450. this._vertexData[offset + 3] = particle.color.r;
  43451. this._vertexData[offset + 4] = particle.color.g;
  43452. this._vertexData[offset + 5] = particle.color.b;
  43453. this._vertexData[offset + 6] = particle.color.a;
  43454. this._vertexData[offset + 7] = particle.angle;
  43455. this._vertexData[offset + 8] = particle.size;
  43456. this._vertexData[offset + 9] = offsetX;
  43457. this._vertexData[offset + 10] = offsetY;
  43458. this._vertexData[offset + 11] = particle.cellIndex;
  43459. };
  43460. ParticleSystem.prototype._update = function (newParticles) {
  43461. // Update current
  43462. this._alive = this.particles.length > 0;
  43463. this.updateFunction(this.particles);
  43464. // Add new ones
  43465. var worldMatrix;
  43466. if (this.emitter.position) {
  43467. var emitterMesh = this.emitter;
  43468. worldMatrix = emitterMesh.getWorldMatrix();
  43469. }
  43470. else {
  43471. var emitterPosition = this.emitter;
  43472. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  43473. }
  43474. var particle;
  43475. for (var index = 0; index < newParticles; index++) {
  43476. if (this.particles.length === this._capacity) {
  43477. break;
  43478. }
  43479. if (this._stockParticles.length !== 0) {
  43480. particle = this._stockParticles.pop();
  43481. particle.age = 0;
  43482. particle.cellIndex = this.startSpriteCellID;
  43483. }
  43484. else {
  43485. particle = new BABYLON.Particle(this);
  43486. }
  43487. this.particles.push(particle);
  43488. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  43489. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  43490. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  43491. particle.size = randomNumber(this.minSize, this.maxSize);
  43492. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  43493. this.startPositionFunction(worldMatrix, particle.position, particle);
  43494. var step = randomNumber(0, 1.0);
  43495. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  43496. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  43497. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  43498. }
  43499. };
  43500. ParticleSystem.prototype._getEffect = function () {
  43501. if (this._customEffect) {
  43502. return this._customEffect;
  43503. }
  43504. ;
  43505. var defines = [];
  43506. if (this._scene.clipPlane) {
  43507. defines.push("#define CLIPPLANE");
  43508. }
  43509. if (this._isAnimationSheetEnabled) {
  43510. defines.push("#define ANIMATESHEET");
  43511. }
  43512. // Effect
  43513. var join = defines.join("\n");
  43514. if (this._cachedDefines !== join) {
  43515. this._cachedDefines = join;
  43516. var attributesNamesOrOptions;
  43517. var effectCreationOption;
  43518. if (this._isAnimationSheetEnabled) {
  43519. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  43520. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  43521. }
  43522. else {
  43523. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  43524. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  43525. }
  43526. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  43527. }
  43528. return this._effect;
  43529. };
  43530. ParticleSystem.prototype.animate = function () {
  43531. if (!this._started)
  43532. return;
  43533. var effect = this._getEffect();
  43534. // Check
  43535. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  43536. return;
  43537. if (this._currentRenderId === this._scene.getRenderId()) {
  43538. return;
  43539. }
  43540. this._currentRenderId = this._scene.getRenderId();
  43541. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  43542. // determine the number of particles we need to create
  43543. var newParticles;
  43544. if (this.manualEmitCount > -1) {
  43545. newParticles = this.manualEmitCount;
  43546. this._newPartsExcess = 0;
  43547. this.manualEmitCount = 0;
  43548. }
  43549. else {
  43550. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  43551. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  43552. }
  43553. if (this._newPartsExcess > 1.0) {
  43554. newParticles += this._newPartsExcess >> 0;
  43555. this._newPartsExcess -= this._newPartsExcess >> 0;
  43556. }
  43557. this._alive = false;
  43558. if (!this._stopped) {
  43559. this._actualFrame += this._scaledUpdateSpeed;
  43560. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  43561. this.stop();
  43562. }
  43563. else {
  43564. newParticles = 0;
  43565. }
  43566. this._update(newParticles);
  43567. // Stopped?
  43568. if (this._stopped) {
  43569. if (!this._alive) {
  43570. this._started = false;
  43571. if (this.onAnimationEnd) {
  43572. this.onAnimationEnd();
  43573. }
  43574. if (this.disposeOnStop) {
  43575. this._scene._toBeDisposed.push(this);
  43576. }
  43577. }
  43578. }
  43579. // Animation sheet
  43580. if (this._isAnimationSheetEnabled) {
  43581. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  43582. }
  43583. else {
  43584. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  43585. }
  43586. // Update VBO
  43587. var offset = 0;
  43588. for (var index = 0; index < this.particles.length; index++) {
  43589. var particle = this.particles[index];
  43590. this.appendParticleVertexes(offset, particle);
  43591. offset += 4;
  43592. }
  43593. this._vertexBuffer.update(this._vertexData);
  43594. };
  43595. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  43596. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  43597. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  43598. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  43599. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  43600. };
  43601. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  43602. this._appendParticleVertex(offset++, particle, 0, 0);
  43603. this._appendParticleVertex(offset++, particle, 1, 0);
  43604. this._appendParticleVertex(offset++, particle, 1, 1);
  43605. this._appendParticleVertex(offset++, particle, 0, 1);
  43606. };
  43607. ParticleSystem.prototype.rebuild = function () {
  43608. this._createIndexBuffer();
  43609. this._vertexBuffer._rebuild();
  43610. };
  43611. ParticleSystem.prototype.render = function () {
  43612. var effect = this._getEffect();
  43613. // Check
  43614. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  43615. return 0;
  43616. var engine = this._scene.getEngine();
  43617. // Render
  43618. engine.enableEffect(effect);
  43619. engine.setState(false);
  43620. var viewMatrix = this._scene.getViewMatrix();
  43621. effect.setTexture("diffuseSampler", this.particleTexture);
  43622. effect.setMatrix("view", viewMatrix);
  43623. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  43624. if (this._isAnimationSheetEnabled) {
  43625. var baseSize = this.particleTexture.getBaseSize();
  43626. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  43627. }
  43628. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  43629. if (this._scene.clipPlane) {
  43630. var clipPlane = this._scene.clipPlane;
  43631. var invView = viewMatrix.clone();
  43632. invView.invert();
  43633. effect.setMatrix("invView", invView);
  43634. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43635. }
  43636. // VBOs
  43637. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  43638. // Draw order
  43639. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  43640. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  43641. }
  43642. else {
  43643. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  43644. }
  43645. if (this.forceDepthWrite) {
  43646. engine.setDepthWrite(true);
  43647. }
  43648. engine.draw(true, 0, this.particles.length * 6);
  43649. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  43650. return this.particles.length;
  43651. };
  43652. ParticleSystem.prototype.dispose = function () {
  43653. if (this._vertexBuffer) {
  43654. this._vertexBuffer.dispose();
  43655. this._vertexBuffer = null;
  43656. }
  43657. if (this._indexBuffer) {
  43658. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  43659. this._indexBuffer = null;
  43660. }
  43661. if (this.particleTexture) {
  43662. this.particleTexture.dispose();
  43663. this.particleTexture = null;
  43664. }
  43665. // Remove from scene
  43666. var index = this._scene.particleSystems.indexOf(this);
  43667. if (index > -1) {
  43668. this._scene.particleSystems.splice(index, 1);
  43669. }
  43670. // Callback
  43671. this.onDisposeObservable.notifyObservers(this);
  43672. this.onDisposeObservable.clear();
  43673. };
  43674. // Clone
  43675. ParticleSystem.prototype.clone = function (name, newEmitter) {
  43676. var custom = null;
  43677. var program = null;
  43678. if (this.customShader != null) {
  43679. program = this.customShader;
  43680. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  43681. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  43682. }
  43683. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  43684. result.customShader = program;
  43685. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  43686. if (newEmitter === undefined) {
  43687. newEmitter = this.emitter;
  43688. }
  43689. result.emitter = newEmitter;
  43690. if (this.particleTexture) {
  43691. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  43692. }
  43693. if (!this.preventAutoStart) {
  43694. result.start();
  43695. }
  43696. return result;
  43697. };
  43698. ParticleSystem.prototype.serialize = function () {
  43699. var serializationObject = {};
  43700. serializationObject.name = this.name;
  43701. serializationObject.id = this.id;
  43702. // Emitter
  43703. if (this.emitter.position) {
  43704. var emitterMesh = this.emitter;
  43705. serializationObject.emitterId = emitterMesh.id;
  43706. }
  43707. else {
  43708. var emitterPosition = this.emitter;
  43709. serializationObject.emitter = emitterPosition.asArray();
  43710. }
  43711. serializationObject.capacity = this.getCapacity();
  43712. if (this.particleTexture) {
  43713. serializationObject.textureName = this.particleTexture.name;
  43714. }
  43715. // Animations
  43716. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  43717. // Particle system
  43718. serializationObject.minAngularSpeed = this.minAngularSpeed;
  43719. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  43720. serializationObject.minSize = this.minSize;
  43721. serializationObject.maxSize = this.maxSize;
  43722. serializationObject.minEmitPower = this.minEmitPower;
  43723. serializationObject.maxEmitPower = this.maxEmitPower;
  43724. serializationObject.minLifeTime = this.minLifeTime;
  43725. serializationObject.maxLifeTime = this.maxLifeTime;
  43726. serializationObject.emitRate = this.emitRate;
  43727. serializationObject.minEmitBox = this.minEmitBox.asArray();
  43728. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  43729. serializationObject.gravity = this.gravity.asArray();
  43730. serializationObject.direction1 = this.direction1.asArray();
  43731. serializationObject.direction2 = this.direction2.asArray();
  43732. serializationObject.color1 = this.color1.asArray();
  43733. serializationObject.color2 = this.color2.asArray();
  43734. serializationObject.colorDead = this.colorDead.asArray();
  43735. serializationObject.updateSpeed = this.updateSpeed;
  43736. serializationObject.targetStopDuration = this.targetStopDuration;
  43737. serializationObject.textureMask = this.textureMask.asArray();
  43738. serializationObject.blendMode = this.blendMode;
  43739. serializationObject.customShader = this.customShader;
  43740. serializationObject.preventAutoStart = this.preventAutoStart;
  43741. return serializationObject;
  43742. };
  43743. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  43744. var name = parsedParticleSystem.name;
  43745. var custom = null;
  43746. var program = null;
  43747. if (parsedParticleSystem.customShader) {
  43748. program = parsedParticleSystem.customShader;
  43749. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  43750. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  43751. }
  43752. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  43753. particleSystem.customShader = program;
  43754. if (parsedParticleSystem.id) {
  43755. particleSystem.id = parsedParticleSystem.id;
  43756. }
  43757. // Auto start
  43758. if (parsedParticleSystem.preventAutoStart) {
  43759. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  43760. }
  43761. // Texture
  43762. if (parsedParticleSystem.textureName) {
  43763. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  43764. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  43765. }
  43766. // Emitter
  43767. if (parsedParticleSystem.emitterId) {
  43768. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  43769. }
  43770. else {
  43771. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  43772. }
  43773. // Animations
  43774. if (parsedParticleSystem.animations) {
  43775. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  43776. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  43777. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  43778. }
  43779. }
  43780. if (parsedParticleSystem.autoAnimate) {
  43781. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  43782. }
  43783. // Particle system
  43784. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  43785. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  43786. particleSystem.minSize = parsedParticleSystem.minSize;
  43787. particleSystem.maxSize = parsedParticleSystem.maxSize;
  43788. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  43789. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  43790. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  43791. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  43792. particleSystem.emitRate = parsedParticleSystem.emitRate;
  43793. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  43794. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  43795. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  43796. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  43797. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  43798. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  43799. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  43800. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  43801. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  43802. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  43803. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  43804. particleSystem.blendMode = parsedParticleSystem.blendMode;
  43805. if (!particleSystem.preventAutoStart) {
  43806. particleSystem.start();
  43807. }
  43808. return particleSystem;
  43809. };
  43810. // Statics
  43811. ParticleSystem.BLENDMODE_ONEONE = 0;
  43812. ParticleSystem.BLENDMODE_STANDARD = 1;
  43813. return ParticleSystem;
  43814. }());
  43815. BABYLON.ParticleSystem = ParticleSystem;
  43816. })(BABYLON || (BABYLON = {}));
  43817. //# sourceMappingURL=babylon.particleSystem.js.map
  43818. var BABYLON;
  43819. (function (BABYLON) {
  43820. var SolidParticle = /** @class */ (function () {
  43821. /**
  43822. * Creates a Solid Particle object.
  43823. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  43824. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  43825. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  43826. * `indiceIndex` (integer) is the starting index of the particle indices in the SPS "indices" array.
  43827. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  43828. * `shapeId` (integer) is the model shape identifier in the SPS.
  43829. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  43830. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  43831. */
  43832. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  43833. this.idx = 0; // particle global index
  43834. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  43835. this.position = BABYLON.Vector3.Zero(); // position
  43836. this.rotation = BABYLON.Vector3.Zero(); // rotation
  43837. this.scaling = BABYLON.Vector3.One(); // scaling
  43838. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  43839. this.velocity = BABYLON.Vector3.Zero(); // velocity
  43840. this.alive = true; // alive
  43841. this.isVisible = true; // visibility
  43842. this._pos = 0; // index of this particle in the global "positions" array
  43843. this._ind = 0; // index of this particle in the global "indices" array
  43844. this.shapeId = 0; // model shape id
  43845. this.idxInShape = 0; // index of the particle in its shape id
  43846. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  43847. this.idx = particleIndex;
  43848. this._pos = positionIndex;
  43849. this._ind = indiceIndex;
  43850. this._model = model;
  43851. this.shapeId = shapeId;
  43852. this.idxInShape = idxInShape;
  43853. this._sps = sps;
  43854. if (modelBoundingInfo) {
  43855. this._modelBoundingInfo = modelBoundingInfo;
  43856. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  43857. }
  43858. }
  43859. Object.defineProperty(SolidParticle.prototype, "scale", {
  43860. /**
  43861. * legacy support, changed scale to scaling
  43862. */
  43863. get: function () {
  43864. return this.scaling;
  43865. },
  43866. set: function (scale) {
  43867. this.scaling = scale;
  43868. },
  43869. enumerable: true,
  43870. configurable: true
  43871. });
  43872. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  43873. /**
  43874. * legacy support, changed quaternion to rotationQuaternion
  43875. */
  43876. get: function () {
  43877. return this.rotationQuaternion;
  43878. },
  43879. set: function (q) {
  43880. this.rotationQuaternion = q;
  43881. },
  43882. enumerable: true,
  43883. configurable: true
  43884. });
  43885. /**
  43886. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  43887. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  43888. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  43889. */
  43890. SolidParticle.prototype.intersectsMesh = function (target) {
  43891. if (!this._boundingInfo || !target._boundingInfo) {
  43892. return false;
  43893. }
  43894. if (this._sps._bSphereOnly) {
  43895. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  43896. }
  43897. return this._boundingInfo.intersects(target._boundingInfo, false);
  43898. };
  43899. return SolidParticle;
  43900. }());
  43901. BABYLON.SolidParticle = SolidParticle;
  43902. var ModelShape = /** @class */ (function () {
  43903. /**
  43904. * 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.
  43905. * SPS internal tool, don't use it manually.
  43906. */
  43907. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  43908. this._indicesLength = 0; // length of the shape in the model indices array
  43909. this.shapeID = id;
  43910. this._shape = shape;
  43911. this._indicesLength = indicesLength;
  43912. this._shapeUV = shapeUV;
  43913. this._positionFunction = posFunction;
  43914. this._vertexFunction = vtxFunction;
  43915. }
  43916. return ModelShape;
  43917. }());
  43918. BABYLON.ModelShape = ModelShape;
  43919. var DepthSortedParticle = /** @class */ (function () {
  43920. function DepthSortedParticle() {
  43921. this.ind = 0; // index of the particle in the "indices" array
  43922. this.indicesLength = 0; // length of the particle shape in the "indices" array
  43923. this.sqDistance = 0.0; // squared distance from the particle to the camera
  43924. }
  43925. return DepthSortedParticle;
  43926. }());
  43927. BABYLON.DepthSortedParticle = DepthSortedParticle;
  43928. })(BABYLON || (BABYLON = {}));
  43929. //# sourceMappingURL=babylon.solidParticle.js.map
  43930. var BABYLON;
  43931. (function (BABYLON) {
  43932. /**
  43933. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  43934. */
  43935. var SolidParticleSystem = /** @class */ (function () {
  43936. /**
  43937. * Creates a SPS (Solid Particle System) object.
  43938. * `name` (String) is the SPS name, this will be the underlying mesh name.
  43939. * `scene` (Scene) is the scene in which the SPS is added.
  43940. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  43941. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  43942. * `enableDepthSort` (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  43943. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  43944. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  43945. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  43946. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  43947. */
  43948. function SolidParticleSystem(name, scene, options) {
  43949. // public members
  43950. /**
  43951. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  43952. * Example : var p = SPS.particles[i];
  43953. */
  43954. this.particles = new Array();
  43955. /**
  43956. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  43957. */
  43958. this.nbParticles = 0;
  43959. /**
  43960. * If the particles must ever face the camera (default false). Useful for planar particles.
  43961. */
  43962. this.billboard = false;
  43963. /**
  43964. * Recompute normals when adding a shape
  43965. */
  43966. this.recomputeNormals = true;
  43967. /**
  43968. * This a counter ofr your own usage. It's not set by any SPS functions.
  43969. */
  43970. this.counter = 0;
  43971. /**
  43972. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  43973. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  43974. */
  43975. this.vars = {};
  43976. this._positions = new Array();
  43977. this._indices = new Array();
  43978. this._normals = new Array();
  43979. this._colors = new Array();
  43980. this._uvs = new Array();
  43981. this._index = 0; // indices index
  43982. this._updatable = true;
  43983. this._pickable = false;
  43984. this._isVisibilityBoxLocked = false;
  43985. this._alwaysVisible = false;
  43986. this._depthSort = false;
  43987. this._shapeCounter = 0;
  43988. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null, null);
  43989. this._color = new BABYLON.Color4(0, 0, 0, 0);
  43990. this._computeParticleColor = true;
  43991. this._computeParticleTexture = true;
  43992. this._computeParticleRotation = true;
  43993. this._computeParticleVertex = false;
  43994. this._computeBoundingBox = false;
  43995. this._depthSortParticles = true;
  43996. this._cam_axisZ = BABYLON.Vector3.Zero();
  43997. this._cam_axisY = BABYLON.Vector3.Zero();
  43998. this._cam_axisX = BABYLON.Vector3.Zero();
  43999. this._axisZ = BABYLON.Axis.Z;
  44000. this._camDir = BABYLON.Vector3.Zero();
  44001. this._camInvertedPosition = BABYLON.Vector3.Zero();
  44002. this._rotMatrix = new BABYLON.Matrix();
  44003. this._invertMatrix = new BABYLON.Matrix();
  44004. this._rotated = BABYLON.Vector3.Zero();
  44005. this._quaternion = new BABYLON.Quaternion();
  44006. this._vertex = BABYLON.Vector3.Zero();
  44007. this._normal = BABYLON.Vector3.Zero();
  44008. this._yaw = 0.0;
  44009. this._pitch = 0.0;
  44010. this._roll = 0.0;
  44011. this._halfroll = 0.0;
  44012. this._halfpitch = 0.0;
  44013. this._halfyaw = 0.0;
  44014. this._sinRoll = 0.0;
  44015. this._cosRoll = 0.0;
  44016. this._sinPitch = 0.0;
  44017. this._cosPitch = 0.0;
  44018. this._sinYaw = 0.0;
  44019. this._cosYaw = 0.0;
  44020. this._mustUnrotateFixedNormals = false;
  44021. this._minimum = BABYLON.Tmp.Vector3[0];
  44022. this._maximum = BABYLON.Tmp.Vector3[1];
  44023. this._minBbox = BABYLON.Tmp.Vector3[4];
  44024. this._maxBbox = BABYLON.Tmp.Vector3[5];
  44025. this._particlesIntersect = false;
  44026. this._depthSortFunction = function (p1, p2) {
  44027. return (p2.sqDistance - p1.sqDistance);
  44028. };
  44029. this._needs32Bits = false;
  44030. this._bSphereOnly = false;
  44031. this._bSphereRadiusFactor = 1.0;
  44032. this.name = name;
  44033. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44034. this._camera = scene.activeCamera;
  44035. this._pickable = options ? options.isPickable : false;
  44036. this._depthSort = options ? options.enableDepthSort : false;
  44037. this._particlesIntersect = options ? options.particleIntersection : false;
  44038. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  44039. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  44040. if (options && options.updatable) {
  44041. this._updatable = options.updatable;
  44042. }
  44043. else {
  44044. this._updatable = true;
  44045. }
  44046. if (this._pickable) {
  44047. this.pickedParticles = [];
  44048. }
  44049. if (this._depthSort) {
  44050. this.depthSortedParticles = [];
  44051. }
  44052. }
  44053. /**
  44054. * Builds the SPS underlying mesh. Returns a standard Mesh.
  44055. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  44056. */
  44057. SolidParticleSystem.prototype.buildMesh = function () {
  44058. if (this.nbParticles === 0) {
  44059. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  44060. this.addShape(triangle, 1);
  44061. triangle.dispose();
  44062. }
  44063. this._positions32 = new Float32Array(this._positions);
  44064. this._uvs32 = new Float32Array(this._uvs);
  44065. this._colors32 = new Float32Array(this._colors);
  44066. if (this.recomputeNormals) {
  44067. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  44068. }
  44069. this._normals32 = new Float32Array(this._normals);
  44070. this._fixedNormal32 = new Float32Array(this._normals);
  44071. if (this._mustUnrotateFixedNormals) {
  44072. this._unrotateFixedNormals();
  44073. }
  44074. var vertexData = new BABYLON.VertexData();
  44075. if (this._depthSort) {
  44076. this._depthSortedIndices = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  44077. vertexData.indices = this._depthSortedIndices;
  44078. }
  44079. else {
  44080. vertexData.indices = this._indices;
  44081. }
  44082. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  44083. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  44084. if (this._uvs32) {
  44085. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  44086. ;
  44087. }
  44088. if (this._colors32) {
  44089. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  44090. }
  44091. var mesh = new BABYLON.Mesh(this.name, this._scene);
  44092. vertexData.applyToMesh(mesh, this._updatable);
  44093. this.mesh = mesh;
  44094. this.mesh.isPickable = this._pickable;
  44095. // free memory
  44096. this._positions = null;
  44097. this._normals = null;
  44098. this._uvs = null;
  44099. this._colors = null;
  44100. if (!this._updatable) {
  44101. this.particles.length = 0;
  44102. }
  44103. return mesh;
  44104. };
  44105. /**
  44106. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  44107. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  44108. * Thus the particles generated from `digest()` have their property `position` set yet.
  44109. * `mesh` ( Mesh ) is the mesh to be digested
  44110. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  44111. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  44112. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  44113. */
  44114. SolidParticleSystem.prototype.digest = function (mesh, options) {
  44115. var size = (options && options.facetNb) || 1;
  44116. var number = (options && options.number);
  44117. var delta = (options && options.delta) || 0;
  44118. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44119. var meshInd = mesh.getIndices();
  44120. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  44121. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  44122. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  44123. var f = 0; // facet counter
  44124. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  44125. // compute size from number
  44126. if (number) {
  44127. number = (number > totalFacets) ? totalFacets : number;
  44128. size = Math.round(totalFacets / number);
  44129. delta = 0;
  44130. }
  44131. else {
  44132. size = (size > totalFacets) ? totalFacets : size;
  44133. }
  44134. var facetPos = []; // submesh positions
  44135. var facetInd = []; // submesh indices
  44136. var facetUV = []; // submesh UV
  44137. var facetCol = []; // submesh colors
  44138. var barycenter = BABYLON.Tmp.Vector3[0];
  44139. var sizeO = size;
  44140. while (f < totalFacets) {
  44141. size = sizeO + Math.floor((1 + delta) * Math.random());
  44142. if (f > totalFacets - size) {
  44143. size = totalFacets - f;
  44144. }
  44145. // reset temp arrays
  44146. facetPos.length = 0;
  44147. facetInd.length = 0;
  44148. facetUV.length = 0;
  44149. facetCol.length = 0;
  44150. // iterate over "size" facets
  44151. var fi = 0;
  44152. for (var j = f * 3; j < (f + size) * 3; j++) {
  44153. facetInd.push(fi);
  44154. var i = meshInd[j];
  44155. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  44156. if (meshUV) {
  44157. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  44158. }
  44159. if (meshCol) {
  44160. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  44161. }
  44162. fi++;
  44163. }
  44164. // create a model shape for each single particle
  44165. var idx = this.nbParticles;
  44166. var shape = this._posToShape(facetPos);
  44167. var shapeUV = this._uvsToShapeUV(facetUV);
  44168. // compute the barycenter of the shape
  44169. var v;
  44170. for (v = 0; v < shape.length; v++) {
  44171. barycenter.addInPlace(shape[v]);
  44172. }
  44173. barycenter.scaleInPlace(1 / shape.length);
  44174. // shift the shape from its barycenter to the origin
  44175. for (v = 0; v < shape.length; v++) {
  44176. shape[v].subtractInPlace(barycenter);
  44177. }
  44178. var bInfo;
  44179. if (this._particlesIntersect) {
  44180. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  44181. }
  44182. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  44183. // add the particle in the SPS
  44184. var currentPos = this._positions.length;
  44185. var currentInd = this._indices.length;
  44186. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  44187. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  44188. // initialize the particle position
  44189. this.particles[this.nbParticles].position.addInPlace(barycenter);
  44190. this._index += shape.length;
  44191. idx++;
  44192. this.nbParticles++;
  44193. this._shapeCounter++;
  44194. f += size;
  44195. }
  44196. return this;
  44197. };
  44198. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  44199. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  44200. var index = 0;
  44201. var idx = 0;
  44202. for (var p = 0; p < this.particles.length; p++) {
  44203. this._particle = this.particles[p];
  44204. this._shape = this._particle._model._shape;
  44205. if (this._particle.rotationQuaternion) {
  44206. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  44207. }
  44208. else {
  44209. this._yaw = this._particle.rotation.y;
  44210. this._pitch = this._particle.rotation.x;
  44211. this._roll = this._particle.rotation.z;
  44212. this._quaternionRotationYPR();
  44213. }
  44214. this._quaternionToRotationMatrix();
  44215. this._rotMatrix.invertToRef(this._invertMatrix);
  44216. for (var pt = 0; pt < this._shape.length; pt++) {
  44217. idx = index + pt * 3;
  44218. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  44219. this._fixedNormal32[idx] = this._normal.x;
  44220. this._fixedNormal32[idx + 1] = this._normal.y;
  44221. this._fixedNormal32[idx + 2] = this._normal.z;
  44222. }
  44223. index = idx + 3;
  44224. }
  44225. };
  44226. //reset copy
  44227. SolidParticleSystem.prototype._resetCopy = function () {
  44228. this._copy.position.x = 0;
  44229. this._copy.position.y = 0;
  44230. this._copy.position.z = 0;
  44231. this._copy.rotation.x = 0;
  44232. this._copy.rotation.y = 0;
  44233. this._copy.rotation.z = 0;
  44234. this._copy.rotationQuaternion = null;
  44235. this._copy.scaling.x = 1.0;
  44236. this._copy.scaling.y = 1.0;
  44237. this._copy.scaling.z = 1.0;
  44238. this._copy.uvs.x = 0;
  44239. this._copy.uvs.y = 0;
  44240. this._copy.uvs.z = 1.0;
  44241. this._copy.uvs.w = 1.0;
  44242. this._copy.color = null;
  44243. };
  44244. // _meshBuilder : inserts the shape model in the global SPS mesh
  44245. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  44246. var i;
  44247. var u = 0;
  44248. var c = 0;
  44249. var n = 0;
  44250. this._resetCopy();
  44251. if (options && options.positionFunction) {
  44252. options.positionFunction(this._copy, idx, idxInShape);
  44253. this._mustUnrotateFixedNormals = true;
  44254. }
  44255. if (this._copy.rotationQuaternion) {
  44256. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  44257. }
  44258. else {
  44259. this._yaw = this._copy.rotation.y;
  44260. this._pitch = this._copy.rotation.x;
  44261. this._roll = this._copy.rotation.z;
  44262. this._quaternionRotationYPR();
  44263. }
  44264. this._quaternionToRotationMatrix();
  44265. for (i = 0; i < shape.length; i++) {
  44266. this._vertex.x = shape[i].x;
  44267. this._vertex.y = shape[i].y;
  44268. this._vertex.z = shape[i].z;
  44269. if (options && options.vertexFunction) {
  44270. options.vertexFunction(this._copy, this._vertex, i);
  44271. }
  44272. this._vertex.x *= this._copy.scaling.x;
  44273. this._vertex.y *= this._copy.scaling.y;
  44274. this._vertex.z *= this._copy.scaling.z;
  44275. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  44276. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  44277. if (meshUV) {
  44278. 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);
  44279. u += 2;
  44280. }
  44281. if (this._copy.color) {
  44282. this._color = this._copy.color;
  44283. }
  44284. else if (meshCol && meshCol[c] !== undefined) {
  44285. this._color.r = meshCol[c];
  44286. this._color.g = meshCol[c + 1];
  44287. this._color.b = meshCol[c + 2];
  44288. this._color.a = meshCol[c + 3];
  44289. }
  44290. else {
  44291. this._color.r = 1.0;
  44292. this._color.g = 1.0;
  44293. this._color.b = 1.0;
  44294. this._color.a = 1.0;
  44295. }
  44296. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  44297. c += 4;
  44298. if (!this.recomputeNormals && meshNor) {
  44299. this._normal.x = meshNor[n];
  44300. this._normal.y = meshNor[n + 1];
  44301. this._normal.z = meshNor[n + 2];
  44302. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  44303. normals.push(this._normal.x, this._normal.y, this._normal.z);
  44304. n += 3;
  44305. }
  44306. }
  44307. for (i = 0; i < meshInd.length; i++) {
  44308. var current_ind = p + meshInd[i];
  44309. indices.push(current_ind);
  44310. if (current_ind > 65535) {
  44311. this._needs32Bits = true;
  44312. }
  44313. }
  44314. if (this._pickable) {
  44315. var nbfaces = meshInd.length / 3;
  44316. for (i = 0; i < nbfaces; i++) {
  44317. this.pickedParticles.push({ idx: idx, faceId: i });
  44318. }
  44319. }
  44320. if (this._depthSort) {
  44321. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  44322. }
  44323. return this._copy;
  44324. };
  44325. // returns a shape array from positions array
  44326. SolidParticleSystem.prototype._posToShape = function (positions) {
  44327. var shape = [];
  44328. for (var i = 0; i < positions.length; i += 3) {
  44329. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  44330. }
  44331. return shape;
  44332. };
  44333. // returns a shapeUV array from a Vector4 uvs
  44334. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  44335. var shapeUV = [];
  44336. if (uvs) {
  44337. for (var i = 0; i < uvs.length; i++)
  44338. shapeUV.push(uvs[i]);
  44339. }
  44340. return shapeUV;
  44341. };
  44342. // adds a new particle object in the particles array
  44343. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  44344. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  44345. this.particles.push(sp);
  44346. return sp;
  44347. };
  44348. /**
  44349. * Adds some particles to the SPS from the model shape. Returns the shape id.
  44350. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  44351. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  44352. * `nb` (positive integer) the number of particles to be created from this model
  44353. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  44354. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  44355. */
  44356. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  44357. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44358. var meshInd = mesh.getIndices();
  44359. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  44360. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  44361. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  44362. var bbInfo;
  44363. if (this._particlesIntersect) {
  44364. bbInfo = mesh.getBoundingInfo();
  44365. }
  44366. var shape = this._posToShape(meshPos);
  44367. var shapeUV = this._uvsToShapeUV(meshUV);
  44368. var posfunc = options ? options.positionFunction : null;
  44369. var vtxfunc = options ? options.vertexFunction : null;
  44370. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  44371. // particles
  44372. var sp;
  44373. var currentCopy;
  44374. var idx = this.nbParticles;
  44375. for (var i = 0; i < nb; i++) {
  44376. var currentPos = this._positions.length;
  44377. var currentInd = this._indices.length;
  44378. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  44379. if (this._updatable) {
  44380. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  44381. sp.position.copyFrom(currentCopy.position);
  44382. sp.rotation.copyFrom(currentCopy.rotation);
  44383. if (currentCopy.rotationQuaternion) {
  44384. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  44385. }
  44386. if (currentCopy.color) {
  44387. sp.color.copyFrom(currentCopy.color);
  44388. }
  44389. sp.scaling.copyFrom(currentCopy.scaling);
  44390. sp.uvs.copyFrom(currentCopy.uvs);
  44391. }
  44392. this._index += shape.length;
  44393. idx++;
  44394. }
  44395. this.nbParticles += nb;
  44396. this._shapeCounter++;
  44397. return this._shapeCounter - 1;
  44398. };
  44399. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  44400. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  44401. this._resetCopy();
  44402. if (particle._model._positionFunction) {
  44403. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  44404. }
  44405. if (this._copy.rotationQuaternion) {
  44406. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  44407. }
  44408. else {
  44409. this._yaw = this._copy.rotation.y;
  44410. this._pitch = this._copy.rotation.x;
  44411. this._roll = this._copy.rotation.z;
  44412. this._quaternionRotationYPR();
  44413. }
  44414. this._quaternionToRotationMatrix();
  44415. this._shape = particle._model._shape;
  44416. for (var pt = 0; pt < this._shape.length; pt++) {
  44417. this._vertex.x = this._shape[pt].x;
  44418. this._vertex.y = this._shape[pt].y;
  44419. this._vertex.z = this._shape[pt].z;
  44420. if (particle._model._vertexFunction) {
  44421. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  44422. }
  44423. this._vertex.x *= this._copy.scaling.x;
  44424. this._vertex.y *= this._copy.scaling.y;
  44425. this._vertex.z *= this._copy.scaling.z;
  44426. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  44427. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  44428. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  44429. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  44430. }
  44431. particle.position.x = 0.0;
  44432. particle.position.y = 0.0;
  44433. particle.position.z = 0.0;
  44434. particle.rotation.x = 0.0;
  44435. particle.rotation.y = 0.0;
  44436. particle.rotation.z = 0.0;
  44437. particle.rotationQuaternion = null;
  44438. particle.scaling.x = 1.0;
  44439. particle.scaling.y = 1.0;
  44440. particle.scaling.z = 1.0;
  44441. };
  44442. /**
  44443. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  44444. * Returns the SPS.
  44445. */
  44446. SolidParticleSystem.prototype.rebuildMesh = function () {
  44447. for (var p = 0; p < this.particles.length; p++) {
  44448. this._rebuildParticle(this.particles[p]);
  44449. }
  44450. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  44451. return this;
  44452. };
  44453. /**
  44454. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  44455. * This method calls `updateParticle()` for each particle of the SPS.
  44456. * For an animated SPS, it is usually called within the render loop.
  44457. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  44458. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  44459. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  44460. * Returns the SPS.
  44461. */
  44462. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  44463. if (start === void 0) { start = 0; }
  44464. if (end === void 0) { end = this.nbParticles - 1; }
  44465. if (update === void 0) { update = true; }
  44466. if (!this._updatable) {
  44467. return this;
  44468. }
  44469. // custom beforeUpdate
  44470. this.beforeUpdateParticles(start, end, update);
  44471. this._cam_axisX.x = 1.0;
  44472. this._cam_axisX.y = 0.0;
  44473. this._cam_axisX.z = 0.0;
  44474. this._cam_axisY.x = 0.0;
  44475. this._cam_axisY.y = 1.0;
  44476. this._cam_axisY.z = 0.0;
  44477. this._cam_axisZ.x = 0.0;
  44478. this._cam_axisZ.y = 0.0;
  44479. this._cam_axisZ.z = 1.0;
  44480. // cases when the World Matrix is to be computed first
  44481. if (this.billboard || this._depthSort) {
  44482. this.mesh.computeWorldMatrix(true);
  44483. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  44484. }
  44485. // if the particles will always face the camera
  44486. if (this.billboard) {
  44487. // compute the camera position and un-rotate it by the current mesh rotation
  44488. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  44489. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  44490. this._cam_axisZ.normalize();
  44491. // same for camera up vector extracted from the cam view matrix
  44492. var view = this._camera.getViewMatrix(true);
  44493. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  44494. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  44495. this._cam_axisY.normalize();
  44496. this._cam_axisX.normalize();
  44497. }
  44498. // if depthSort, compute the camera global position in the mesh local system
  44499. if (this._depthSort) {
  44500. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  44501. }
  44502. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  44503. var idx = 0; // current position index in the global array positions32
  44504. var index = 0; // position start index in the global array positions32 of the current particle
  44505. var colidx = 0; // current color index in the global array colors32
  44506. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  44507. var uvidx = 0; // current uv index in the global array uvs32
  44508. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  44509. var pt = 0; // current index in the particle model shape
  44510. if (this.mesh.isFacetDataEnabled) {
  44511. this._computeBoundingBox = true;
  44512. }
  44513. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  44514. if (this._computeBoundingBox) {
  44515. if (start == 0 && end == this.nbParticles - 1) {
  44516. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  44517. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  44518. }
  44519. else {
  44520. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  44521. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  44522. }
  44523. }
  44524. // particle loop
  44525. index = this.particles[start]._pos;
  44526. var vpos = (index / 3) | 0;
  44527. colorIndex = vpos * 4;
  44528. uvIndex = vpos * 2;
  44529. for (var p = start; p <= end; p++) {
  44530. this._particle = this.particles[p];
  44531. this._shape = this._particle._model._shape;
  44532. this._shapeUV = this._particle._model._shapeUV;
  44533. // call to custom user function to update the particle properties
  44534. this.updateParticle(this._particle);
  44535. // camera-particle distance for depth sorting
  44536. if (this._depthSort && this._depthSortParticles) {
  44537. var dsp = this.depthSortedParticles[p];
  44538. dsp.ind = this._particle._ind;
  44539. dsp.indicesLength = this._particle._model._indicesLength;
  44540. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  44541. }
  44542. // skip the computations for inactive or already invisible particles
  44543. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  44544. // increment indexes for the next particle
  44545. pt = this._shape.length;
  44546. index += pt * 3;
  44547. colorIndex += pt * 4;
  44548. uvIndex += pt * 2;
  44549. continue;
  44550. }
  44551. if (this._particle.isVisible) {
  44552. this._particle._stillInvisible = false; // un-mark permanent invisibility
  44553. // particle rotation matrix
  44554. if (this.billboard) {
  44555. this._particle.rotation.x = 0.0;
  44556. this._particle.rotation.y = 0.0;
  44557. }
  44558. if (this._computeParticleRotation || this.billboard) {
  44559. if (this._particle.rotationQuaternion) {
  44560. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  44561. }
  44562. else {
  44563. this._yaw = this._particle.rotation.y;
  44564. this._pitch = this._particle.rotation.x;
  44565. this._roll = this._particle.rotation.z;
  44566. this._quaternionRotationYPR();
  44567. }
  44568. this._quaternionToRotationMatrix();
  44569. }
  44570. // particle vertex loop
  44571. for (pt = 0; pt < this._shape.length; pt++) {
  44572. idx = index + pt * 3;
  44573. colidx = colorIndex + pt * 4;
  44574. uvidx = uvIndex + pt * 2;
  44575. this._vertex.x = this._shape[pt].x;
  44576. this._vertex.y = this._shape[pt].y;
  44577. this._vertex.z = this._shape[pt].z;
  44578. if (this._computeParticleVertex) {
  44579. this.updateParticleVertex(this._particle, this._vertex, pt);
  44580. }
  44581. // positions
  44582. this._vertex.x *= this._particle.scaling.x;
  44583. this._vertex.y *= this._particle.scaling.y;
  44584. this._vertex.z *= this._particle.scaling.z;
  44585. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  44586. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  44587. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  44588. 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;
  44589. 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;
  44590. 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;
  44591. if (this._computeBoundingBox) {
  44592. if (this._positions32[idx] < this._minimum.x) {
  44593. this._minimum.x = this._positions32[idx];
  44594. }
  44595. if (this._positions32[idx] > this._maximum.x) {
  44596. this._maximum.x = this._positions32[idx];
  44597. }
  44598. if (this._positions32[idx + 1] < this._minimum.y) {
  44599. this._minimum.y = this._positions32[idx + 1];
  44600. }
  44601. if (this._positions32[idx + 1] > this._maximum.y) {
  44602. this._maximum.y = this._positions32[idx + 1];
  44603. }
  44604. if (this._positions32[idx + 2] < this._minimum.z) {
  44605. this._minimum.z = this._positions32[idx + 2];
  44606. }
  44607. if (this._positions32[idx + 2] > this._maximum.z) {
  44608. this._maximum.z = this._positions32[idx + 2];
  44609. }
  44610. }
  44611. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  44612. if (!this._computeParticleVertex) {
  44613. this._normal.x = this._fixedNormal32[idx];
  44614. this._normal.y = this._fixedNormal32[idx + 1];
  44615. this._normal.z = this._fixedNormal32[idx + 2];
  44616. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  44617. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  44618. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  44619. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  44620. 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;
  44621. 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;
  44622. }
  44623. if (this._computeParticleColor) {
  44624. this._colors32[colidx] = this._particle.color.r;
  44625. this._colors32[colidx + 1] = this._particle.color.g;
  44626. this._colors32[colidx + 2] = this._particle.color.b;
  44627. this._colors32[colidx + 3] = this._particle.color.a;
  44628. }
  44629. if (this._computeParticleTexture) {
  44630. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  44631. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  44632. }
  44633. }
  44634. }
  44635. else {
  44636. this._particle._stillInvisible = true; // mark the particle as invisible
  44637. for (pt = 0; pt < this._shape.length; pt++) {
  44638. idx = index + pt * 3;
  44639. colidx = colorIndex + pt * 4;
  44640. uvidx = uvIndex + pt * 2;
  44641. this._positions32[idx] = 0.0;
  44642. this._positions32[idx + 1] = 0.0;
  44643. this._positions32[idx + 2] = 0.0;
  44644. this._normals32[idx] = 0.0;
  44645. this._normals32[idx + 1] = 0.0;
  44646. this._normals32[idx + 2] = 0.0;
  44647. if (this._computeParticleColor) {
  44648. this._colors32[colidx] = this._particle.color.r;
  44649. this._colors32[colidx + 1] = this._particle.color.g;
  44650. this._colors32[colidx + 2] = this._particle.color.b;
  44651. this._colors32[colidx + 3] = this._particle.color.a;
  44652. }
  44653. if (this._computeParticleTexture) {
  44654. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  44655. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  44656. }
  44657. }
  44658. }
  44659. // if the particle intersections must be computed : update the bbInfo
  44660. if (this._particlesIntersect) {
  44661. var bInfo = this._particle._boundingInfo;
  44662. var bBox = bInfo.boundingBox;
  44663. var bSphere = bInfo.boundingSphere;
  44664. if (!this._bSphereOnly) {
  44665. // place, scale and rotate the particle bbox within the SPS local system, then update it
  44666. for (var b = 0; b < bBox.vectors.length; b++) {
  44667. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  44668. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  44669. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  44670. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  44671. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  44672. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  44673. 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;
  44674. 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;
  44675. 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;
  44676. }
  44677. bBox._update(this.mesh._worldMatrix);
  44678. }
  44679. // place and scale the particle bouding sphere in the SPS local system, then update it
  44680. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  44681. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  44682. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  44683. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  44684. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  44685. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  44686. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  44687. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  44688. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  44689. 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));
  44690. bSphere._update(this.mesh._worldMatrix);
  44691. }
  44692. // increment indexes for the next particle
  44693. index = idx + 3;
  44694. colorIndex = colidx + 4;
  44695. uvIndex = uvidx + 2;
  44696. }
  44697. // if the VBO must be updated
  44698. if (update) {
  44699. if (this._computeParticleColor) {
  44700. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  44701. }
  44702. if (this._computeParticleTexture) {
  44703. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  44704. }
  44705. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  44706. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  44707. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  44708. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  44709. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  44710. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  44711. for (var i = 0; i < this._normals32.length; i++) {
  44712. this._fixedNormal32[i] = this._normals32[i];
  44713. }
  44714. }
  44715. if (!this.mesh.areNormalsFrozen) {
  44716. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  44717. }
  44718. }
  44719. if (this._depthSort && this._depthSortParticles) {
  44720. this.depthSortedParticles.sort(this._depthSortFunction);
  44721. var dspl = this.depthSortedParticles.length;
  44722. var sorted = 0;
  44723. var lind = 0;
  44724. var sind = 0;
  44725. var sid = 0;
  44726. for (sorted = 0; sorted < dspl; sorted++) {
  44727. lind = this.depthSortedParticles[sorted].indicesLength;
  44728. sind = this.depthSortedParticles[sorted].ind;
  44729. for (var i = 0; i < lind; i++) {
  44730. this._depthSortedIndices[sid] = this._indices[sind + i];
  44731. sid++;
  44732. }
  44733. }
  44734. this.mesh.updateIndices(this._depthSortedIndices);
  44735. }
  44736. }
  44737. if (this._computeBoundingBox) {
  44738. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  44739. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  44740. }
  44741. this.afterUpdateParticles(start, end, update);
  44742. return this;
  44743. };
  44744. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  44745. this._halfroll = this._roll * 0.5;
  44746. this._halfpitch = this._pitch * 0.5;
  44747. this._halfyaw = this._yaw * 0.5;
  44748. this._sinRoll = Math.sin(this._halfroll);
  44749. this._cosRoll = Math.cos(this._halfroll);
  44750. this._sinPitch = Math.sin(this._halfpitch);
  44751. this._cosPitch = Math.cos(this._halfpitch);
  44752. this._sinYaw = Math.sin(this._halfyaw);
  44753. this._cosYaw = Math.cos(this._halfyaw);
  44754. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  44755. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  44756. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  44757. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  44758. };
  44759. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  44760. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  44761. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  44762. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  44763. this._rotMatrix.m[3] = 0;
  44764. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  44765. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  44766. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  44767. this._rotMatrix.m[7] = 0;
  44768. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  44769. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  44770. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  44771. this._rotMatrix.m[11] = 0;
  44772. this._rotMatrix.m[12] = 0;
  44773. this._rotMatrix.m[13] = 0;
  44774. this._rotMatrix.m[14] = 0;
  44775. this._rotMatrix.m[15] = 1.0;
  44776. };
  44777. /**
  44778. * Disposes the SPS.
  44779. * Returns nothing.
  44780. */
  44781. SolidParticleSystem.prototype.dispose = function () {
  44782. this.mesh.dispose();
  44783. this.vars = null;
  44784. // drop references to internal big arrays for the GC
  44785. this._positions = null;
  44786. this._indices = null;
  44787. this._normals = null;
  44788. this._uvs = null;
  44789. this._colors = null;
  44790. this._positions32 = null;
  44791. this._normals32 = null;
  44792. this._fixedNormal32 = null;
  44793. this._uvs32 = null;
  44794. this._colors32 = null;
  44795. this.pickedParticles = null;
  44796. };
  44797. /**
  44798. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  44799. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  44800. * Returns the SPS.
  44801. */
  44802. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  44803. if (!this._isVisibilityBoxLocked) {
  44804. this.mesh.refreshBoundingInfo();
  44805. }
  44806. return this;
  44807. };
  44808. /**
  44809. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  44810. * @param size the size (float) of the visibility box
  44811. * note : this doesn't lock the SPS mesh bounding box.
  44812. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  44813. */
  44814. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  44815. var vis = size / 2;
  44816. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  44817. };
  44818. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  44819. // getter and setter
  44820. get: function () {
  44821. return this._alwaysVisible;
  44822. },
  44823. /**
  44824. * Sets the SPS as always visible or not
  44825. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  44826. */
  44827. set: function (val) {
  44828. this._alwaysVisible = val;
  44829. this.mesh.alwaysSelectAsActiveMesh = val;
  44830. },
  44831. enumerable: true,
  44832. configurable: true
  44833. });
  44834. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  44835. get: function () {
  44836. return this._isVisibilityBoxLocked;
  44837. },
  44838. /**
  44839. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  44840. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  44841. */
  44842. set: function (val) {
  44843. this._isVisibilityBoxLocked = val;
  44844. this.mesh.getBoundingInfo().isLocked = val;
  44845. },
  44846. enumerable: true,
  44847. configurable: true
  44848. });
  44849. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  44850. // getters
  44851. get: function () {
  44852. return this._computeParticleRotation;
  44853. },
  44854. // Optimizer setters
  44855. /**
  44856. * Tells to `setParticles()` to compute the particle rotations or not.
  44857. * Default value : true. The SPS is faster when it's set to false.
  44858. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  44859. */
  44860. set: function (val) {
  44861. this._computeParticleRotation = val;
  44862. },
  44863. enumerable: true,
  44864. configurable: true
  44865. });
  44866. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  44867. get: function () {
  44868. return this._computeParticleColor;
  44869. },
  44870. /**
  44871. * Tells to `setParticles()` to compute the particle colors or not.
  44872. * Default value : true. The SPS is faster when it's set to false.
  44873. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  44874. */
  44875. set: function (val) {
  44876. this._computeParticleColor = val;
  44877. },
  44878. enumerable: true,
  44879. configurable: true
  44880. });
  44881. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  44882. get: function () {
  44883. return this._computeParticleTexture;
  44884. },
  44885. /**
  44886. * Tells to `setParticles()` to compute the particle textures or not.
  44887. * Default value : true. The SPS is faster when it's set to false.
  44888. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  44889. */
  44890. set: function (val) {
  44891. this._computeParticleTexture = val;
  44892. },
  44893. enumerable: true,
  44894. configurable: true
  44895. });
  44896. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  44897. get: function () {
  44898. return this._computeParticleVertex;
  44899. },
  44900. /**
  44901. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  44902. * Default value : false. The SPS is faster when it's set to false.
  44903. * Note : the particle custom vertex positions aren't stored values.
  44904. */
  44905. set: function (val) {
  44906. this._computeParticleVertex = val;
  44907. },
  44908. enumerable: true,
  44909. configurable: true
  44910. });
  44911. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  44912. get: function () {
  44913. return this._computeBoundingBox;
  44914. },
  44915. /**
  44916. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  44917. */
  44918. set: function (val) {
  44919. this._computeBoundingBox = val;
  44920. },
  44921. enumerable: true,
  44922. configurable: true
  44923. });
  44924. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  44925. get: function () {
  44926. return this._depthSortParticles;
  44927. },
  44928. /**
  44929. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  44930. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  44931. * Default : `true`
  44932. */
  44933. set: function (val) {
  44934. this._depthSortParticles = val;
  44935. },
  44936. enumerable: true,
  44937. configurable: true
  44938. });
  44939. // =======================================================================
  44940. // Particle behavior logic
  44941. // these following methods may be overwritten by the user to fit his needs
  44942. /**
  44943. * This function does nothing. It may be overwritten to set all the particle first values.
  44944. * The SPS doesn't call this function, you may have to call it by your own.
  44945. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  44946. */
  44947. SolidParticleSystem.prototype.initParticles = function () {
  44948. };
  44949. /**
  44950. * This function does nothing. It may be overwritten to recycle a particle.
  44951. * The SPS doesn't call this function, you may have to call it by your own.
  44952. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  44953. */
  44954. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  44955. return particle;
  44956. };
  44957. /**
  44958. * Updates a particle : this function should be overwritten by the user.
  44959. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  44960. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  44961. * ex : just set a particle position or velocity and recycle conditions
  44962. */
  44963. SolidParticleSystem.prototype.updateParticle = function (particle) {
  44964. return particle;
  44965. };
  44966. /**
  44967. * Updates a vertex of a particle : it can be overwritten by the user.
  44968. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  44969. * @param particle the current particle
  44970. * @param vertex the current index of the current particle
  44971. * @param pt the index of the current vertex in the particle shape
  44972. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  44973. * ex : just set a vertex particle position
  44974. */
  44975. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  44976. return vertex;
  44977. };
  44978. /**
  44979. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  44980. * This does nothing and may be overwritten by the user.
  44981. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  44982. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  44983. * @param update the boolean update value actually passed to setParticles()
  44984. */
  44985. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  44986. };
  44987. /**
  44988. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  44989. * This will be passed three parameters.
  44990. * This does nothing and may be overwritten by the user.
  44991. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  44992. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  44993. * @param update the boolean update value actually passed to setParticles()
  44994. */
  44995. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  44996. };
  44997. return SolidParticleSystem;
  44998. }());
  44999. BABYLON.SolidParticleSystem = SolidParticleSystem;
  45000. })(BABYLON || (BABYLON = {}));
  45001. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  45002. /// <reference path="babylon.mesh.ts" />
  45003. var BABYLON;
  45004. (function (BABYLON) {
  45005. var GroundMesh = /** @class */ (function (_super) {
  45006. __extends(GroundMesh, _super);
  45007. function GroundMesh(name, scene) {
  45008. var _this = _super.call(this, name, scene) || this;
  45009. _this.generateOctree = false;
  45010. return _this;
  45011. }
  45012. GroundMesh.prototype.getClassName = function () {
  45013. return "GroundMesh";
  45014. };
  45015. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  45016. get: function () {
  45017. return Math.min(this._subdivisionsX, this._subdivisionsY);
  45018. },
  45019. enumerable: true,
  45020. configurable: true
  45021. });
  45022. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  45023. get: function () {
  45024. return this._subdivisionsX;
  45025. },
  45026. enumerable: true,
  45027. configurable: true
  45028. });
  45029. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  45030. get: function () {
  45031. return this._subdivisionsY;
  45032. },
  45033. enumerable: true,
  45034. configurable: true
  45035. });
  45036. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  45037. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  45038. this._subdivisionsX = chunksCount;
  45039. this._subdivisionsY = chunksCount;
  45040. this.subdivide(chunksCount);
  45041. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  45042. };
  45043. /**
  45044. * Returns a height (y) value in the Worl system :
  45045. * the ground altitude at the coordinates (x, z) expressed in the World system.
  45046. * Returns the ground y position if (x, z) are outside the ground surface.
  45047. */
  45048. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  45049. var world = this.getWorldMatrix();
  45050. var invMat = BABYLON.Tmp.Matrix[5];
  45051. world.invertToRef(invMat);
  45052. var tmpVect = BABYLON.Tmp.Vector3[8];
  45053. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  45054. x = tmpVect.x;
  45055. z = tmpVect.z;
  45056. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  45057. return this.position.y;
  45058. }
  45059. if (!this._heightQuads || this._heightQuads.length == 0) {
  45060. this._initHeightQuads();
  45061. this._computeHeightQuads();
  45062. }
  45063. var facet = this._getFacetAt(x, z);
  45064. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  45065. // return y in the World system
  45066. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  45067. return tmpVect.y;
  45068. };
  45069. /**
  45070. * Returns a normalized vector (Vector3) orthogonal to the ground
  45071. * at the ground coordinates (x, z) expressed in the World system.
  45072. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  45073. */
  45074. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  45075. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  45076. this.getNormalAtCoordinatesToRef(x, z, normal);
  45077. return normal;
  45078. };
  45079. /**
  45080. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  45081. * at the ground coordinates (x, z) expressed in the World system.
  45082. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  45083. * Returns the GroundMesh.
  45084. */
  45085. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  45086. var world = this.getWorldMatrix();
  45087. var tmpMat = BABYLON.Tmp.Matrix[5];
  45088. world.invertToRef(tmpMat);
  45089. var tmpVect = BABYLON.Tmp.Vector3[8];
  45090. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  45091. x = tmpVect.x;
  45092. z = tmpVect.z;
  45093. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  45094. return this;
  45095. }
  45096. if (!this._heightQuads || this._heightQuads.length == 0) {
  45097. this._initHeightQuads();
  45098. this._computeHeightQuads();
  45099. }
  45100. var facet = this._getFacetAt(x, z);
  45101. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  45102. return this;
  45103. };
  45104. /**
  45105. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  45106. * if the ground has been updated.
  45107. * This can be used in the render loop.
  45108. * Returns the GroundMesh.
  45109. */
  45110. GroundMesh.prototype.updateCoordinateHeights = function () {
  45111. if (!this._heightQuads || this._heightQuads.length == 0) {
  45112. this._initHeightQuads();
  45113. }
  45114. this._computeHeightQuads();
  45115. return this;
  45116. };
  45117. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  45118. GroundMesh.prototype._getFacetAt = function (x, z) {
  45119. // retrieve col and row from x, z coordinates in the ground local system
  45120. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  45121. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  45122. var quad = this._heightQuads[row * this._subdivisionsX + col];
  45123. var facet;
  45124. if (z < quad.slope.x * x + quad.slope.y) {
  45125. facet = quad.facet1;
  45126. }
  45127. else {
  45128. facet = quad.facet2;
  45129. }
  45130. return facet;
  45131. };
  45132. // Creates and populates the heightMap array with "facet" elements :
  45133. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  45134. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  45135. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  45136. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  45137. // Returns the GroundMesh.
  45138. GroundMesh.prototype._initHeightQuads = function () {
  45139. var subdivisionsX = this._subdivisionsX;
  45140. var subdivisionsY = this._subdivisionsY;
  45141. this._heightQuads = new Array();
  45142. for (var row = 0; row < subdivisionsY; row++) {
  45143. for (var col = 0; col < subdivisionsX; col++) {
  45144. 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) };
  45145. this._heightQuads[row * subdivisionsX + col] = quad;
  45146. }
  45147. }
  45148. return this;
  45149. };
  45150. // Compute each quad element values and update the the heightMap array :
  45151. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  45152. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  45153. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  45154. // Returns the GroundMesh.
  45155. GroundMesh.prototype._computeHeightQuads = function () {
  45156. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45157. var v1 = BABYLON.Tmp.Vector3[3];
  45158. var v2 = BABYLON.Tmp.Vector3[2];
  45159. var v3 = BABYLON.Tmp.Vector3[1];
  45160. var v4 = BABYLON.Tmp.Vector3[0];
  45161. var v1v2 = BABYLON.Tmp.Vector3[4];
  45162. var v1v3 = BABYLON.Tmp.Vector3[5];
  45163. var v1v4 = BABYLON.Tmp.Vector3[6];
  45164. var norm1 = BABYLON.Tmp.Vector3[7];
  45165. var norm2 = BABYLON.Tmp.Vector3[8];
  45166. var i = 0;
  45167. var j = 0;
  45168. var k = 0;
  45169. var cd = 0; // 2D slope coefficient : z = cd * x + h
  45170. var h = 0;
  45171. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  45172. var d2 = 0;
  45173. var subdivisionsX = this._subdivisionsX;
  45174. var subdivisionsY = this._subdivisionsY;
  45175. for (var row = 0; row < subdivisionsY; row++) {
  45176. for (var col = 0; col < subdivisionsX; col++) {
  45177. i = col * 3;
  45178. j = row * (subdivisionsX + 1) * 3;
  45179. k = (row + 1) * (subdivisionsX + 1) * 3;
  45180. v1.x = positions[j + i];
  45181. v1.y = positions[j + i + 1];
  45182. v1.z = positions[j + i + 2];
  45183. v2.x = positions[j + i + 3];
  45184. v2.y = positions[j + i + 4];
  45185. v2.z = positions[j + i + 5];
  45186. v3.x = positions[k + i];
  45187. v3.y = positions[k + i + 1];
  45188. v3.z = positions[k + i + 2];
  45189. v4.x = positions[k + i + 3];
  45190. v4.y = positions[k + i + 4];
  45191. v4.z = positions[k + i + 5];
  45192. // 2D slope V1V4
  45193. cd = (v4.z - v1.z) / (v4.x - v1.x);
  45194. h = v1.z - cd * v1.x; // v1 belongs to the slope
  45195. // facet equations :
  45196. // we compute each facet normal vector
  45197. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  45198. // we compute the value d by applying the equation to v1 which belongs to the plane
  45199. // then we store the facet equation in a Vector4
  45200. v2.subtractToRef(v1, v1v2);
  45201. v3.subtractToRef(v1, v1v3);
  45202. v4.subtractToRef(v1, v1v4);
  45203. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  45204. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  45205. norm1.normalize();
  45206. norm2.normalize();
  45207. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  45208. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  45209. var quad = this._heightQuads[row * subdivisionsX + col];
  45210. quad.slope.copyFromFloats(cd, h);
  45211. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  45212. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  45213. }
  45214. }
  45215. return this;
  45216. };
  45217. GroundMesh.prototype.serialize = function (serializationObject) {
  45218. _super.prototype.serialize.call(this, serializationObject);
  45219. serializationObject.subdivisionsX = this._subdivisionsX;
  45220. serializationObject.subdivisionsY = this._subdivisionsY;
  45221. serializationObject.minX = this._minX;
  45222. serializationObject.maxX = this._maxX;
  45223. serializationObject.minZ = this._minZ;
  45224. serializationObject.maxZ = this._maxZ;
  45225. serializationObject.width = this._width;
  45226. serializationObject.height = this._height;
  45227. };
  45228. GroundMesh.Parse = function (parsedMesh, scene) {
  45229. var result = new GroundMesh(parsedMesh.name, scene);
  45230. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  45231. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  45232. result._minX = parsedMesh.minX;
  45233. result._maxX = parsedMesh.maxX;
  45234. result._minZ = parsedMesh.minZ;
  45235. result._maxZ = parsedMesh.maxZ;
  45236. result._width = parsedMesh.width;
  45237. result._height = parsedMesh.height;
  45238. return result;
  45239. };
  45240. return GroundMesh;
  45241. }(BABYLON.Mesh));
  45242. BABYLON.GroundMesh = GroundMesh;
  45243. })(BABYLON || (BABYLON = {}));
  45244. //# sourceMappingURL=babylon.groundMesh.js.map
  45245. var BABYLON;
  45246. (function (BABYLON) {
  45247. /**
  45248. * Creates an instance based on a source mesh.
  45249. */
  45250. var InstancedMesh = /** @class */ (function (_super) {
  45251. __extends(InstancedMesh, _super);
  45252. function InstancedMesh(name, source) {
  45253. var _this = _super.call(this, name, source.getScene()) || this;
  45254. source.instances.push(_this);
  45255. _this._sourceMesh = source;
  45256. _this.position.copyFrom(source.position);
  45257. _this.rotation.copyFrom(source.rotation);
  45258. _this.scaling.copyFrom(source.scaling);
  45259. if (source.rotationQuaternion) {
  45260. _this.rotationQuaternion = source.rotationQuaternion.clone();
  45261. }
  45262. _this.infiniteDistance = source.infiniteDistance;
  45263. _this.setPivotMatrix(source.getPivotMatrix());
  45264. _this.refreshBoundingInfo();
  45265. _this._syncSubMeshes();
  45266. return _this;
  45267. }
  45268. /**
  45269. * Returns the string "InstancedMesh".
  45270. */
  45271. InstancedMesh.prototype.getClassName = function () {
  45272. return "InstancedMesh";
  45273. };
  45274. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  45275. // Methods
  45276. get: function () {
  45277. return this._sourceMesh.receiveShadows;
  45278. },
  45279. enumerable: true,
  45280. configurable: true
  45281. });
  45282. Object.defineProperty(InstancedMesh.prototype, "material", {
  45283. get: function () {
  45284. return this._sourceMesh.material;
  45285. },
  45286. enumerable: true,
  45287. configurable: true
  45288. });
  45289. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  45290. get: function () {
  45291. return this._sourceMesh.visibility;
  45292. },
  45293. enumerable: true,
  45294. configurable: true
  45295. });
  45296. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  45297. get: function () {
  45298. return this._sourceMesh.skeleton;
  45299. },
  45300. enumerable: true,
  45301. configurable: true
  45302. });
  45303. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  45304. get: function () {
  45305. return this._sourceMesh.renderingGroupId;
  45306. },
  45307. enumerable: true,
  45308. configurable: true
  45309. });
  45310. /**
  45311. * Returns the total number of vertices (integer).
  45312. */
  45313. InstancedMesh.prototype.getTotalVertices = function () {
  45314. return this._sourceMesh.getTotalVertices();
  45315. };
  45316. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  45317. get: function () {
  45318. return this._sourceMesh;
  45319. },
  45320. enumerable: true,
  45321. configurable: true
  45322. });
  45323. /**
  45324. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  45325. */
  45326. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  45327. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  45328. };
  45329. /**
  45330. * Sets the vertex data of the mesh geometry for the requested `kind`.
  45331. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  45332. * The `data` are either a numeric array either a Float32Array.
  45333. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  45334. * 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).
  45335. * Note that a new underlying VertexBuffer object is created each call.
  45336. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  45337. *
  45338. * Possible `kind` values :
  45339. * - BABYLON.VertexBuffer.PositionKind
  45340. * - BABYLON.VertexBuffer.UVKind
  45341. * - BABYLON.VertexBuffer.UV2Kind
  45342. * - BABYLON.VertexBuffer.UV3Kind
  45343. * - BABYLON.VertexBuffer.UV4Kind
  45344. * - BABYLON.VertexBuffer.UV5Kind
  45345. * - BABYLON.VertexBuffer.UV6Kind
  45346. * - BABYLON.VertexBuffer.ColorKind
  45347. * - BABYLON.VertexBuffer.MatricesIndicesKind
  45348. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  45349. * - BABYLON.VertexBuffer.MatricesWeightsKind
  45350. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  45351. *
  45352. * Returns the Mesh.
  45353. */
  45354. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  45355. if (this.sourceMesh) {
  45356. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  45357. }
  45358. return this.sourceMesh;
  45359. };
  45360. /**
  45361. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  45362. * If the mesh has no geometry, it is simply returned as it is.
  45363. * The `data` are either a numeric array either a Float32Array.
  45364. * No new underlying VertexBuffer object is created.
  45365. * 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.
  45366. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  45367. *
  45368. * Possible `kind` values :
  45369. * - BABYLON.VertexBuffer.PositionKind
  45370. * - BABYLON.VertexBuffer.UVKind
  45371. * - BABYLON.VertexBuffer.UV2Kind
  45372. * - BABYLON.VertexBuffer.UV3Kind
  45373. * - BABYLON.VertexBuffer.UV4Kind
  45374. * - BABYLON.VertexBuffer.UV5Kind
  45375. * - BABYLON.VertexBuffer.UV6Kind
  45376. * - BABYLON.VertexBuffer.ColorKind
  45377. * - BABYLON.VertexBuffer.MatricesIndicesKind
  45378. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  45379. * - BABYLON.VertexBuffer.MatricesWeightsKind
  45380. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  45381. *
  45382. * Returns the Mesh.
  45383. */
  45384. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  45385. if (this.sourceMesh) {
  45386. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  45387. }
  45388. return this.sourceMesh;
  45389. };
  45390. /**
  45391. * Sets the mesh indices.
  45392. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  45393. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  45394. * This method creates a new index buffer each call.
  45395. * Returns the Mesh.
  45396. */
  45397. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  45398. if (totalVertices === void 0) { totalVertices = null; }
  45399. if (this.sourceMesh) {
  45400. this.sourceMesh.setIndices(indices, totalVertices);
  45401. }
  45402. return this.sourceMesh;
  45403. };
  45404. /**
  45405. * Boolean : True if the mesh owns the requested kind of data.
  45406. */
  45407. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  45408. return this._sourceMesh.isVerticesDataPresent(kind);
  45409. };
  45410. /**
  45411. * Returns an array of indices (IndicesArray).
  45412. */
  45413. InstancedMesh.prototype.getIndices = function () {
  45414. return this._sourceMesh.getIndices();
  45415. };
  45416. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  45417. get: function () {
  45418. return this._sourceMesh._positions;
  45419. },
  45420. enumerable: true,
  45421. configurable: true
  45422. });
  45423. /**
  45424. * Sets a new updated BoundingInfo to the mesh.
  45425. * Returns the mesh.
  45426. */
  45427. InstancedMesh.prototype.refreshBoundingInfo = function () {
  45428. var meshBB = this._sourceMesh.getBoundingInfo();
  45429. if (meshBB) {
  45430. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  45431. }
  45432. this._updateBoundingInfo();
  45433. return this;
  45434. };
  45435. InstancedMesh.prototype._preActivate = function () {
  45436. if (this._currentLOD) {
  45437. this._currentLOD._preActivate();
  45438. }
  45439. return this;
  45440. };
  45441. InstancedMesh.prototype._activate = function (renderId) {
  45442. if (this._currentLOD) {
  45443. this._currentLOD._registerInstanceForRenderId(this, renderId);
  45444. }
  45445. return this;
  45446. };
  45447. /**
  45448. * Returns the current associated LOD AbstractMesh.
  45449. */
  45450. InstancedMesh.prototype.getLOD = function (camera) {
  45451. if (!camera) {
  45452. return this;
  45453. }
  45454. var boundingInfo = this.getBoundingInfo();
  45455. if (!boundingInfo) {
  45456. return this;
  45457. }
  45458. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  45459. if (this._currentLOD === this.sourceMesh) {
  45460. return this;
  45461. }
  45462. return this._currentLOD;
  45463. };
  45464. InstancedMesh.prototype._syncSubMeshes = function () {
  45465. this.releaseSubMeshes();
  45466. if (this._sourceMesh.subMeshes) {
  45467. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  45468. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  45469. }
  45470. }
  45471. return this;
  45472. };
  45473. InstancedMesh.prototype._generatePointsArray = function () {
  45474. return this._sourceMesh._generatePointsArray();
  45475. };
  45476. /**
  45477. * Creates a new InstancedMesh from the current mesh.
  45478. * - name (string) : the cloned mesh name
  45479. * - newParent (optional Node) : the optional Node to parent the clone to.
  45480. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  45481. *
  45482. * Returns the clone.
  45483. */
  45484. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  45485. var result = this._sourceMesh.createInstance(name);
  45486. // Deep copy
  45487. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  45488. // Bounding info
  45489. this.refreshBoundingInfo();
  45490. // Parent
  45491. if (newParent) {
  45492. result.parent = newParent;
  45493. }
  45494. if (!doNotCloneChildren) {
  45495. // Children
  45496. for (var index = 0; index < this.getScene().meshes.length; index++) {
  45497. var mesh = this.getScene().meshes[index];
  45498. if (mesh.parent === this) {
  45499. mesh.clone(mesh.name, result);
  45500. }
  45501. }
  45502. }
  45503. result.computeWorldMatrix(true);
  45504. return result;
  45505. };
  45506. /**
  45507. * Disposes the InstancedMesh.
  45508. * Returns nothing.
  45509. */
  45510. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  45511. // Remove from mesh
  45512. var index = this._sourceMesh.instances.indexOf(this);
  45513. this._sourceMesh.instances.splice(index, 1);
  45514. _super.prototype.dispose.call(this, doNotRecurse);
  45515. };
  45516. return InstancedMesh;
  45517. }(BABYLON.AbstractMesh));
  45518. BABYLON.InstancedMesh = InstancedMesh;
  45519. })(BABYLON || (BABYLON = {}));
  45520. //# sourceMappingURL=babylon.instancedMesh.js.map
  45521. /// <reference path="babylon.mesh.ts" />
  45522. var BABYLON;
  45523. (function (BABYLON) {
  45524. var LinesMesh = /** @class */ (function (_super) {
  45525. __extends(LinesMesh, _super);
  45526. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  45527. if (parent === void 0) { parent = null; }
  45528. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  45529. _this.useVertexColor = useVertexColor;
  45530. _this.color = new BABYLON.Color3(1, 1, 1);
  45531. _this.alpha = 1;
  45532. if (source) {
  45533. _this.color = source.color.clone();
  45534. _this.alpha = source.alpha;
  45535. _this.useVertexColor = source.useVertexColor;
  45536. }
  45537. _this._intersectionThreshold = 0.1;
  45538. var options = {
  45539. attributes: [BABYLON.VertexBuffer.PositionKind],
  45540. uniforms: ["world", "viewProjection"],
  45541. needAlphaBlending: false,
  45542. };
  45543. if (!useVertexColor) {
  45544. options.uniforms.push("color");
  45545. options.needAlphaBlending = true;
  45546. }
  45547. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  45548. return _this;
  45549. }
  45550. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  45551. /**
  45552. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  45553. * This margin is expressed in world space coordinates, so its value may vary.
  45554. * Default value is 0.1
  45555. * @returns the intersection Threshold value.
  45556. */
  45557. get: function () {
  45558. return this._intersectionThreshold;
  45559. },
  45560. /**
  45561. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  45562. * This margin is expressed in world space coordinates, so its value may vary.
  45563. * @param value the new threshold to apply
  45564. */
  45565. set: function (value) {
  45566. if (this._intersectionThreshold === value) {
  45567. return;
  45568. }
  45569. this._intersectionThreshold = value;
  45570. if (this.geometry) {
  45571. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  45572. }
  45573. },
  45574. enumerable: true,
  45575. configurable: true
  45576. });
  45577. /**
  45578. * Returns the string "LineMesh"
  45579. */
  45580. LinesMesh.prototype.getClassName = function () {
  45581. return "LinesMesh";
  45582. };
  45583. Object.defineProperty(LinesMesh.prototype, "material", {
  45584. get: function () {
  45585. return this._colorShader;
  45586. },
  45587. enumerable: true,
  45588. configurable: true
  45589. });
  45590. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  45591. get: function () {
  45592. return false;
  45593. },
  45594. enumerable: true,
  45595. configurable: true
  45596. });
  45597. LinesMesh.prototype.createInstance = function (name) {
  45598. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  45599. return null;
  45600. };
  45601. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  45602. // VBOs
  45603. this._geometry._bind(this._colorShader.getEffect());
  45604. // Color
  45605. if (!this.useVertexColor) {
  45606. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  45607. }
  45608. return this;
  45609. };
  45610. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  45611. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  45612. return this;
  45613. }
  45614. var engine = this.getScene().getEngine();
  45615. // Draw order
  45616. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  45617. return this;
  45618. };
  45619. LinesMesh.prototype.dispose = function (doNotRecurse) {
  45620. this._colorShader.dispose();
  45621. _super.prototype.dispose.call(this, doNotRecurse);
  45622. };
  45623. /**
  45624. * Returns a new LineMesh object cloned from the current one.
  45625. */
  45626. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  45627. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  45628. };
  45629. return LinesMesh;
  45630. }(BABYLON.Mesh));
  45631. BABYLON.LinesMesh = LinesMesh;
  45632. })(BABYLON || (BABYLON = {}));
  45633. //# sourceMappingURL=babylon.linesMesh.js.map
  45634. var BABYLON;
  45635. (function (BABYLON) {
  45636. var ShaderMaterial = /** @class */ (function (_super) {
  45637. __extends(ShaderMaterial, _super);
  45638. function ShaderMaterial(name, scene, shaderPath, options) {
  45639. var _this = _super.call(this, name, scene) || this;
  45640. _this._textures = {};
  45641. _this._textureArrays = {};
  45642. _this._floats = {};
  45643. _this._floatsArrays = {};
  45644. _this._colors3 = {};
  45645. _this._colors3Arrays = {};
  45646. _this._colors4 = {};
  45647. _this._vectors2 = {};
  45648. _this._vectors3 = {};
  45649. _this._vectors4 = {};
  45650. _this._matrices = {};
  45651. _this._matrices3x3 = {};
  45652. _this._matrices2x2 = {};
  45653. _this._vectors3Arrays = {};
  45654. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  45655. _this._shaderPath = shaderPath;
  45656. options.needAlphaBlending = options.needAlphaBlending || false;
  45657. options.needAlphaTesting = options.needAlphaTesting || false;
  45658. options.attributes = options.attributes || ["position", "normal", "uv"];
  45659. options.uniforms = options.uniforms || ["worldViewProjection"];
  45660. options.uniformBuffers = options.uniformBuffers || [];
  45661. options.samplers = options.samplers || [];
  45662. options.defines = options.defines || [];
  45663. _this._options = options;
  45664. return _this;
  45665. }
  45666. ShaderMaterial.prototype.getClassName = function () {
  45667. return "ShaderMaterial";
  45668. };
  45669. ShaderMaterial.prototype.needAlphaBlending = function () {
  45670. return this._options.needAlphaBlending;
  45671. };
  45672. ShaderMaterial.prototype.needAlphaTesting = function () {
  45673. return this._options.needAlphaTesting;
  45674. };
  45675. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  45676. if (this._options.uniforms.indexOf(uniformName) === -1) {
  45677. this._options.uniforms.push(uniformName);
  45678. }
  45679. };
  45680. ShaderMaterial.prototype.setTexture = function (name, texture) {
  45681. if (this._options.samplers.indexOf(name) === -1) {
  45682. this._options.samplers.push(name);
  45683. }
  45684. this._textures[name] = texture;
  45685. return this;
  45686. };
  45687. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  45688. if (this._options.samplers.indexOf(name) === -1) {
  45689. this._options.samplers.push(name);
  45690. }
  45691. this._checkUniform(name);
  45692. this._textureArrays[name] = textures;
  45693. return this;
  45694. };
  45695. ShaderMaterial.prototype.setFloat = function (name, value) {
  45696. this._checkUniform(name);
  45697. this._floats[name] = value;
  45698. return this;
  45699. };
  45700. ShaderMaterial.prototype.setFloats = function (name, value) {
  45701. this._checkUniform(name);
  45702. this._floatsArrays[name] = value;
  45703. return this;
  45704. };
  45705. ShaderMaterial.prototype.setColor3 = function (name, value) {
  45706. this._checkUniform(name);
  45707. this._colors3[name] = value;
  45708. return this;
  45709. };
  45710. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  45711. this._checkUniform(name);
  45712. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  45713. color.toArray(arr, arr.length);
  45714. return arr;
  45715. }, []);
  45716. return this;
  45717. };
  45718. ShaderMaterial.prototype.setColor4 = function (name, value) {
  45719. this._checkUniform(name);
  45720. this._colors4[name] = value;
  45721. return this;
  45722. };
  45723. ShaderMaterial.prototype.setVector2 = function (name, value) {
  45724. this._checkUniform(name);
  45725. this._vectors2[name] = value;
  45726. return this;
  45727. };
  45728. ShaderMaterial.prototype.setVector3 = function (name, value) {
  45729. this._checkUniform(name);
  45730. this._vectors3[name] = value;
  45731. return this;
  45732. };
  45733. ShaderMaterial.prototype.setVector4 = function (name, value) {
  45734. this._checkUniform(name);
  45735. this._vectors4[name] = value;
  45736. return this;
  45737. };
  45738. ShaderMaterial.prototype.setMatrix = function (name, value) {
  45739. this._checkUniform(name);
  45740. this._matrices[name] = value;
  45741. return this;
  45742. };
  45743. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  45744. this._checkUniform(name);
  45745. this._matrices3x3[name] = value;
  45746. return this;
  45747. };
  45748. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  45749. this._checkUniform(name);
  45750. this._matrices2x2[name] = value;
  45751. return this;
  45752. };
  45753. ShaderMaterial.prototype.setArray3 = function (name, value) {
  45754. this._checkUniform(name);
  45755. this._vectors3Arrays[name] = value;
  45756. return this;
  45757. };
  45758. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  45759. if (!mesh) {
  45760. return true;
  45761. }
  45762. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  45763. return false;
  45764. }
  45765. return false;
  45766. };
  45767. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  45768. var scene = this.getScene();
  45769. var engine = scene.getEngine();
  45770. if (!this.checkReadyOnEveryCall) {
  45771. if (this._renderId === scene.getRenderId()) {
  45772. if (this._checkCache(scene, mesh, useInstances)) {
  45773. return true;
  45774. }
  45775. }
  45776. }
  45777. // Instances
  45778. var defines = [];
  45779. var attribs = [];
  45780. var fallbacks = new BABYLON.EffectFallbacks();
  45781. if (useInstances) {
  45782. defines.push("#define INSTANCES");
  45783. }
  45784. for (var index = 0; index < this._options.defines.length; index++) {
  45785. defines.push(this._options.defines[index]);
  45786. }
  45787. for (var index = 0; index < this._options.attributes.length; index++) {
  45788. attribs.push(this._options.attributes[index]);
  45789. }
  45790. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  45791. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45792. defines.push("#define VERTEXCOLOR");
  45793. }
  45794. // Bones
  45795. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  45796. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  45797. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  45798. if (mesh.numBoneInfluencers > 4) {
  45799. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  45800. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  45801. }
  45802. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  45803. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  45804. fallbacks.addCPUSkinningFallback(0, mesh);
  45805. if (this._options.uniforms.indexOf("mBones") === -1) {
  45806. this._options.uniforms.push("mBones");
  45807. }
  45808. }
  45809. else {
  45810. defines.push("#define NUM_BONE_INFLUENCERS 0");
  45811. }
  45812. // Textures
  45813. for (var name in this._textures) {
  45814. if (!this._textures[name].isReady()) {
  45815. return false;
  45816. }
  45817. }
  45818. // Alpha test
  45819. if (engine.getAlphaTesting()) {
  45820. defines.push("#define ALPHATEST");
  45821. }
  45822. var previousEffect = this._effect;
  45823. var join = defines.join("\n");
  45824. this._effect = engine.createEffect(this._shaderPath, {
  45825. attributes: attribs,
  45826. uniformsNames: this._options.uniforms,
  45827. uniformBuffersNames: this._options.uniformBuffers,
  45828. samplers: this._options.samplers,
  45829. defines: join,
  45830. fallbacks: fallbacks,
  45831. onCompiled: this.onCompiled,
  45832. onError: this.onError
  45833. }, engine);
  45834. if (!this._effect.isReady()) {
  45835. return false;
  45836. }
  45837. if (previousEffect !== this._effect) {
  45838. scene.resetCachedMaterial();
  45839. }
  45840. this._renderId = scene.getRenderId();
  45841. return true;
  45842. };
  45843. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  45844. var scene = this.getScene();
  45845. if (this._options.uniforms.indexOf("world") !== -1) {
  45846. this._effect.setMatrix("world", world);
  45847. }
  45848. if (this._options.uniforms.indexOf("worldView") !== -1) {
  45849. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  45850. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  45851. }
  45852. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  45853. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  45854. }
  45855. };
  45856. ShaderMaterial.prototype.bind = function (world, mesh) {
  45857. // Std values
  45858. this.bindOnlyWorldMatrix(world);
  45859. if (this.getScene().getCachedMaterial() !== this) {
  45860. if (this._options.uniforms.indexOf("view") !== -1) {
  45861. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  45862. }
  45863. if (this._options.uniforms.indexOf("projection") !== -1) {
  45864. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  45865. }
  45866. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  45867. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  45868. }
  45869. // Bones
  45870. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  45871. var name;
  45872. // Texture
  45873. for (name in this._textures) {
  45874. this._effect.setTexture(name, this._textures[name]);
  45875. }
  45876. // Texture arrays
  45877. for (name in this._textureArrays) {
  45878. this._effect.setTextureArray(name, this._textureArrays[name]);
  45879. }
  45880. // Float
  45881. for (name in this._floats) {
  45882. this._effect.setFloat(name, this._floats[name]);
  45883. }
  45884. // Float s
  45885. for (name in this._floatsArrays) {
  45886. this._effect.setArray(name, this._floatsArrays[name]);
  45887. }
  45888. // Color3
  45889. for (name in this._colors3) {
  45890. this._effect.setColor3(name, this._colors3[name]);
  45891. }
  45892. for (name in this._colors3Arrays) {
  45893. this._effect.setArray3(name, this._colors3Arrays[name]);
  45894. }
  45895. // Color4
  45896. for (name in this._colors4) {
  45897. var color = this._colors4[name];
  45898. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  45899. }
  45900. // Vector2
  45901. for (name in this._vectors2) {
  45902. this._effect.setVector2(name, this._vectors2[name]);
  45903. }
  45904. // Vector3
  45905. for (name in this._vectors3) {
  45906. this._effect.setVector3(name, this._vectors3[name]);
  45907. }
  45908. // Vector4
  45909. for (name in this._vectors4) {
  45910. this._effect.setVector4(name, this._vectors4[name]);
  45911. }
  45912. // Matrix
  45913. for (name in this._matrices) {
  45914. this._effect.setMatrix(name, this._matrices[name]);
  45915. }
  45916. // Matrix 3x3
  45917. for (name in this._matrices3x3) {
  45918. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  45919. }
  45920. // Matrix 2x2
  45921. for (name in this._matrices2x2) {
  45922. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  45923. }
  45924. // Vector3Array
  45925. for (name in this._vectors3Arrays) {
  45926. this._effect.setArray3(name, this._vectors3Arrays[name]);
  45927. }
  45928. }
  45929. this._afterBind(mesh);
  45930. };
  45931. ShaderMaterial.prototype.getActiveTextures = function () {
  45932. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45933. for (var name in this._textures) {
  45934. activeTextures.push(this._textures[name]);
  45935. }
  45936. for (var name in this._textureArrays) {
  45937. var array = this._textureArrays[name];
  45938. for (var index = 0; index < array.length; index++) {
  45939. activeTextures.push(array[index]);
  45940. }
  45941. }
  45942. return activeTextures;
  45943. };
  45944. ShaderMaterial.prototype.hasTexture = function (texture) {
  45945. if (_super.prototype.hasTexture.call(this, texture)) {
  45946. return true;
  45947. }
  45948. for (var name in this._textures) {
  45949. if (this._textures[name] === texture) {
  45950. return true;
  45951. }
  45952. }
  45953. for (var name in this._textureArrays) {
  45954. var array = this._textureArrays[name];
  45955. for (var index = 0; index < array.length; index++) {
  45956. if (array[index] === texture) {
  45957. return true;
  45958. }
  45959. }
  45960. }
  45961. return false;
  45962. };
  45963. ShaderMaterial.prototype.clone = function (name) {
  45964. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  45965. return newShaderMaterial;
  45966. };
  45967. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45968. if (forceDisposeTextures) {
  45969. var name;
  45970. for (name in this._textures) {
  45971. this._textures[name].dispose();
  45972. }
  45973. for (name in this._textureArrays) {
  45974. var array = this._textureArrays[name];
  45975. for (var index = 0; index < array.length; index++) {
  45976. array[index].dispose();
  45977. }
  45978. }
  45979. }
  45980. this._textures = {};
  45981. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45982. };
  45983. ShaderMaterial.prototype.serialize = function () {
  45984. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45985. serializationObject.customType = "BABYLON.ShaderMaterial";
  45986. serializationObject.options = this._options;
  45987. serializationObject.shaderPath = this._shaderPath;
  45988. var name;
  45989. // Texture
  45990. serializationObject.textures = {};
  45991. for (name in this._textures) {
  45992. serializationObject.textures[name] = this._textures[name].serialize();
  45993. }
  45994. // Texture arrays
  45995. serializationObject.textureArrays = {};
  45996. for (name in this._textureArrays) {
  45997. serializationObject.textureArrays[name] = [];
  45998. var array = this._textureArrays[name];
  45999. for (var index = 0; index < array.length; index++) {
  46000. serializationObject.textureArrays[name].push(array[index].serialize());
  46001. }
  46002. }
  46003. // Float
  46004. serializationObject.floats = {};
  46005. for (name in this._floats) {
  46006. serializationObject.floats[name] = this._floats[name];
  46007. }
  46008. // Float s
  46009. serializationObject.floatArrays = {};
  46010. for (name in this._floatsArrays) {
  46011. serializationObject.floatArrays[name] = this._floatsArrays[name];
  46012. }
  46013. // Color3
  46014. serializationObject.colors3 = {};
  46015. for (name in this._colors3) {
  46016. serializationObject.colors3[name] = this._colors3[name].asArray();
  46017. }
  46018. // Color3 array
  46019. serializationObject.colors3Arrays = {};
  46020. for (name in this._colors3Arrays) {
  46021. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  46022. }
  46023. // Color4
  46024. serializationObject.colors4 = {};
  46025. for (name in this._colors4) {
  46026. serializationObject.colors4[name] = this._colors4[name].asArray();
  46027. }
  46028. // Vector2
  46029. serializationObject.vectors2 = {};
  46030. for (name in this._vectors2) {
  46031. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  46032. }
  46033. // Vector3
  46034. serializationObject.vectors3 = {};
  46035. for (name in this._vectors3) {
  46036. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  46037. }
  46038. // Vector4
  46039. serializationObject.vectors4 = {};
  46040. for (name in this._vectors4) {
  46041. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  46042. }
  46043. // Matrix
  46044. serializationObject.matrices = {};
  46045. for (name in this._matrices) {
  46046. serializationObject.matrices[name] = this._matrices[name].asArray();
  46047. }
  46048. // Matrix 3x3
  46049. serializationObject.matrices3x3 = {};
  46050. for (name in this._matrices3x3) {
  46051. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  46052. }
  46053. // Matrix 2x2
  46054. serializationObject.matrices2x2 = {};
  46055. for (name in this._matrices2x2) {
  46056. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  46057. }
  46058. // Vector3Array
  46059. serializationObject.vectors3Arrays = {};
  46060. for (name in this._vectors3Arrays) {
  46061. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  46062. }
  46063. return serializationObject;
  46064. };
  46065. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  46066. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  46067. var name;
  46068. // Texture
  46069. for (name in source.textures) {
  46070. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  46071. }
  46072. // Texture arrays
  46073. for (name in source.textureArrays) {
  46074. var array = source.textureArrays[name];
  46075. var textureArray = new Array();
  46076. for (var index = 0; index < array.length; index++) {
  46077. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  46078. }
  46079. material.setTextureArray(name, textureArray);
  46080. }
  46081. // Float
  46082. for (name in source.floats) {
  46083. material.setFloat(name, source.floats[name]);
  46084. }
  46085. // Float s
  46086. for (name in source.floatsArrays) {
  46087. material.setFloats(name, source.floatsArrays[name]);
  46088. }
  46089. // Color3
  46090. for (name in source.colors3) {
  46091. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  46092. }
  46093. // Color3 arrays
  46094. for (name in source.colors3Arrays) {
  46095. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  46096. if (i % 3 === 0) {
  46097. arr.push([num]);
  46098. }
  46099. else {
  46100. arr[arr.length - 1].push(num);
  46101. }
  46102. return arr;
  46103. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  46104. material.setColor3Array(name, colors);
  46105. }
  46106. // Color4
  46107. for (name in source.colors4) {
  46108. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  46109. }
  46110. // Vector2
  46111. for (name in source.vectors2) {
  46112. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  46113. }
  46114. // Vector3
  46115. for (name in source.vectors3) {
  46116. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  46117. }
  46118. // Vector4
  46119. for (name in source.vectors4) {
  46120. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  46121. }
  46122. // Matrix
  46123. for (name in source.matrices) {
  46124. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  46125. }
  46126. // Matrix 3x3
  46127. for (name in source.matrices3x3) {
  46128. material.setMatrix3x3(name, source.matrices3x3[name]);
  46129. }
  46130. // Matrix 2x2
  46131. for (name in source.matrices2x2) {
  46132. material.setMatrix2x2(name, source.matrices2x2[name]);
  46133. }
  46134. // Vector3Array
  46135. for (name in source.vectors3Arrays) {
  46136. material.setArray3(name, source.vectors3Arrays[name]);
  46137. }
  46138. return material;
  46139. };
  46140. return ShaderMaterial;
  46141. }(BABYLON.Material));
  46142. BABYLON.ShaderMaterial = ShaderMaterial;
  46143. })(BABYLON || (BABYLON = {}));
  46144. //# sourceMappingURL=babylon.shaderMaterial.js.map
  46145. var BABYLON;
  46146. (function (BABYLON) {
  46147. var MeshBuilder = /** @class */ (function () {
  46148. function MeshBuilder() {
  46149. }
  46150. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  46151. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  46152. return BABYLON.Mesh.DOUBLESIDE;
  46153. }
  46154. if (orientation === undefined || orientation === null) {
  46155. return BABYLON.Mesh.FRONTSIDE;
  46156. }
  46157. return orientation;
  46158. };
  46159. /**
  46160. * Creates a box mesh.
  46161. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  46162. * The parameter `size` sets the size (float) of each box side (default 1).
  46163. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  46164. * 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).
  46165. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  46166. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46167. * 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).
  46168. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46169. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46170. */
  46171. MeshBuilder.CreateBox = function (name, options, scene) {
  46172. var box = new BABYLON.Mesh(name, scene);
  46173. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  46174. box._originalBuilderSideOrientation = options.sideOrientation;
  46175. var vertexData = BABYLON.VertexData.CreateBox(options);
  46176. vertexData.applyToMesh(box, options.updatable);
  46177. return box;
  46178. };
  46179. /**
  46180. * Creates a sphere mesh.
  46181. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  46182. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  46183. * 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`).
  46184. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  46185. * 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
  46186. * 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).
  46187. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46188. * 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).
  46189. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46190. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46191. */
  46192. MeshBuilder.CreateSphere = function (name, options, scene) {
  46193. var sphere = new BABYLON.Mesh(name, scene);
  46194. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  46195. sphere._originalBuilderSideOrientation = options.sideOrientation;
  46196. var vertexData = BABYLON.VertexData.CreateSphere(options);
  46197. vertexData.applyToMesh(sphere, options.updatable);
  46198. return sphere;
  46199. };
  46200. /**
  46201. * Creates a plane polygonal mesh. By default, this is a disc.
  46202. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  46203. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  46204. * 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.
  46205. * 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
  46206. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46207. * 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).
  46208. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46209. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46210. */
  46211. MeshBuilder.CreateDisc = function (name, options, scene) {
  46212. var disc = new BABYLON.Mesh(name, scene);
  46213. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  46214. disc._originalBuilderSideOrientation = options.sideOrientation;
  46215. var vertexData = BABYLON.VertexData.CreateDisc(options);
  46216. vertexData.applyToMesh(disc, options.updatable);
  46217. return disc;
  46218. };
  46219. /**
  46220. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  46221. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  46222. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  46223. * 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`).
  46224. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  46225. * 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.
  46226. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46227. * 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).
  46228. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46229. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46230. */
  46231. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  46232. var sphere = new BABYLON.Mesh(name, scene);
  46233. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  46234. sphere._originalBuilderSideOrientation = options.sideOrientation;
  46235. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  46236. vertexData.applyToMesh(sphere, options.updatable);
  46237. return sphere;
  46238. };
  46239. ;
  46240. /**
  46241. * Creates a ribbon mesh.
  46242. * 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.
  46243. *
  46244. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  46245. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  46246. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  46247. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  46248. * 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.
  46249. * 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.
  46250. * 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
  46251. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46252. * 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).
  46253. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46254. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  46255. * 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.
  46256. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  46257. * 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
  46258. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  46259. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  46260. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46261. */
  46262. MeshBuilder.CreateRibbon = function (name, options, scene) {
  46263. var pathArray = options.pathArray;
  46264. var closeArray = options.closeArray;
  46265. var closePath = options.closePath;
  46266. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  46267. var instance = options.instance;
  46268. var updatable = options.updatable;
  46269. if (instance) {
  46270. // positionFunction : ribbon case
  46271. // only pathArray and sideOrientation parameters are taken into account for positions update
  46272. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  46273. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  46274. var positionFunction = function (positions) {
  46275. var minlg = pathArray[0].length;
  46276. var i = 0;
  46277. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  46278. for (var si = 1; si <= ns; si++) {
  46279. for (var p = 0; p < pathArray.length; p++) {
  46280. var path = pathArray[p];
  46281. var l = path.length;
  46282. minlg = (minlg < l) ? minlg : l;
  46283. var j = 0;
  46284. while (j < minlg) {
  46285. positions[i] = path[j].x;
  46286. positions[i + 1] = path[j].y;
  46287. positions[i + 2] = path[j].z;
  46288. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  46289. BABYLON.Tmp.Vector3[0].x = path[j].x;
  46290. }
  46291. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  46292. BABYLON.Tmp.Vector3[1].x = path[j].x;
  46293. }
  46294. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  46295. BABYLON.Tmp.Vector3[0].y = path[j].y;
  46296. }
  46297. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  46298. BABYLON.Tmp.Vector3[1].y = path[j].y;
  46299. }
  46300. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  46301. BABYLON.Tmp.Vector3[0].z = path[j].z;
  46302. }
  46303. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  46304. BABYLON.Tmp.Vector3[1].z = path[j].z;
  46305. }
  46306. j++;
  46307. i += 3;
  46308. }
  46309. if (instance._closePath) {
  46310. positions[i] = path[0].x;
  46311. positions[i + 1] = path[0].y;
  46312. positions[i + 2] = path[0].z;
  46313. i += 3;
  46314. }
  46315. }
  46316. }
  46317. };
  46318. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46319. positionFunction(positions);
  46320. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  46321. instance._boundingInfo.update(instance._worldMatrix);
  46322. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  46323. if (options.colors) {
  46324. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  46325. for (var c = 0; c < options.colors.length; c++) {
  46326. colors[c * 4] = options.colors[c].r;
  46327. colors[c * 4 + 1] = options.colors[c].g;
  46328. colors[c * 4 + 2] = options.colors[c].b;
  46329. colors[c * 4 + 3] = options.colors[c].a;
  46330. }
  46331. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  46332. }
  46333. if (options.uvs) {
  46334. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  46335. for (var i = 0; i < options.uvs.length; i++) {
  46336. uvs[i * 2] = options.uvs[i].x;
  46337. uvs[i * 2 + 1] = options.uvs[i].y;
  46338. }
  46339. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  46340. }
  46341. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  46342. var indices = instance.getIndices();
  46343. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  46344. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  46345. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  46346. if (instance._closePath) {
  46347. var indexFirst = 0;
  46348. var indexLast = 0;
  46349. for (var p = 0; p < pathArray.length; p++) {
  46350. indexFirst = instance._idx[p] * 3;
  46351. if (p + 1 < pathArray.length) {
  46352. indexLast = (instance._idx[p + 1] - 1) * 3;
  46353. }
  46354. else {
  46355. indexLast = normals.length - 3;
  46356. }
  46357. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  46358. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  46359. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  46360. normals[indexLast] = normals[indexFirst];
  46361. normals[indexLast + 1] = normals[indexFirst + 1];
  46362. normals[indexLast + 2] = normals[indexFirst + 2];
  46363. }
  46364. }
  46365. if (!(instance.areNormalsFrozen)) {
  46366. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  46367. }
  46368. }
  46369. return instance;
  46370. }
  46371. else {
  46372. var ribbon = new BABYLON.Mesh(name, scene);
  46373. ribbon._originalBuilderSideOrientation = sideOrientation;
  46374. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  46375. if (closePath) {
  46376. ribbon._idx = vertexData._idx;
  46377. }
  46378. ribbon._closePath = closePath;
  46379. ribbon._closeArray = closeArray;
  46380. vertexData.applyToMesh(ribbon, updatable);
  46381. return ribbon;
  46382. }
  46383. };
  46384. /**
  46385. * Creates a cylinder or a cone mesh.
  46386. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  46387. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  46388. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  46389. * 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.
  46390. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  46391. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  46392. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  46393. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  46394. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  46395. * 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).
  46396. * 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
  46397. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  46398. * 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
  46399. * 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.
  46400. * If `enclose` is false, a ring surface is one element.
  46401. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  46402. * 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
  46403. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46404. * 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).
  46405. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46406. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46407. */
  46408. MeshBuilder.CreateCylinder = function (name, options, scene) {
  46409. var cylinder = new BABYLON.Mesh(name, scene);
  46410. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  46411. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  46412. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  46413. vertexData.applyToMesh(cylinder, options.updatable);
  46414. return cylinder;
  46415. };
  46416. /**
  46417. * Creates a torus mesh.
  46418. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  46419. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  46420. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  46421. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  46422. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46423. * 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).
  46424. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46425. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46426. */
  46427. MeshBuilder.CreateTorus = function (name, options, scene) {
  46428. var torus = new BABYLON.Mesh(name, scene);
  46429. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  46430. torus._originalBuilderSideOrientation = options.sideOrientation;
  46431. var vertexData = BABYLON.VertexData.CreateTorus(options);
  46432. vertexData.applyToMesh(torus, options.updatable);
  46433. return torus;
  46434. };
  46435. /**
  46436. * Creates a torus knot mesh.
  46437. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  46438. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  46439. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  46440. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  46441. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  46442. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46443. * 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).
  46444. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46445. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46446. */
  46447. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  46448. var torusKnot = new BABYLON.Mesh(name, scene);
  46449. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  46450. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  46451. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  46452. vertexData.applyToMesh(torusKnot, options.updatable);
  46453. return torusKnot;
  46454. };
  46455. /**
  46456. * Creates a line system mesh.
  46457. * A line system is a pool of many lines gathered in a single mesh.
  46458. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  46459. * 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.
  46460. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  46461. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  46462. * 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
  46463. * 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
  46464. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  46465. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46466. */
  46467. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  46468. var instance = options.instance;
  46469. var lines = options.lines;
  46470. if (instance) {
  46471. var positionFunction = function (positions) {
  46472. var i = 0;
  46473. for (var l = 0; l < lines.length; l++) {
  46474. var points = lines[l];
  46475. for (var p = 0; p < points.length; p++) {
  46476. positions[i] = points[p].x;
  46477. positions[i + 1] = points[p].y;
  46478. positions[i + 2] = points[p].z;
  46479. i += 3;
  46480. }
  46481. }
  46482. };
  46483. instance.updateMeshPositions(positionFunction, false);
  46484. return instance;
  46485. }
  46486. // line system creation
  46487. var lineSystem = new BABYLON.LinesMesh(name, scene);
  46488. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  46489. vertexData.applyToMesh(lineSystem, options.updatable);
  46490. return lineSystem;
  46491. };
  46492. /**
  46493. * Creates a line mesh.
  46494. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  46495. * 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.
  46496. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  46497. * The parameter `points` is an array successive Vector3.
  46498. * 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
  46499. * When updating an instance, remember that only point positions can change, not the number of points.
  46500. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46501. */
  46502. MeshBuilder.CreateLines = function (name, options, scene) {
  46503. if (scene === void 0) { scene = null; }
  46504. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  46505. return lines;
  46506. };
  46507. /**
  46508. * Creates a dashed line mesh.
  46509. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  46510. * 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.
  46511. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  46512. * The parameter `points` is an array successive Vector3.
  46513. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  46514. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  46515. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  46516. * 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
  46517. * When updating an instance, remember that only point positions can change, not the number of points.
  46518. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46519. */
  46520. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  46521. var points = options.points;
  46522. var instance = options.instance;
  46523. var gapSize = options.gapSize || 1;
  46524. var dashSize = options.dashSize || 3;
  46525. if (instance) {
  46526. var positionFunction = function (positions) {
  46527. var curvect = BABYLON.Vector3.Zero();
  46528. var nbSeg = positions.length / 6;
  46529. var lg = 0;
  46530. var nb = 0;
  46531. var shft = 0;
  46532. var dashshft = 0;
  46533. var curshft = 0;
  46534. var p = 0;
  46535. var i = 0;
  46536. var j = 0;
  46537. for (i = 0; i < points.length - 1; i++) {
  46538. points[i + 1].subtractToRef(points[i], curvect);
  46539. lg += curvect.length();
  46540. }
  46541. shft = lg / nbSeg;
  46542. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  46543. for (i = 0; i < points.length - 1; i++) {
  46544. points[i + 1].subtractToRef(points[i], curvect);
  46545. nb = Math.floor(curvect.length() / shft);
  46546. curvect.normalize();
  46547. j = 0;
  46548. while (j < nb && p < positions.length) {
  46549. curshft = shft * j;
  46550. positions[p] = points[i].x + curshft * curvect.x;
  46551. positions[p + 1] = points[i].y + curshft * curvect.y;
  46552. positions[p + 2] = points[i].z + curshft * curvect.z;
  46553. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  46554. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  46555. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  46556. p += 6;
  46557. j++;
  46558. }
  46559. }
  46560. while (p < positions.length) {
  46561. positions[p] = points[i].x;
  46562. positions[p + 1] = points[i].y;
  46563. positions[p + 2] = points[i].z;
  46564. p += 3;
  46565. }
  46566. };
  46567. instance.updateMeshPositions(positionFunction, false);
  46568. return instance;
  46569. }
  46570. // dashed lines creation
  46571. var dashedLines = new BABYLON.LinesMesh(name, scene);
  46572. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  46573. vertexData.applyToMesh(dashedLines, options.updatable);
  46574. dashedLines.dashSize = dashSize;
  46575. dashedLines.gapSize = gapSize;
  46576. return dashedLines;
  46577. };
  46578. /**
  46579. * Creates an extruded shape mesh.
  46580. * 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.
  46581. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  46582. *
  46583. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  46584. * 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
  46585. * extruded along the Z axis.
  46586. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  46587. * 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.
  46588. * The parameter `scale` (float, default 1) is the value to scale the shape.
  46589. * 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
  46590. * 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
  46591. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  46592. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46593. * 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).
  46594. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46595. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  46596. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46597. */
  46598. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  46599. var path = options.path;
  46600. var shape = options.shape;
  46601. var scale = options.scale || 1;
  46602. var rotation = options.rotation || 0;
  46603. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  46604. var updatable = options.updatable;
  46605. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  46606. var instance = options.instance;
  46607. var invertUV = options.invertUV || false;
  46608. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  46609. };
  46610. /**
  46611. * Creates an custom extruded shape mesh.
  46612. * 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.
  46613. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  46614. *
  46615. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  46616. * 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
  46617. * extruded along the Z axis.
  46618. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  46619. * 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
  46620. * and the distance of this point from the begining of the path :
  46621. * ```javascript
  46622. * var rotationFunction = function(i, distance) {
  46623. * // do things
  46624. * return rotationValue; }
  46625. * ```
  46626. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  46627. * 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
  46628. * and the distance of this point from the begining of the path :
  46629. * ```javascript
  46630. * var scaleFunction = function(i, distance) {
  46631. * // do things
  46632. * return scaleValue;}
  46633. * ```
  46634. * It must returns a float value that will be the scale value applied to the shape on each path point.
  46635. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  46636. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  46637. * 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
  46638. * 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
  46639. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  46640. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46641. * 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).
  46642. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46643. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  46644. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46645. */
  46646. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  46647. var path = options.path;
  46648. var shape = options.shape;
  46649. var scaleFunction = options.scaleFunction || (function () { return 1; });
  46650. var rotationFunction = options.rotationFunction || (function () { return 0; });
  46651. var ribbonCloseArray = options.ribbonCloseArray || false;
  46652. var ribbonClosePath = options.ribbonClosePath || false;
  46653. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  46654. var updatable = options.updatable;
  46655. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  46656. var instance = options.instance;
  46657. var invertUV = options.invertUV || false;
  46658. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  46659. };
  46660. /**
  46661. * Creates lathe mesh.
  46662. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  46663. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  46664. *
  46665. * 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
  46666. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  46667. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  46668. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  46669. * 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.
  46670. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  46671. * 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
  46672. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46673. * 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).
  46674. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46675. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  46676. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46677. */
  46678. MeshBuilder.CreateLathe = function (name, options, scene) {
  46679. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  46680. var closed = (options.closed === undefined) ? true : options.closed;
  46681. var shape = options.shape;
  46682. var radius = options.radius || 1;
  46683. var tessellation = options.tessellation || 64;
  46684. var updatable = options.updatable;
  46685. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  46686. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  46687. var pi2 = Math.PI * 2;
  46688. var paths = new Array();
  46689. var invertUV = options.invertUV || false;
  46690. var i = 0;
  46691. var p = 0;
  46692. var step = pi2 / tessellation * arc;
  46693. var rotated;
  46694. var path = new Array();
  46695. ;
  46696. for (i = 0; i <= tessellation; i++) {
  46697. var path = [];
  46698. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  46699. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  46700. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  46701. }
  46702. for (p = 0; p < shape.length; p++) {
  46703. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  46704. path.push(rotated);
  46705. }
  46706. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  46707. 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));
  46708. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  46709. }
  46710. paths.push(path);
  46711. }
  46712. // lathe ribbon
  46713. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  46714. return lathe;
  46715. };
  46716. /**
  46717. * Creates a plane mesh.
  46718. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  46719. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  46720. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  46721. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  46722. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46723. * 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).
  46724. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46725. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46726. */
  46727. MeshBuilder.CreatePlane = function (name, options, scene) {
  46728. var plane = new BABYLON.Mesh(name, scene);
  46729. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  46730. plane._originalBuilderSideOrientation = options.sideOrientation;
  46731. var vertexData = BABYLON.VertexData.CreatePlane(options);
  46732. vertexData.applyToMesh(plane, options.updatable);
  46733. if (options.sourcePlane) {
  46734. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  46735. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  46736. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  46737. plane.rotate(vectorProduct, product);
  46738. }
  46739. return plane;
  46740. };
  46741. /**
  46742. * Creates a ground mesh.
  46743. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  46744. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  46745. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  46746. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46747. */
  46748. MeshBuilder.CreateGround = function (name, options, scene) {
  46749. var ground = new BABYLON.GroundMesh(name, scene);
  46750. ground._setReady(false);
  46751. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  46752. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  46753. ground._width = options.width || 1;
  46754. ground._height = options.height || 1;
  46755. ground._maxX = ground._width / 2;
  46756. ground._maxZ = ground._height / 2;
  46757. ground._minX = -ground._maxX;
  46758. ground._minZ = -ground._maxZ;
  46759. var vertexData = BABYLON.VertexData.CreateGround(options);
  46760. vertexData.applyToMesh(ground, options.updatable);
  46761. ground._setReady(true);
  46762. return ground;
  46763. };
  46764. /**
  46765. * Creates a tiled ground mesh.
  46766. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  46767. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  46768. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  46769. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  46770. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  46771. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  46772. * numbers of subdivisions on the ground width and height of each tile.
  46773. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46774. */
  46775. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  46776. var tiledGround = new BABYLON.Mesh(name, scene);
  46777. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  46778. vertexData.applyToMesh(tiledGround, options.updatable);
  46779. return tiledGround;
  46780. };
  46781. /**
  46782. * Creates a ground mesh from a height map.
  46783. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  46784. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  46785. * The parameter `url` sets the URL of the height map image resource.
  46786. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  46787. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  46788. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  46789. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  46790. * 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.
  46791. * 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).
  46792. * This function is passed the newly built mesh :
  46793. * ```javascript
  46794. * function(mesh) { // do things
  46795. * return; }
  46796. * ```
  46797. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46798. */
  46799. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  46800. var width = options.width || 10.0;
  46801. var height = options.height || 10.0;
  46802. var subdivisions = options.subdivisions || 1 | 0;
  46803. var minHeight = options.minHeight || 0.0;
  46804. var maxHeight = options.maxHeight || 1.0;
  46805. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  46806. var updatable = options.updatable;
  46807. var onReady = options.onReady;
  46808. var ground = new BABYLON.GroundMesh(name, scene);
  46809. ground._subdivisionsX = subdivisions;
  46810. ground._subdivisionsY = subdivisions;
  46811. ground._width = width;
  46812. ground._height = height;
  46813. ground._maxX = ground._width / 2.0;
  46814. ground._maxZ = ground._height / 2.0;
  46815. ground._minX = -ground._maxX;
  46816. ground._minZ = -ground._maxZ;
  46817. ground._setReady(false);
  46818. var onload = function (img) {
  46819. // Getting height map data
  46820. var canvas = document.createElement("canvas");
  46821. var context = canvas.getContext("2d");
  46822. var bufferWidth = img.width;
  46823. var bufferHeight = img.height;
  46824. canvas.width = bufferWidth;
  46825. canvas.height = bufferHeight;
  46826. context.drawImage(img, 0, 0);
  46827. // Create VertexData from map data
  46828. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  46829. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  46830. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  46831. width: width, height: height,
  46832. subdivisions: subdivisions,
  46833. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  46834. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  46835. });
  46836. vertexData.applyToMesh(ground, updatable);
  46837. ground._setReady(true);
  46838. //execute ready callback, if set
  46839. if (onReady) {
  46840. onReady(ground);
  46841. }
  46842. };
  46843. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  46844. return ground;
  46845. };
  46846. /**
  46847. * Creates a polygon mesh.
  46848. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  46849. * 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.
  46850. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46851. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46852. * 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).
  46853. * Remember you can only change the shape positions, not their number when updating a polygon.
  46854. */
  46855. MeshBuilder.CreatePolygon = function (name, options, scene) {
  46856. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  46857. var shape = options.shape;
  46858. var holes = options.holes || [];
  46859. var depth = options.depth || 0;
  46860. var contours = [];
  46861. var hole = [];
  46862. for (var i = 0; i < shape.length; i++) {
  46863. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  46864. }
  46865. var epsilon = 0.00000001;
  46866. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  46867. contours.pop();
  46868. }
  46869. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  46870. for (var hNb = 0; hNb < holes.length; hNb++) {
  46871. hole = [];
  46872. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  46873. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  46874. }
  46875. polygonTriangulation.addHole(hole);
  46876. }
  46877. var polygon = polygonTriangulation.build(options.updatable, depth);
  46878. polygon._originalBuilderSideOrientation = options.sideOrientation;
  46879. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  46880. vertexData.applyToMesh(polygon, options.updatable);
  46881. return polygon;
  46882. };
  46883. ;
  46884. /**
  46885. * Creates an extruded polygon mesh, with depth in the Y direction.
  46886. * 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).
  46887. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  46888. */
  46889. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  46890. return MeshBuilder.CreatePolygon(name, options, scene);
  46891. };
  46892. ;
  46893. /**
  46894. * Creates a tube mesh.
  46895. * 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.
  46896. *
  46897. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  46898. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  46899. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  46900. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  46901. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  46902. * 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.
  46903. * It must return a radius value (positive float) :
  46904. * ```javascript
  46905. * var radiusFunction = function(i, distance) {
  46906. * // do things
  46907. * return radius; }
  46908. * ```
  46909. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  46910. * 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
  46911. * 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
  46912. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46913. * 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).
  46914. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46915. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  46916. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46917. */
  46918. MeshBuilder.CreateTube = function (name, options, scene) {
  46919. var path = options.path;
  46920. var instance = options.instance;
  46921. var radius = 1.0;
  46922. if (instance) {
  46923. radius = instance.radius;
  46924. }
  46925. if (options.radius !== undefined) {
  46926. radius = options.radius;
  46927. }
  46928. ;
  46929. var tessellation = options.tessellation || 64 | 0;
  46930. var radiusFunction = options.radiusFunction;
  46931. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  46932. var invertUV = options.invertUV || false;
  46933. var updatable = options.updatable;
  46934. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  46935. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  46936. // tube geometry
  46937. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  46938. var tangents = path3D.getTangents();
  46939. var normals = path3D.getNormals();
  46940. var distances = path3D.getDistances();
  46941. var pi2 = Math.PI * 2;
  46942. var step = pi2 / tessellation * arc;
  46943. var returnRadius = function () { return radius; };
  46944. var radiusFunctionFinal = radiusFunction || returnRadius;
  46945. var circlePath;
  46946. var rad;
  46947. var normal;
  46948. var rotated;
  46949. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  46950. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  46951. for (var i = 0; i < path.length; i++) {
  46952. rad = radiusFunctionFinal(i, distances[i]); // current radius
  46953. circlePath = Array(); // current circle array
  46954. normal = normals[i]; // current normal
  46955. for (var t = 0; t < tessellation; t++) {
  46956. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  46957. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  46958. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  46959. rotated.scaleInPlace(rad).addInPlace(path[i]);
  46960. circlePath[t] = rotated;
  46961. }
  46962. circlePaths[index] = circlePath;
  46963. index++;
  46964. }
  46965. // cap
  46966. var capPath = function (nbPoints, pathIndex) {
  46967. var pointCap = Array();
  46968. for (var i = 0; i < nbPoints; i++) {
  46969. pointCap.push(path[pathIndex]);
  46970. }
  46971. return pointCap;
  46972. };
  46973. switch (cap) {
  46974. case BABYLON.Mesh.NO_CAP:
  46975. break;
  46976. case BABYLON.Mesh.CAP_START:
  46977. circlePaths[0] = capPath(tessellation, 0);
  46978. circlePaths[1] = circlePaths[2].slice(0);
  46979. break;
  46980. case BABYLON.Mesh.CAP_END:
  46981. circlePaths[index] = circlePaths[index - 1].slice(0);
  46982. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  46983. break;
  46984. case BABYLON.Mesh.CAP_ALL:
  46985. circlePaths[0] = capPath(tessellation, 0);
  46986. circlePaths[1] = circlePaths[2].slice(0);
  46987. circlePaths[index] = circlePaths[index - 1].slice(0);
  46988. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  46989. break;
  46990. default:
  46991. break;
  46992. }
  46993. return circlePaths;
  46994. };
  46995. var path3D;
  46996. var pathArray;
  46997. if (instance) {
  46998. var arc = options.arc || instance.arc;
  46999. path3D = (instance.path3D).update(path);
  47000. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  47001. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  47002. instance.path3D = path3D;
  47003. instance.pathArray = pathArray;
  47004. instance.arc = arc;
  47005. instance.radius = radius;
  47006. return instance;
  47007. }
  47008. // tube creation
  47009. path3D = new BABYLON.Path3D(path);
  47010. var newPathArray = new Array();
  47011. cap = (cap < 0 || cap > 3) ? 0 : cap;
  47012. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  47013. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  47014. tube.pathArray = pathArray;
  47015. tube.path3D = path3D;
  47016. tube.tessellation = tessellation;
  47017. tube.cap = cap;
  47018. tube.arc = options.arc;
  47019. tube.radius = radius;
  47020. return tube;
  47021. };
  47022. /**
  47023. * Creates a polyhedron mesh.
  47024. *
  47025. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  47026. * 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
  47027. * to choose the wanted type.
  47028. * The parameter `size` (positive float, default 1) sets the polygon size.
  47029. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  47030. * 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`.
  47031. * 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
  47032. * 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)`).
  47033. * 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
  47034. * 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.
  47035. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47036. * 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).
  47037. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47038. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47039. */
  47040. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  47041. var polyhedron = new BABYLON.Mesh(name, scene);
  47042. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  47043. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  47044. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  47045. vertexData.applyToMesh(polyhedron, options.updatable);
  47046. return polyhedron;
  47047. };
  47048. /**
  47049. * Creates a decal mesh.
  47050. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  47051. * 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.
  47052. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  47053. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  47054. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  47055. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  47056. */
  47057. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  47058. var indices = sourceMesh.getIndices();
  47059. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47060. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47061. var position = options.position || BABYLON.Vector3.Zero();
  47062. var normal = options.normal || BABYLON.Vector3.Up();
  47063. var size = options.size || BABYLON.Vector3.One();
  47064. var angle = options.angle || 0;
  47065. // Getting correct rotation
  47066. if (!normal) {
  47067. var target = new BABYLON.Vector3(0, 0, 1);
  47068. var camera = sourceMesh.getScene().activeCamera;
  47069. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  47070. normal = camera.globalPosition.subtract(cameraWorldTarget);
  47071. }
  47072. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  47073. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  47074. var pitch = Math.atan2(normal.y, len);
  47075. // Matrix
  47076. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  47077. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  47078. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  47079. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  47080. var vertexData = new BABYLON.VertexData();
  47081. vertexData.indices = [];
  47082. vertexData.positions = [];
  47083. vertexData.normals = [];
  47084. vertexData.uvs = [];
  47085. var currentVertexDataIndex = 0;
  47086. var extractDecalVector3 = function (indexId) {
  47087. var vertexId = indices[indexId];
  47088. var result = new BABYLON.PositionNormalVertex();
  47089. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  47090. // Send vector to decal local world
  47091. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  47092. // Get normal
  47093. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  47094. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  47095. return result;
  47096. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  47097. var clip = function (vertices, axis) {
  47098. if (vertices.length === 0) {
  47099. return vertices;
  47100. }
  47101. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  47102. var clipVertices = function (v0, v1) {
  47103. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  47104. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  47105. };
  47106. var result = new Array();
  47107. for (var index = 0; index < vertices.length; index += 3) {
  47108. var v1Out;
  47109. var v2Out;
  47110. var v3Out;
  47111. var total = 0;
  47112. var nV1, nV2, nV3, nV4;
  47113. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  47114. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  47115. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  47116. v1Out = d1 > 0;
  47117. v2Out = d2 > 0;
  47118. v3Out = d3 > 0;
  47119. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  47120. switch (total) {
  47121. case 0:
  47122. result.push(vertices[index]);
  47123. result.push(vertices[index + 1]);
  47124. result.push(vertices[index + 2]);
  47125. break;
  47126. case 1:
  47127. if (v1Out) {
  47128. nV1 = vertices[index + 1];
  47129. nV2 = vertices[index + 2];
  47130. nV3 = clipVertices(vertices[index], nV1);
  47131. nV4 = clipVertices(vertices[index], nV2);
  47132. }
  47133. if (v2Out) {
  47134. nV1 = vertices[index];
  47135. nV2 = vertices[index + 2];
  47136. nV3 = clipVertices(vertices[index + 1], nV1);
  47137. nV4 = clipVertices(vertices[index + 1], nV2);
  47138. result.push(nV3);
  47139. result.push(nV2.clone());
  47140. result.push(nV1.clone());
  47141. result.push(nV2.clone());
  47142. result.push(nV3.clone());
  47143. result.push(nV4);
  47144. break;
  47145. }
  47146. if (v3Out) {
  47147. nV1 = vertices[index];
  47148. nV2 = vertices[index + 1];
  47149. nV3 = clipVertices(vertices[index + 2], nV1);
  47150. nV4 = clipVertices(vertices[index + 2], nV2);
  47151. }
  47152. result.push(nV1.clone());
  47153. result.push(nV2.clone());
  47154. result.push(nV3);
  47155. result.push(nV4);
  47156. result.push(nV3.clone());
  47157. result.push(nV2.clone());
  47158. break;
  47159. case 2:
  47160. if (!v1Out) {
  47161. nV1 = vertices[index].clone();
  47162. nV2 = clipVertices(nV1, vertices[index + 1]);
  47163. nV3 = clipVertices(nV1, vertices[index + 2]);
  47164. result.push(nV1);
  47165. result.push(nV2);
  47166. result.push(nV3);
  47167. }
  47168. if (!v2Out) {
  47169. nV1 = vertices[index + 1].clone();
  47170. nV2 = clipVertices(nV1, vertices[index + 2]);
  47171. nV3 = clipVertices(nV1, vertices[index]);
  47172. result.push(nV1);
  47173. result.push(nV2);
  47174. result.push(nV3);
  47175. }
  47176. if (!v3Out) {
  47177. nV1 = vertices[index + 2].clone();
  47178. nV2 = clipVertices(nV1, vertices[index]);
  47179. nV3 = clipVertices(nV1, vertices[index + 1]);
  47180. result.push(nV1);
  47181. result.push(nV2);
  47182. result.push(nV3);
  47183. }
  47184. break;
  47185. case 3:
  47186. break;
  47187. }
  47188. }
  47189. return result;
  47190. };
  47191. for (var index = 0; index < indices.length; index += 3) {
  47192. var faceVertices = new Array();
  47193. faceVertices.push(extractDecalVector3(index));
  47194. faceVertices.push(extractDecalVector3(index + 1));
  47195. faceVertices.push(extractDecalVector3(index + 2));
  47196. // Clip
  47197. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  47198. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  47199. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  47200. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  47201. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  47202. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  47203. if (faceVertices.length === 0) {
  47204. continue;
  47205. }
  47206. // Add UVs and get back to world
  47207. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  47208. var vertex = faceVertices[vIndex];
  47209. //TODO check for Int32Array | Uint32Array | Uint16Array
  47210. vertexData.indices.push(currentVertexDataIndex);
  47211. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  47212. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  47213. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  47214. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  47215. currentVertexDataIndex++;
  47216. }
  47217. }
  47218. // Return mesh
  47219. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  47220. vertexData.applyToMesh(decal);
  47221. decal.position = position.clone();
  47222. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  47223. return decal;
  47224. };
  47225. // Privates
  47226. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  47227. // extrusion geometry
  47228. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  47229. var tangents = path3D.getTangents();
  47230. var normals = path3D.getNormals();
  47231. var binormals = path3D.getBinormals();
  47232. var distances = path3D.getDistances();
  47233. var angle = 0;
  47234. var returnScale = function () { return scale; };
  47235. var returnRotation = function () { return rotation; };
  47236. var rotate = custom ? rotateFunction : returnRotation;
  47237. var scl = custom ? scaleFunction : returnScale;
  47238. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  47239. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  47240. for (var i = 0; i < curve.length; i++) {
  47241. var shapePath = new Array();
  47242. var angleStep = rotate(i, distances[i]);
  47243. var scaleRatio = scl(i, distances[i]);
  47244. for (var p = 0; p < shape.length; p++) {
  47245. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  47246. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  47247. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  47248. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  47249. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  47250. shapePath[p] = rotated;
  47251. }
  47252. shapePaths[index] = shapePath;
  47253. angle += angleStep;
  47254. index++;
  47255. }
  47256. // cap
  47257. var capPath = function (shapePath) {
  47258. var pointCap = Array();
  47259. var barycenter = BABYLON.Vector3.Zero();
  47260. var i;
  47261. for (i = 0; i < shapePath.length; i++) {
  47262. barycenter.addInPlace(shapePath[i]);
  47263. }
  47264. barycenter.scaleInPlace(1.0 / shapePath.length);
  47265. for (i = 0; i < shapePath.length; i++) {
  47266. pointCap.push(barycenter);
  47267. }
  47268. return pointCap;
  47269. };
  47270. switch (cap) {
  47271. case BABYLON.Mesh.NO_CAP:
  47272. break;
  47273. case BABYLON.Mesh.CAP_START:
  47274. shapePaths[0] = capPath(shapePaths[2]);
  47275. shapePaths[1] = shapePaths[2];
  47276. break;
  47277. case BABYLON.Mesh.CAP_END:
  47278. shapePaths[index] = shapePaths[index - 1];
  47279. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  47280. break;
  47281. case BABYLON.Mesh.CAP_ALL:
  47282. shapePaths[0] = capPath(shapePaths[2]);
  47283. shapePaths[1] = shapePaths[2];
  47284. shapePaths[index] = shapePaths[index - 1];
  47285. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  47286. break;
  47287. default:
  47288. break;
  47289. }
  47290. return shapePaths;
  47291. };
  47292. var path3D;
  47293. var pathArray;
  47294. if (instance) {
  47295. path3D = (instance.path3D).update(curve);
  47296. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  47297. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  47298. return instance;
  47299. }
  47300. // extruded shape creation
  47301. path3D = new BABYLON.Path3D(curve);
  47302. var newShapePaths = new Array();
  47303. cap = (cap < 0 || cap > 3) ? 0 : cap;
  47304. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  47305. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  47306. extrudedGeneric.pathArray = pathArray;
  47307. extrudedGeneric.path3D = path3D;
  47308. extrudedGeneric.cap = cap;
  47309. return extrudedGeneric;
  47310. };
  47311. return MeshBuilder;
  47312. }());
  47313. BABYLON.MeshBuilder = MeshBuilder;
  47314. })(BABYLON || (BABYLON = {}));
  47315. //# sourceMappingURL=babylon.meshBuilder.js.map
  47316. var BABYLON;
  47317. (function (BABYLON) {
  47318. var AudioEngine = /** @class */ (function () {
  47319. function AudioEngine() {
  47320. this._audioContext = null;
  47321. this._audioContextInitialized = false;
  47322. this.canUseWebAudio = false;
  47323. this.WarnedWebAudioUnsupported = false;
  47324. this.unlocked = false;
  47325. this.isMP3supported = false;
  47326. this.isOGGsupported = false;
  47327. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  47328. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  47329. this.canUseWebAudio = true;
  47330. }
  47331. var audioElem = document.createElement('audio');
  47332. try {
  47333. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  47334. this.isMP3supported = true;
  47335. }
  47336. }
  47337. catch (e) {
  47338. // protect error during capability check.
  47339. }
  47340. try {
  47341. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  47342. this.isOGGsupported = true;
  47343. }
  47344. }
  47345. catch (e) {
  47346. // protect error during capability check.
  47347. }
  47348. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  47349. this._unlockiOSaudio();
  47350. }
  47351. else {
  47352. this.unlocked = true;
  47353. }
  47354. }
  47355. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  47356. get: function () {
  47357. if (!this._audioContextInitialized) {
  47358. this._initializeAudioContext();
  47359. }
  47360. return this._audioContext;
  47361. },
  47362. enumerable: true,
  47363. configurable: true
  47364. });
  47365. AudioEngine.prototype._unlockiOSaudio = function () {
  47366. var _this = this;
  47367. var unlockaudio = function () {
  47368. if (!_this.audioContext) {
  47369. return;
  47370. }
  47371. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  47372. var source = _this.audioContext.createBufferSource();
  47373. source.buffer = buffer;
  47374. source.connect(_this.audioContext.destination);
  47375. source.start(0);
  47376. setTimeout(function () {
  47377. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  47378. _this.unlocked = true;
  47379. window.removeEventListener('touchend', unlockaudio, false);
  47380. if (_this.onAudioUnlocked) {
  47381. _this.onAudioUnlocked();
  47382. }
  47383. }
  47384. }, 0);
  47385. };
  47386. window.addEventListener('touchend', unlockaudio, false);
  47387. };
  47388. AudioEngine.prototype._initializeAudioContext = function () {
  47389. try {
  47390. if (this.canUseWebAudio) {
  47391. this._audioContext = new AudioContext();
  47392. // create a global volume gain node
  47393. this.masterGain = this._audioContext.createGain();
  47394. this.masterGain.gain.value = 1;
  47395. this.masterGain.connect(this._audioContext.destination);
  47396. this._audioContextInitialized = true;
  47397. }
  47398. }
  47399. catch (e) {
  47400. this.canUseWebAudio = false;
  47401. BABYLON.Tools.Error("Web Audio: " + e.message);
  47402. }
  47403. };
  47404. AudioEngine.prototype.dispose = function () {
  47405. if (this.canUseWebAudio && this._audioContextInitialized) {
  47406. if (this._connectedAnalyser && this._audioContext) {
  47407. this._connectedAnalyser.stopDebugCanvas();
  47408. this._connectedAnalyser.dispose();
  47409. this.masterGain.disconnect();
  47410. this.masterGain.connect(this._audioContext.destination);
  47411. this._connectedAnalyser = null;
  47412. }
  47413. this.masterGain.gain.value = 1;
  47414. }
  47415. this.WarnedWebAudioUnsupported = false;
  47416. };
  47417. AudioEngine.prototype.getGlobalVolume = function () {
  47418. if (this.canUseWebAudio && this._audioContextInitialized) {
  47419. return this.masterGain.gain.value;
  47420. }
  47421. else {
  47422. return -1;
  47423. }
  47424. };
  47425. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  47426. if (this.canUseWebAudio && this._audioContextInitialized) {
  47427. this.masterGain.gain.value = newVolume;
  47428. }
  47429. };
  47430. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  47431. if (this._connectedAnalyser) {
  47432. this._connectedAnalyser.stopDebugCanvas();
  47433. }
  47434. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  47435. this._connectedAnalyser = analyser;
  47436. this.masterGain.disconnect();
  47437. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  47438. }
  47439. };
  47440. return AudioEngine;
  47441. }());
  47442. BABYLON.AudioEngine = AudioEngine;
  47443. })(BABYLON || (BABYLON = {}));
  47444. //# sourceMappingURL=babylon.audioEngine.js.map
  47445. var BABYLON;
  47446. (function (BABYLON) {
  47447. var Sound = /** @class */ (function () {
  47448. /**
  47449. * Create a sound and attach it to a scene
  47450. * @param name Name of your sound
  47451. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  47452. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  47453. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  47454. */
  47455. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  47456. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  47457. var _this = this;
  47458. this.autoplay = false;
  47459. this.loop = false;
  47460. this.useCustomAttenuation = false;
  47461. this.spatialSound = false;
  47462. this.refDistance = 1;
  47463. this.rolloffFactor = 1;
  47464. this.maxDistance = 100;
  47465. this.distanceModel = "linear";
  47466. this._panningModel = "equalpower";
  47467. this._playbackRate = 1;
  47468. this._streaming = false;
  47469. this._startTime = 0;
  47470. this._startOffset = 0;
  47471. this._position = BABYLON.Vector3.Zero();
  47472. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  47473. this._volume = 1;
  47474. this._isLoaded = false;
  47475. this._isReadyToPlay = false;
  47476. this.isPlaying = false;
  47477. this.isPaused = false;
  47478. this._isDirectional = false;
  47479. // Used if you'd like to create a directional sound.
  47480. // If not set, the sound will be omnidirectional
  47481. this._coneInnerAngle = 360;
  47482. this._coneOuterAngle = 360;
  47483. this._coneOuterGain = 0;
  47484. this._isOutputConnected = false;
  47485. this._urlType = "Unknown";
  47486. this.name = name;
  47487. this._scene = scene;
  47488. this._readyToPlayCallback = readyToPlayCallback;
  47489. // Default custom attenuation function is a linear attenuation
  47490. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  47491. if (currentDistance < maxDistance) {
  47492. return currentVolume * (1 - currentDistance / maxDistance);
  47493. }
  47494. else {
  47495. return 0;
  47496. }
  47497. };
  47498. if (options) {
  47499. this.autoplay = options.autoplay || false;
  47500. this.loop = options.loop || false;
  47501. // if volume === 0, we need another way to check this option
  47502. if (options.volume !== undefined) {
  47503. this._volume = options.volume;
  47504. }
  47505. this.spatialSound = options.spatialSound || false;
  47506. this.maxDistance = options.maxDistance || 100;
  47507. this.useCustomAttenuation = options.useCustomAttenuation || false;
  47508. this.rolloffFactor = options.rolloffFactor || 1;
  47509. this.refDistance = options.refDistance || 1;
  47510. this.distanceModel = options.distanceModel || "linear";
  47511. this._playbackRate = options.playbackRate || 1;
  47512. this._streaming = options.streaming || false;
  47513. }
  47514. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  47515. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  47516. this._soundGain.gain.value = this._volume;
  47517. this._inputAudioNode = this._soundGain;
  47518. this._ouputAudioNode = this._soundGain;
  47519. if (this.spatialSound) {
  47520. this._createSpatialParameters();
  47521. }
  47522. this._scene.mainSoundTrack.AddSound(this);
  47523. var validParameter = true;
  47524. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  47525. if (urlOrArrayBuffer) {
  47526. if (typeof (urlOrArrayBuffer) === "string")
  47527. this._urlType = "String";
  47528. if (Array.isArray(urlOrArrayBuffer))
  47529. this._urlType = "Array";
  47530. if (urlOrArrayBuffer instanceof ArrayBuffer)
  47531. this._urlType = "ArrayBuffer";
  47532. var urls = [];
  47533. var codecSupportedFound = false;
  47534. switch (this._urlType) {
  47535. case "ArrayBuffer":
  47536. if (urlOrArrayBuffer.byteLength > 0) {
  47537. codecSupportedFound = true;
  47538. this._soundLoaded(urlOrArrayBuffer);
  47539. }
  47540. break;
  47541. case "String":
  47542. urls.push(urlOrArrayBuffer);
  47543. case "Array":
  47544. if (urls.length === 0)
  47545. urls = urlOrArrayBuffer;
  47546. // If we found a supported format, we load it immediately and stop the loop
  47547. for (var i = 0; i < urls.length; i++) {
  47548. var url = urls[i];
  47549. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  47550. codecSupportedFound = true;
  47551. }
  47552. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  47553. codecSupportedFound = true;
  47554. }
  47555. if (url.indexOf(".wav", url.length - 4) !== -1) {
  47556. codecSupportedFound = true;
  47557. }
  47558. if (url.indexOf("blob:") !== -1) {
  47559. codecSupportedFound = true;
  47560. }
  47561. if (codecSupportedFound) {
  47562. // Loading sound using XHR2
  47563. if (!this._streaming) {
  47564. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, undefined, this._scene.database, true);
  47565. }
  47566. else {
  47567. this._htmlAudioElement = new Audio(url);
  47568. this._htmlAudioElement.controls = false;
  47569. this._htmlAudioElement.loop = this.loop;
  47570. this._htmlAudioElement.crossOrigin = "anonymous";
  47571. this._htmlAudioElement.preload = "auto";
  47572. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  47573. _this._isReadyToPlay = true;
  47574. if (_this.autoplay) {
  47575. _this.play();
  47576. }
  47577. if (_this._readyToPlayCallback) {
  47578. _this._readyToPlayCallback();
  47579. }
  47580. });
  47581. document.body.appendChild(this._htmlAudioElement);
  47582. }
  47583. break;
  47584. }
  47585. }
  47586. break;
  47587. default:
  47588. validParameter = false;
  47589. break;
  47590. }
  47591. if (!validParameter) {
  47592. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  47593. }
  47594. else {
  47595. if (!codecSupportedFound) {
  47596. this._isReadyToPlay = true;
  47597. // Simulating a ready to play event to avoid breaking code path
  47598. if (this._readyToPlayCallback) {
  47599. window.setTimeout(function () {
  47600. if (_this._readyToPlayCallback) {
  47601. _this._readyToPlayCallback();
  47602. }
  47603. }, 1000);
  47604. }
  47605. }
  47606. }
  47607. }
  47608. }
  47609. else {
  47610. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  47611. this._scene.mainSoundTrack.AddSound(this);
  47612. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  47613. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  47614. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  47615. }
  47616. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  47617. if (this._readyToPlayCallback) {
  47618. window.setTimeout(function () {
  47619. if (_this._readyToPlayCallback) {
  47620. _this._readyToPlayCallback();
  47621. }
  47622. }, 1000);
  47623. }
  47624. }
  47625. }
  47626. Sound.prototype.dispose = function () {
  47627. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  47628. if (this.isPlaying) {
  47629. this.stop();
  47630. }
  47631. this._isReadyToPlay = false;
  47632. if (this.soundTrackId === -1) {
  47633. this._scene.mainSoundTrack.RemoveSound(this);
  47634. }
  47635. else {
  47636. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  47637. }
  47638. if (this._soundGain) {
  47639. this._soundGain.disconnect();
  47640. this._soundGain = null;
  47641. }
  47642. if (this._soundPanner) {
  47643. this._soundPanner.disconnect();
  47644. this._soundPanner = null;
  47645. }
  47646. if (this._soundSource) {
  47647. this._soundSource.disconnect();
  47648. this._soundSource = null;
  47649. }
  47650. this._audioBuffer = null;
  47651. if (this._htmlAudioElement) {
  47652. this._htmlAudioElement.pause();
  47653. this._htmlAudioElement.src = "";
  47654. document.body.removeChild(this._htmlAudioElement);
  47655. }
  47656. if (this._connectedMesh && this._registerFunc) {
  47657. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  47658. this._connectedMesh = null;
  47659. }
  47660. }
  47661. };
  47662. Sound.prototype.isReady = function () {
  47663. return this._isReadyToPlay;
  47664. };
  47665. Sound.prototype._soundLoaded = function (audioData) {
  47666. var _this = this;
  47667. this._isLoaded = true;
  47668. if (!BABYLON.Engine.audioEngine.audioContext) {
  47669. return;
  47670. }
  47671. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  47672. _this._audioBuffer = buffer;
  47673. _this._isReadyToPlay = true;
  47674. if (_this.autoplay) {
  47675. _this.play();
  47676. }
  47677. if (_this._readyToPlayCallback) {
  47678. _this._readyToPlayCallback();
  47679. }
  47680. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  47681. };
  47682. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  47683. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  47684. this._audioBuffer = audioBuffer;
  47685. this._isReadyToPlay = true;
  47686. }
  47687. };
  47688. Sound.prototype.updateOptions = function (options) {
  47689. if (options) {
  47690. this.loop = options.loop || this.loop;
  47691. this.maxDistance = options.maxDistance || this.maxDistance;
  47692. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  47693. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  47694. this.refDistance = options.refDistance || this.refDistance;
  47695. this.distanceModel = options.distanceModel || this.distanceModel;
  47696. this._playbackRate = options.playbackRate || this._playbackRate;
  47697. this._updateSpatialParameters();
  47698. if (this.isPlaying) {
  47699. if (this._streaming) {
  47700. this._htmlAudioElement.playbackRate = this._playbackRate;
  47701. }
  47702. else {
  47703. if (this._soundSource) {
  47704. this._soundSource.playbackRate.value = this._playbackRate;
  47705. }
  47706. }
  47707. }
  47708. }
  47709. };
  47710. Sound.prototype._createSpatialParameters = function () {
  47711. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  47712. if (this._scene.headphone) {
  47713. this._panningModel = "HRTF";
  47714. }
  47715. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  47716. this._updateSpatialParameters();
  47717. this._soundPanner.connect(this._ouputAudioNode);
  47718. this._inputAudioNode = this._soundPanner;
  47719. }
  47720. };
  47721. Sound.prototype._updateSpatialParameters = function () {
  47722. if (this.spatialSound && this._soundPanner) {
  47723. if (this.useCustomAttenuation) {
  47724. // Tricks to disable in a way embedded Web Audio attenuation
  47725. this._soundPanner.distanceModel = "linear";
  47726. this._soundPanner.maxDistance = Number.MAX_VALUE;
  47727. this._soundPanner.refDistance = 1;
  47728. this._soundPanner.rolloffFactor = 1;
  47729. this._soundPanner.panningModel = this._panningModel;
  47730. }
  47731. else {
  47732. this._soundPanner.distanceModel = this.distanceModel;
  47733. this._soundPanner.maxDistance = this.maxDistance;
  47734. this._soundPanner.refDistance = this.refDistance;
  47735. this._soundPanner.rolloffFactor = this.rolloffFactor;
  47736. this._soundPanner.panningModel = this._panningModel;
  47737. }
  47738. }
  47739. };
  47740. Sound.prototype.switchPanningModelToHRTF = function () {
  47741. this._panningModel = "HRTF";
  47742. this._switchPanningModel();
  47743. };
  47744. Sound.prototype.switchPanningModelToEqualPower = function () {
  47745. this._panningModel = "equalpower";
  47746. this._switchPanningModel();
  47747. };
  47748. Sound.prototype._switchPanningModel = function () {
  47749. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  47750. this._soundPanner.panningModel = this._panningModel;
  47751. }
  47752. };
  47753. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  47754. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  47755. if (this._isOutputConnected) {
  47756. this._ouputAudioNode.disconnect();
  47757. }
  47758. this._ouputAudioNode.connect(soundTrackAudioNode);
  47759. this._isOutputConnected = true;
  47760. }
  47761. };
  47762. /**
  47763. * Transform this sound into a directional source
  47764. * @param coneInnerAngle Size of the inner cone in degree
  47765. * @param coneOuterAngle Size of the outer cone in degree
  47766. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  47767. */
  47768. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  47769. if (coneOuterAngle < coneInnerAngle) {
  47770. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  47771. return;
  47772. }
  47773. this._coneInnerAngle = coneInnerAngle;
  47774. this._coneOuterAngle = coneOuterAngle;
  47775. this._coneOuterGain = coneOuterGain;
  47776. this._isDirectional = true;
  47777. if (this.isPlaying && this.loop) {
  47778. this.stop();
  47779. this.play();
  47780. }
  47781. };
  47782. Sound.prototype.setPosition = function (newPosition) {
  47783. this._position = newPosition;
  47784. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  47785. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  47786. }
  47787. };
  47788. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  47789. this._localDirection = newLocalDirection;
  47790. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  47791. this._updateDirection();
  47792. }
  47793. };
  47794. Sound.prototype._updateDirection = function () {
  47795. if (!this._connectedMesh || !this._soundPanner) {
  47796. return;
  47797. }
  47798. var mat = this._connectedMesh.getWorldMatrix();
  47799. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  47800. direction.normalize();
  47801. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  47802. };
  47803. Sound.prototype.updateDistanceFromListener = function () {
  47804. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  47805. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  47806. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  47807. }
  47808. };
  47809. Sound.prototype.setAttenuationFunction = function (callback) {
  47810. this._customAttenuationFunction = callback;
  47811. };
  47812. /**
  47813. * Play the sound
  47814. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  47815. * @param offset (optional) Start the sound setting it at a specific time
  47816. */
  47817. Sound.prototype.play = function (time, offset) {
  47818. var _this = this;
  47819. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  47820. try {
  47821. if (this._startOffset < 0) {
  47822. time = -this._startOffset;
  47823. this._startOffset = 0;
  47824. }
  47825. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  47826. if (!this._soundSource || !this._streamingSource) {
  47827. if (this.spatialSound && this._soundPanner) {
  47828. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  47829. if (this._isDirectional) {
  47830. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  47831. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  47832. this._soundPanner.coneOuterGain = this._coneOuterGain;
  47833. if (this._connectedMesh) {
  47834. this._updateDirection();
  47835. }
  47836. else {
  47837. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  47838. }
  47839. }
  47840. }
  47841. }
  47842. if (this._streaming) {
  47843. if (!this._streamingSource) {
  47844. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  47845. this._htmlAudioElement.onended = function () { _this._onended(); };
  47846. this._htmlAudioElement.playbackRate = this._playbackRate;
  47847. }
  47848. this._streamingSource.disconnect();
  47849. this._streamingSource.connect(this._inputAudioNode);
  47850. this._htmlAudioElement.play();
  47851. }
  47852. else {
  47853. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  47854. this._soundSource.buffer = this._audioBuffer;
  47855. this._soundSource.connect(this._inputAudioNode);
  47856. this._soundSource.loop = this.loop;
  47857. this._soundSource.playbackRate.value = this._playbackRate;
  47858. this._soundSource.onended = function () { _this._onended(); };
  47859. if (this._soundSource.buffer) {
  47860. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  47861. }
  47862. }
  47863. this._startTime = startTime;
  47864. this.isPlaying = true;
  47865. this.isPaused = false;
  47866. }
  47867. catch (ex) {
  47868. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  47869. }
  47870. }
  47871. };
  47872. Sound.prototype._onended = function () {
  47873. this.isPlaying = false;
  47874. if (this.onended) {
  47875. this.onended();
  47876. }
  47877. };
  47878. /**
  47879. * Stop the sound
  47880. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  47881. */
  47882. Sound.prototype.stop = function (time) {
  47883. if (this.isPlaying) {
  47884. if (this._streaming) {
  47885. this._htmlAudioElement.pause();
  47886. // Test needed for Firefox or it will generate an Invalid State Error
  47887. if (this._htmlAudioElement.currentTime > 0) {
  47888. this._htmlAudioElement.currentTime = 0;
  47889. }
  47890. }
  47891. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  47892. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  47893. this._soundSource.stop(stopTime);
  47894. this._soundSource.onended = function () { };
  47895. if (!this.isPaused) {
  47896. this._startOffset = 0;
  47897. }
  47898. }
  47899. this.isPlaying = false;
  47900. }
  47901. };
  47902. Sound.prototype.pause = function () {
  47903. if (this.isPlaying) {
  47904. this.isPaused = true;
  47905. if (this._streaming) {
  47906. this._htmlAudioElement.pause();
  47907. }
  47908. else if (BABYLON.Engine.audioEngine.audioContext) {
  47909. this.stop(0);
  47910. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  47911. }
  47912. }
  47913. };
  47914. Sound.prototype.setVolume = function (newVolume, time) {
  47915. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  47916. if (time && BABYLON.Engine.audioEngine.audioContext) {
  47917. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  47918. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  47919. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  47920. }
  47921. else {
  47922. this._soundGain.gain.value = newVolume;
  47923. }
  47924. }
  47925. this._volume = newVolume;
  47926. };
  47927. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  47928. this._playbackRate = newPlaybackRate;
  47929. if (this.isPlaying) {
  47930. if (this._streaming) {
  47931. this._htmlAudioElement.playbackRate = this._playbackRate;
  47932. }
  47933. else if (this._soundSource) {
  47934. this._soundSource.playbackRate.value = this._playbackRate;
  47935. }
  47936. }
  47937. };
  47938. Sound.prototype.getVolume = function () {
  47939. return this._volume;
  47940. };
  47941. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  47942. var _this = this;
  47943. if (this._connectedMesh && this._registerFunc) {
  47944. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  47945. this._registerFunc = null;
  47946. }
  47947. this._connectedMesh = meshToConnectTo;
  47948. if (!this.spatialSound) {
  47949. this.spatialSound = true;
  47950. this._createSpatialParameters();
  47951. if (this.isPlaying && this.loop) {
  47952. this.stop();
  47953. this.play();
  47954. }
  47955. }
  47956. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  47957. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  47958. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  47959. };
  47960. Sound.prototype.detachFromMesh = function () {
  47961. if (this._connectedMesh && this._registerFunc) {
  47962. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  47963. this._registerFunc = null;
  47964. this._connectedMesh = null;
  47965. }
  47966. };
  47967. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  47968. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  47969. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  47970. this._updateDirection();
  47971. }
  47972. };
  47973. Sound.prototype.clone = function () {
  47974. var _this = this;
  47975. if (!this._streaming) {
  47976. var setBufferAndRun = function () {
  47977. if (_this._isReadyToPlay) {
  47978. clonedSound._audioBuffer = _this.getAudioBuffer();
  47979. clonedSound._isReadyToPlay = true;
  47980. if (clonedSound.autoplay) {
  47981. clonedSound.play();
  47982. }
  47983. }
  47984. else {
  47985. window.setTimeout(setBufferAndRun, 300);
  47986. }
  47987. };
  47988. var currentOptions = {
  47989. autoplay: this.autoplay, loop: this.loop,
  47990. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  47991. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  47992. refDistance: this.refDistance, distanceModel: this.distanceModel
  47993. };
  47994. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  47995. if (this.useCustomAttenuation) {
  47996. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  47997. }
  47998. clonedSound.setPosition(this._position);
  47999. clonedSound.setPlaybackRate(this._playbackRate);
  48000. setBufferAndRun();
  48001. return clonedSound;
  48002. }
  48003. else {
  48004. return null;
  48005. }
  48006. };
  48007. Sound.prototype.getAudioBuffer = function () {
  48008. return this._audioBuffer;
  48009. };
  48010. Sound.prototype.serialize = function () {
  48011. var serializationObject = {
  48012. name: this.name,
  48013. url: this.name,
  48014. autoplay: this.autoplay,
  48015. loop: this.loop,
  48016. volume: this._volume,
  48017. spatialSound: this.spatialSound,
  48018. maxDistance: this.maxDistance,
  48019. rolloffFactor: this.rolloffFactor,
  48020. refDistance: this.refDistance,
  48021. distanceModel: this.distanceModel,
  48022. playbackRate: this._playbackRate,
  48023. panningModel: this._panningModel,
  48024. soundTrackId: this.soundTrackId
  48025. };
  48026. if (this.spatialSound) {
  48027. if (this._connectedMesh)
  48028. serializationObject.connectedMeshId = this._connectedMesh.id;
  48029. serializationObject.position = this._position.asArray();
  48030. serializationObject.refDistance = this.refDistance;
  48031. serializationObject.distanceModel = this.distanceModel;
  48032. serializationObject.isDirectional = this._isDirectional;
  48033. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  48034. serializationObject.coneInnerAngle = this._coneInnerAngle;
  48035. serializationObject.coneOuterAngle = this._coneOuterAngle;
  48036. serializationObject.coneOuterGain = this._coneOuterGain;
  48037. }
  48038. return serializationObject;
  48039. };
  48040. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  48041. var soundName = parsedSound.name;
  48042. var soundUrl;
  48043. if (parsedSound.url) {
  48044. soundUrl = rootUrl + parsedSound.url;
  48045. }
  48046. else {
  48047. soundUrl = rootUrl + soundName;
  48048. }
  48049. var options = {
  48050. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  48051. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  48052. rolloffFactor: parsedSound.rolloffFactor,
  48053. refDistance: parsedSound.refDistance,
  48054. distanceModel: parsedSound.distanceModel,
  48055. playbackRate: parsedSound.playbackRate
  48056. };
  48057. var newSound;
  48058. if (!sourceSound) {
  48059. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  48060. scene._addPendingData(newSound);
  48061. }
  48062. else {
  48063. var setBufferAndRun = function () {
  48064. if (sourceSound._isReadyToPlay) {
  48065. newSound._audioBuffer = sourceSound.getAudioBuffer();
  48066. newSound._isReadyToPlay = true;
  48067. if (newSound.autoplay) {
  48068. newSound.play();
  48069. }
  48070. }
  48071. else {
  48072. window.setTimeout(setBufferAndRun, 300);
  48073. }
  48074. };
  48075. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  48076. setBufferAndRun();
  48077. }
  48078. if (parsedSound.position) {
  48079. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  48080. newSound.setPosition(soundPosition);
  48081. }
  48082. if (parsedSound.isDirectional) {
  48083. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  48084. if (parsedSound.localDirectionToMesh) {
  48085. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  48086. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  48087. }
  48088. }
  48089. if (parsedSound.connectedMeshId) {
  48090. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  48091. if (connectedMesh) {
  48092. newSound.attachToMesh(connectedMesh);
  48093. }
  48094. }
  48095. return newSound;
  48096. };
  48097. return Sound;
  48098. }());
  48099. BABYLON.Sound = Sound;
  48100. })(BABYLON || (BABYLON = {}));
  48101. //# sourceMappingURL=babylon.sound.js.map
  48102. var BABYLON;
  48103. (function (BABYLON) {
  48104. var SoundTrack = /** @class */ (function () {
  48105. function SoundTrack(scene, options) {
  48106. this.id = -1;
  48107. this._isMainTrack = false;
  48108. this._isInitialized = false;
  48109. this._scene = scene;
  48110. this.soundCollection = new Array();
  48111. this._options = options;
  48112. if (!this._isMainTrack) {
  48113. this._scene.soundTracks.push(this);
  48114. this.id = this._scene.soundTracks.length - 1;
  48115. }
  48116. }
  48117. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  48118. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48119. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  48120. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  48121. if (this._options) {
  48122. if (this._options.volume) {
  48123. this._outputAudioNode.gain.value = this._options.volume;
  48124. }
  48125. if (this._options.mainTrack) {
  48126. this._isMainTrack = this._options.mainTrack;
  48127. }
  48128. }
  48129. this._isInitialized = true;
  48130. }
  48131. };
  48132. SoundTrack.prototype.dispose = function () {
  48133. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48134. if (this._connectedAnalyser) {
  48135. this._connectedAnalyser.stopDebugCanvas();
  48136. }
  48137. while (this.soundCollection.length) {
  48138. this.soundCollection[0].dispose();
  48139. }
  48140. if (this._outputAudioNode) {
  48141. this._outputAudioNode.disconnect();
  48142. }
  48143. this._outputAudioNode = null;
  48144. }
  48145. };
  48146. SoundTrack.prototype.AddSound = function (sound) {
  48147. if (!this._isInitialized) {
  48148. this._initializeSoundTrackAudioGraph();
  48149. }
  48150. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  48151. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  48152. }
  48153. if (sound.soundTrackId) {
  48154. if (sound.soundTrackId === -1) {
  48155. this._scene.mainSoundTrack.RemoveSound(sound);
  48156. }
  48157. else {
  48158. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  48159. }
  48160. }
  48161. this.soundCollection.push(sound);
  48162. sound.soundTrackId = this.id;
  48163. };
  48164. SoundTrack.prototype.RemoveSound = function (sound) {
  48165. var index = this.soundCollection.indexOf(sound);
  48166. if (index !== -1) {
  48167. this.soundCollection.splice(index, 1);
  48168. }
  48169. };
  48170. SoundTrack.prototype.setVolume = function (newVolume) {
  48171. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  48172. this._outputAudioNode.gain.value = newVolume;
  48173. }
  48174. };
  48175. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  48176. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48177. for (var i = 0; i < this.soundCollection.length; i++) {
  48178. this.soundCollection[i].switchPanningModelToHRTF();
  48179. }
  48180. }
  48181. };
  48182. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  48183. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48184. for (var i = 0; i < this.soundCollection.length; i++) {
  48185. this.soundCollection[i].switchPanningModelToEqualPower();
  48186. }
  48187. }
  48188. };
  48189. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  48190. if (this._connectedAnalyser) {
  48191. this._connectedAnalyser.stopDebugCanvas();
  48192. }
  48193. this._connectedAnalyser = analyser;
  48194. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  48195. this._outputAudioNode.disconnect();
  48196. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  48197. }
  48198. };
  48199. return SoundTrack;
  48200. }());
  48201. BABYLON.SoundTrack = SoundTrack;
  48202. })(BABYLON || (BABYLON = {}));
  48203. //# sourceMappingURL=babylon.soundtrack.js.map
  48204. var BABYLON;
  48205. (function (BABYLON) {
  48206. var Analyser = /** @class */ (function () {
  48207. function Analyser(scene) {
  48208. this.SMOOTHING = 0.75;
  48209. this.FFT_SIZE = 512;
  48210. this.BARGRAPHAMPLITUDE = 256;
  48211. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  48212. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  48213. this._scene = scene;
  48214. this._audioEngine = BABYLON.Engine.audioEngine;
  48215. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  48216. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  48217. this._webAudioAnalyser.minDecibels = -140;
  48218. this._webAudioAnalyser.maxDecibels = 0;
  48219. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  48220. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  48221. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  48222. }
  48223. }
  48224. Analyser.prototype.getFrequencyBinCount = function () {
  48225. if (this._audioEngine.canUseWebAudio) {
  48226. return this._webAudioAnalyser.frequencyBinCount;
  48227. }
  48228. else {
  48229. return 0;
  48230. }
  48231. };
  48232. Analyser.prototype.getByteFrequencyData = function () {
  48233. if (this._audioEngine.canUseWebAudio) {
  48234. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  48235. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  48236. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  48237. }
  48238. return this._byteFreqs;
  48239. };
  48240. Analyser.prototype.getByteTimeDomainData = function () {
  48241. if (this._audioEngine.canUseWebAudio) {
  48242. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  48243. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  48244. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  48245. }
  48246. return this._byteTime;
  48247. };
  48248. Analyser.prototype.getFloatFrequencyData = function () {
  48249. if (this._audioEngine.canUseWebAudio) {
  48250. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  48251. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  48252. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  48253. }
  48254. return this._floatFreqs;
  48255. };
  48256. Analyser.prototype.drawDebugCanvas = function () {
  48257. var _this = this;
  48258. if (this._audioEngine.canUseWebAudio) {
  48259. if (!this._debugCanvas) {
  48260. this._debugCanvas = document.createElement("canvas");
  48261. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  48262. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  48263. this._debugCanvas.style.position = "absolute";
  48264. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  48265. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  48266. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  48267. document.body.appendChild(this._debugCanvas);
  48268. this._registerFunc = function () {
  48269. _this.drawDebugCanvas();
  48270. };
  48271. this._scene.registerBeforeRender(this._registerFunc);
  48272. }
  48273. if (this._registerFunc && this._debugCanvasContext) {
  48274. var workingArray = this.getByteFrequencyData();
  48275. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  48276. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  48277. // Draw the frequency domain chart.
  48278. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  48279. var value = workingArray[i];
  48280. var percent = value / this.BARGRAPHAMPLITUDE;
  48281. var height = this.DEBUGCANVASSIZE.height * percent;
  48282. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  48283. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  48284. var hue = i / this.getFrequencyBinCount() * 360;
  48285. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  48286. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  48287. }
  48288. }
  48289. }
  48290. };
  48291. Analyser.prototype.stopDebugCanvas = function () {
  48292. if (this._debugCanvas) {
  48293. if (this._registerFunc) {
  48294. this._scene.unregisterBeforeRender(this._registerFunc);
  48295. this._registerFunc = null;
  48296. }
  48297. document.body.removeChild(this._debugCanvas);
  48298. this._debugCanvas = null;
  48299. this._debugCanvasContext = null;
  48300. }
  48301. };
  48302. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  48303. if (this._audioEngine.canUseWebAudio) {
  48304. inputAudioNode.connect(this._webAudioAnalyser);
  48305. this._webAudioAnalyser.connect(outputAudioNode);
  48306. }
  48307. };
  48308. Analyser.prototype.dispose = function () {
  48309. if (this._audioEngine.canUseWebAudio) {
  48310. this._webAudioAnalyser.disconnect();
  48311. }
  48312. };
  48313. return Analyser;
  48314. }());
  48315. BABYLON.Analyser = Analyser;
  48316. })(BABYLON || (BABYLON = {}));
  48317. //# sourceMappingURL=babylon.analyser.js.map
  48318. var BABYLON;
  48319. (function (BABYLON) {
  48320. var CubeTexture = /** @class */ (function (_super) {
  48321. __extends(CubeTexture, _super);
  48322. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  48323. if (onLoad === void 0) { onLoad = null; }
  48324. if (onError === void 0) { onError = null; }
  48325. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  48326. if (prefiltered === void 0) { prefiltered = false; }
  48327. if (forcedExtension === void 0) { forcedExtension = null; }
  48328. var _this = _super.call(this, scene) || this;
  48329. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  48330. _this.name = rootUrl;
  48331. _this.url = rootUrl;
  48332. _this._noMipmap = noMipmap;
  48333. _this.hasAlpha = false;
  48334. _this._format = format;
  48335. _this._prefiltered = prefiltered;
  48336. _this.isCube = true;
  48337. _this._textureMatrix = BABYLON.Matrix.Identity();
  48338. if (prefiltered) {
  48339. _this.gammaSpace = false;
  48340. }
  48341. if (!rootUrl && !files) {
  48342. return _this;
  48343. }
  48344. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  48345. if (!files) {
  48346. if (!extensions) {
  48347. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  48348. }
  48349. files = [];
  48350. for (var index = 0; index < extensions.length; index++) {
  48351. files.push(rootUrl + extensions[index]);
  48352. }
  48353. _this._extensions = extensions;
  48354. }
  48355. _this._files = files;
  48356. if (!_this._texture) {
  48357. if (!scene.useDelayedTextureLoading) {
  48358. if (prefiltered) {
  48359. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  48360. }
  48361. else {
  48362. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  48363. }
  48364. }
  48365. else {
  48366. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  48367. }
  48368. }
  48369. else if (onLoad) {
  48370. if (_this._texture.isReady) {
  48371. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  48372. }
  48373. else {
  48374. _this._texture.onLoadedObservable.add(onLoad);
  48375. }
  48376. }
  48377. return _this;
  48378. }
  48379. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  48380. return new CubeTexture("", scene, null, noMipmap, files);
  48381. };
  48382. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  48383. if (forcedExtension === void 0) { forcedExtension = null; }
  48384. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  48385. };
  48386. // Methods
  48387. CubeTexture.prototype.delayLoad = function () {
  48388. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  48389. return;
  48390. }
  48391. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  48392. this._texture = this._getFromCache(this.url, this._noMipmap);
  48393. if (!this._texture) {
  48394. if (this._prefiltered) {
  48395. this._texture = this.getScene().getEngine().createPrefilteredCubeTexture(this.url, this.getScene(), this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  48396. }
  48397. else {
  48398. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  48399. }
  48400. }
  48401. };
  48402. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  48403. return this._textureMatrix;
  48404. };
  48405. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  48406. this._textureMatrix = value;
  48407. };
  48408. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  48409. var texture = BABYLON.SerializationHelper.Parse(function () {
  48410. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  48411. }, parsedTexture, scene);
  48412. // Animations
  48413. if (parsedTexture.animations) {
  48414. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  48415. var parsedAnimation = parsedTexture.animations[animationIndex];
  48416. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  48417. }
  48418. }
  48419. return texture;
  48420. };
  48421. CubeTexture.prototype.clone = function () {
  48422. var _this = this;
  48423. return BABYLON.SerializationHelper.Clone(function () {
  48424. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  48425. }, this);
  48426. };
  48427. return CubeTexture;
  48428. }(BABYLON.BaseTexture));
  48429. BABYLON.CubeTexture = CubeTexture;
  48430. })(BABYLON || (BABYLON = {}));
  48431. //# sourceMappingURL=babylon.cubeTexture.js.map
  48432. var BABYLON;
  48433. (function (BABYLON) {
  48434. var RenderTargetTexture = /** @class */ (function (_super) {
  48435. __extends(RenderTargetTexture, _super);
  48436. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  48437. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  48438. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  48439. if (isCube === void 0) { isCube = false; }
  48440. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48441. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  48442. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  48443. if (isMulti === void 0) { isMulti = false; }
  48444. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  48445. _this.isCube = isCube;
  48446. /**
  48447. * Use this list to define the list of mesh you want to render.
  48448. */
  48449. _this.renderList = new Array();
  48450. _this.renderParticles = true;
  48451. _this.renderSprites = false;
  48452. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  48453. _this.ignoreCameraViewport = false;
  48454. // Events
  48455. /**
  48456. * An event triggered when the texture is unbind.
  48457. * @type {BABYLON.Observable}
  48458. */
  48459. _this.onBeforeBindObservable = new BABYLON.Observable();
  48460. /**
  48461. * An event triggered when the texture is unbind.
  48462. * @type {BABYLON.Observable}
  48463. */
  48464. _this.onAfterUnbindObservable = new BABYLON.Observable();
  48465. /**
  48466. * An event triggered before rendering the texture
  48467. * @type {BABYLON.Observable}
  48468. */
  48469. _this.onBeforeRenderObservable = new BABYLON.Observable();
  48470. /**
  48471. * An event triggered after rendering the texture
  48472. * @type {BABYLON.Observable}
  48473. */
  48474. _this.onAfterRenderObservable = new BABYLON.Observable();
  48475. /**
  48476. * An event triggered after the texture clear
  48477. * @type {BABYLON.Observable}
  48478. */
  48479. _this.onClearObservable = new BABYLON.Observable();
  48480. _this._currentRefreshId = -1;
  48481. _this._refreshRate = 1;
  48482. _this._samples = 1;
  48483. scene = _this.getScene();
  48484. if (!scene) {
  48485. return _this;
  48486. }
  48487. _this.name = name;
  48488. _this.isRenderTarget = true;
  48489. _this._size = size;
  48490. _this._generateMipMaps = generateMipMaps ? true : false;
  48491. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  48492. // Rendering groups
  48493. _this._renderingManager = new BABYLON.RenderingManager(scene);
  48494. if (isMulti) {
  48495. return _this;
  48496. }
  48497. _this._renderTargetOptions = {
  48498. generateMipMaps: generateMipMaps,
  48499. type: type,
  48500. samplingMode: samplingMode,
  48501. generateDepthBuffer: generateDepthBuffer,
  48502. generateStencilBuffer: generateStencilBuffer
  48503. };
  48504. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  48505. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48506. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48507. }
  48508. if (isCube) {
  48509. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  48510. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  48511. _this._textureMatrix = BABYLON.Matrix.Identity();
  48512. }
  48513. else {
  48514. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  48515. }
  48516. return _this;
  48517. }
  48518. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  48519. get: function () {
  48520. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  48521. },
  48522. enumerable: true,
  48523. configurable: true
  48524. });
  48525. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  48526. get: function () {
  48527. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  48528. },
  48529. enumerable: true,
  48530. configurable: true
  48531. });
  48532. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  48533. get: function () {
  48534. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  48535. },
  48536. enumerable: true,
  48537. configurable: true
  48538. });
  48539. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  48540. set: function (callback) {
  48541. if (this._onAfterUnbindObserver) {
  48542. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  48543. }
  48544. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  48545. },
  48546. enumerable: true,
  48547. configurable: true
  48548. });
  48549. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  48550. set: function (callback) {
  48551. if (this._onBeforeRenderObserver) {
  48552. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  48553. }
  48554. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  48555. },
  48556. enumerable: true,
  48557. configurable: true
  48558. });
  48559. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  48560. set: function (callback) {
  48561. if (this._onAfterRenderObserver) {
  48562. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  48563. }
  48564. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  48565. },
  48566. enumerable: true,
  48567. configurable: true
  48568. });
  48569. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  48570. set: function (callback) {
  48571. if (this._onClearObserver) {
  48572. this.onClearObservable.remove(this._onClearObserver);
  48573. }
  48574. this._onClearObserver = this.onClearObservable.add(callback);
  48575. },
  48576. enumerable: true,
  48577. configurable: true
  48578. });
  48579. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  48580. get: function () {
  48581. return this._renderTargetOptions;
  48582. },
  48583. enumerable: true,
  48584. configurable: true
  48585. });
  48586. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  48587. get: function () {
  48588. return this._samples;
  48589. },
  48590. set: function (value) {
  48591. if (this._samples === value) {
  48592. return;
  48593. }
  48594. var scene = this.getScene();
  48595. if (!scene) {
  48596. return;
  48597. }
  48598. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  48599. },
  48600. enumerable: true,
  48601. configurable: true
  48602. });
  48603. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  48604. this._currentRefreshId = -1;
  48605. };
  48606. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  48607. get: function () {
  48608. return this._refreshRate;
  48609. },
  48610. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  48611. set: function (value) {
  48612. this._refreshRate = value;
  48613. this.resetRefreshCounter();
  48614. },
  48615. enumerable: true,
  48616. configurable: true
  48617. });
  48618. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  48619. if (!this._postProcessManager) {
  48620. var scene = this.getScene();
  48621. if (!scene) {
  48622. return;
  48623. }
  48624. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  48625. this._postProcesses = new Array();
  48626. }
  48627. this._postProcesses.push(postProcess);
  48628. this._postProcesses[0].autoClear = false;
  48629. };
  48630. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  48631. if (!this._postProcesses) {
  48632. return;
  48633. }
  48634. if (dispose) {
  48635. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  48636. var postProcess = _a[_i];
  48637. postProcess.dispose();
  48638. }
  48639. }
  48640. this._postProcesses = [];
  48641. };
  48642. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  48643. if (!this._postProcesses) {
  48644. return;
  48645. }
  48646. var index = this._postProcesses.indexOf(postProcess);
  48647. if (index === -1) {
  48648. return;
  48649. }
  48650. this._postProcesses.splice(index, 1);
  48651. if (this._postProcesses.length > 0) {
  48652. this._postProcesses[0].autoClear = false;
  48653. }
  48654. };
  48655. RenderTargetTexture.prototype._shouldRender = function () {
  48656. if (this._currentRefreshId === -1) {
  48657. this._currentRefreshId = 1;
  48658. return true;
  48659. }
  48660. if (this.refreshRate === this._currentRefreshId) {
  48661. this._currentRefreshId = 1;
  48662. return true;
  48663. }
  48664. this._currentRefreshId++;
  48665. return false;
  48666. };
  48667. RenderTargetTexture.prototype.getRenderSize = function () {
  48668. return this._size;
  48669. };
  48670. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  48671. get: function () {
  48672. return true;
  48673. },
  48674. enumerable: true,
  48675. configurable: true
  48676. });
  48677. RenderTargetTexture.prototype.scale = function (ratio) {
  48678. var newSize = this._size * ratio;
  48679. this.resize(newSize);
  48680. };
  48681. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  48682. if (this.isCube) {
  48683. return this._textureMatrix;
  48684. }
  48685. return _super.prototype.getReflectionTextureMatrix.call(this);
  48686. };
  48687. RenderTargetTexture.prototype.resize = function (size) {
  48688. this.releaseInternalTexture();
  48689. var scene = this.getScene();
  48690. if (!scene) {
  48691. return;
  48692. }
  48693. if (this.isCube) {
  48694. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  48695. }
  48696. else {
  48697. this._texture = scene.getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  48698. }
  48699. this._size = size;
  48700. };
  48701. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  48702. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  48703. if (dumpForDebug === void 0) { dumpForDebug = false; }
  48704. var scene = this.getScene();
  48705. if (!scene) {
  48706. return;
  48707. }
  48708. var engine = scene.getEngine();
  48709. if (this.useCameraPostProcesses !== undefined) {
  48710. useCameraPostProcess = this.useCameraPostProcesses;
  48711. }
  48712. if (this._waitingRenderList) {
  48713. this.renderList = [];
  48714. for (var index = 0; index < this._waitingRenderList.length; index++) {
  48715. var id = this._waitingRenderList[index];
  48716. var mesh_1 = scene.getMeshByID(id);
  48717. if (mesh_1) {
  48718. this.renderList.push(mesh_1);
  48719. }
  48720. }
  48721. delete this._waitingRenderList;
  48722. }
  48723. // Is predicate defined?
  48724. if (this.renderListPredicate) {
  48725. if (this.renderList) {
  48726. this.renderList.splice(0); // Clear previous renderList
  48727. }
  48728. else {
  48729. this.renderList = [];
  48730. }
  48731. var scene = this.getScene();
  48732. if (!scene) {
  48733. return;
  48734. }
  48735. var sceneMeshes = scene.meshes;
  48736. for (var index = 0; index < sceneMeshes.length; index++) {
  48737. var mesh = sceneMeshes[index];
  48738. if (this.renderListPredicate(mesh)) {
  48739. this.renderList.push(mesh);
  48740. }
  48741. }
  48742. }
  48743. this.onBeforeBindObservable.notifyObservers(this);
  48744. // Set custom projection.
  48745. // Needs to be before binding to prevent changing the aspect ratio.
  48746. var camera;
  48747. if (this.activeCamera) {
  48748. camera = this.activeCamera;
  48749. engine.setViewport(this.activeCamera.viewport, this._size, this._size);
  48750. if (this.activeCamera !== scene.activeCamera) {
  48751. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  48752. }
  48753. }
  48754. else {
  48755. camera = scene.activeCamera;
  48756. if (camera) {
  48757. engine.setViewport(camera.viewport, this._size, this._size);
  48758. }
  48759. }
  48760. // Prepare renderingManager
  48761. this._renderingManager.reset();
  48762. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  48763. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  48764. var sceneRenderId = scene.getRenderId();
  48765. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  48766. var mesh = currentRenderList[meshIndex];
  48767. if (mesh) {
  48768. if (!mesh.isReady()) {
  48769. // Reset _currentRefreshId
  48770. this.resetRefreshCounter();
  48771. continue;
  48772. }
  48773. mesh._preActivateForIntermediateRendering(sceneRenderId);
  48774. var isMasked = void 0;
  48775. if (!this.renderList && camera) {
  48776. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  48777. }
  48778. else {
  48779. isMasked = false;
  48780. }
  48781. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  48782. mesh._activate(sceneRenderId);
  48783. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  48784. var subMesh = mesh.subMeshes[subIndex];
  48785. scene._activeIndices.addCount(subMesh.indexCount, false);
  48786. this._renderingManager.dispatch(subMesh);
  48787. }
  48788. }
  48789. }
  48790. }
  48791. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  48792. var particleSystem = scene.particleSystems[particleIndex];
  48793. var emitter = particleSystem.emitter;
  48794. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  48795. continue;
  48796. }
  48797. if (currentRenderList.indexOf(emitter) >= 0) {
  48798. this._renderingManager.dispatchParticles(particleSystem);
  48799. }
  48800. }
  48801. if (this.isCube) {
  48802. for (var face = 0; face < 6; face++) {
  48803. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  48804. scene.incrementRenderId();
  48805. scene.resetCachedMaterial();
  48806. }
  48807. }
  48808. else {
  48809. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  48810. }
  48811. this.onAfterUnbindObservable.notifyObservers(this);
  48812. if (scene.activeCamera) {
  48813. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  48814. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  48815. }
  48816. engine.setViewport(scene.activeCamera.viewport);
  48817. }
  48818. scene.resetCachedMaterial();
  48819. };
  48820. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  48821. var _this = this;
  48822. var scene = this.getScene();
  48823. if (!scene) {
  48824. return;
  48825. }
  48826. var engine = scene.getEngine();
  48827. if (!this._texture) {
  48828. return;
  48829. }
  48830. // Bind
  48831. if (this._postProcessManager) {
  48832. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  48833. }
  48834. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  48835. if (this._texture) {
  48836. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  48837. }
  48838. }
  48839. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  48840. // Clear
  48841. if (this.onClearObservable.hasObservers()) {
  48842. this.onClearObservable.notifyObservers(engine);
  48843. }
  48844. else {
  48845. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  48846. }
  48847. if (!this._doNotChangeAspectRatio) {
  48848. scene.updateTransformMatrix(true);
  48849. }
  48850. // Render
  48851. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  48852. if (this._postProcessManager) {
  48853. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  48854. }
  48855. else if (useCameraPostProcess) {
  48856. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  48857. }
  48858. if (!this._doNotChangeAspectRatio) {
  48859. scene.updateTransformMatrix(true);
  48860. }
  48861. // Dump ?
  48862. if (dumpForDebug) {
  48863. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  48864. }
  48865. // Unbind
  48866. if (!this.isCube || faceIndex === 5) {
  48867. if (this.isCube) {
  48868. if (faceIndex === 5) {
  48869. engine.generateMipMapsForCubemap(this._texture);
  48870. }
  48871. }
  48872. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  48873. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  48874. });
  48875. }
  48876. else {
  48877. this.onAfterRenderObservable.notifyObservers(faceIndex);
  48878. }
  48879. };
  48880. /**
  48881. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  48882. * This allowed control for front to back rendering or reversly depending of the special needs.
  48883. *
  48884. * @param renderingGroupId The rendering group id corresponding to its index
  48885. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  48886. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  48887. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  48888. */
  48889. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  48890. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  48891. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  48892. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  48893. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  48894. };
  48895. /**
  48896. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  48897. *
  48898. * @param renderingGroupId The rendering group id corresponding to its index
  48899. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  48900. */
  48901. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  48902. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  48903. };
  48904. RenderTargetTexture.prototype.clone = function () {
  48905. var textureSize = this.getSize();
  48906. 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);
  48907. // Base texture
  48908. newTexture.hasAlpha = this.hasAlpha;
  48909. newTexture.level = this.level;
  48910. // RenderTarget Texture
  48911. newTexture.coordinatesMode = this.coordinatesMode;
  48912. if (this.renderList) {
  48913. newTexture.renderList = this.renderList.slice(0);
  48914. }
  48915. return newTexture;
  48916. };
  48917. RenderTargetTexture.prototype.serialize = function () {
  48918. if (!this.name) {
  48919. return null;
  48920. }
  48921. var serializationObject = _super.prototype.serialize.call(this);
  48922. serializationObject.renderTargetSize = this.getRenderSize();
  48923. serializationObject.renderList = [];
  48924. if (this.renderList) {
  48925. for (var index = 0; index < this.renderList.length; index++) {
  48926. serializationObject.renderList.push(this.renderList[index].id);
  48927. }
  48928. }
  48929. return serializationObject;
  48930. };
  48931. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  48932. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  48933. var objBuffer = this.getInternalTexture();
  48934. var scene = this.getScene();
  48935. if (objBuffer && scene) {
  48936. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  48937. }
  48938. };
  48939. RenderTargetTexture.prototype.dispose = function () {
  48940. if (this._postProcessManager) {
  48941. this._postProcessManager.dispose();
  48942. this._postProcessManager = null;
  48943. }
  48944. this.clearPostProcesses(true);
  48945. this.renderList = null;
  48946. // Remove from custom render targets
  48947. var scene = this.getScene();
  48948. if (!scene) {
  48949. return;
  48950. }
  48951. var index = scene.customRenderTargets.indexOf(this);
  48952. if (index >= 0) {
  48953. scene.customRenderTargets.splice(index, 1);
  48954. }
  48955. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  48956. var camera = _a[_i];
  48957. index = camera.customRenderTargets.indexOf(this);
  48958. if (index >= 0) {
  48959. camera.customRenderTargets.splice(index, 1);
  48960. }
  48961. }
  48962. _super.prototype.dispose.call(this);
  48963. };
  48964. RenderTargetTexture.prototype._rebuild = function () {
  48965. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  48966. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  48967. }
  48968. if (this._postProcessManager) {
  48969. this._postProcessManager._rebuild();
  48970. }
  48971. };
  48972. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  48973. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  48974. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  48975. return RenderTargetTexture;
  48976. }(BABYLON.Texture));
  48977. BABYLON.RenderTargetTexture = RenderTargetTexture;
  48978. })(BABYLON || (BABYLON = {}));
  48979. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  48980. var BABYLON;
  48981. (function (BABYLON) {
  48982. ;
  48983. var MultiRenderTarget = /** @class */ (function (_super) {
  48984. __extends(MultiRenderTarget, _super);
  48985. function MultiRenderTarget(name, size, count, scene, options) {
  48986. var _this = this;
  48987. options = options || {};
  48988. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  48989. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  48990. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  48991. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  48992. if (!_this.isSupported) {
  48993. _this.dispose();
  48994. return;
  48995. }
  48996. var types = [];
  48997. var samplingModes = [];
  48998. for (var i = 0; i < count; i++) {
  48999. if (options.types && options.types[i]) {
  49000. types.push(options.types[i]);
  49001. }
  49002. else {
  49003. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  49004. }
  49005. if (options.samplingModes && options.samplingModes[i]) {
  49006. samplingModes.push(options.samplingModes[i]);
  49007. }
  49008. else {
  49009. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  49010. }
  49011. }
  49012. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  49013. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  49014. _this._count = count;
  49015. _this._size = size;
  49016. _this._multiRenderTargetOptions = {
  49017. samplingModes: samplingModes,
  49018. generateMipMaps: generateMipMaps,
  49019. generateDepthBuffer: generateDepthBuffer,
  49020. generateStencilBuffer: generateStencilBuffer,
  49021. generateDepthTexture: generateDepthTexture,
  49022. types: types,
  49023. textureCount: count
  49024. };
  49025. _this._createInternalTextures();
  49026. _this._createTextures();
  49027. return _this;
  49028. }
  49029. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  49030. get: function () {
  49031. var engine = this.getScene().getEngine();
  49032. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  49033. },
  49034. enumerable: true,
  49035. configurable: true
  49036. });
  49037. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  49038. get: function () {
  49039. return this._textures;
  49040. },
  49041. enumerable: true,
  49042. configurable: true
  49043. });
  49044. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  49045. get: function () {
  49046. return this._textures[this._textures.length - 1];
  49047. },
  49048. enumerable: true,
  49049. configurable: true
  49050. });
  49051. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  49052. set: function (wrap) {
  49053. if (this._textures) {
  49054. for (var i = 0; i < this._textures.length; i++) {
  49055. this._textures[i].wrapU = wrap;
  49056. }
  49057. }
  49058. },
  49059. enumerable: true,
  49060. configurable: true
  49061. });
  49062. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  49063. set: function (wrap) {
  49064. if (this._textures) {
  49065. for (var i = 0; i < this._textures.length; i++) {
  49066. this._textures[i].wrapV = wrap;
  49067. }
  49068. }
  49069. },
  49070. enumerable: true,
  49071. configurable: true
  49072. });
  49073. MultiRenderTarget.prototype._rebuild = function () {
  49074. this.releaseInternalTextures();
  49075. this._createInternalTextures();
  49076. for (var i = 0; i < this._internalTextures.length; i++) {
  49077. var texture = this._textures[i];
  49078. texture._texture = this._internalTextures[i];
  49079. }
  49080. // Keeps references to frame buffer and stencil/depth buffer
  49081. this._texture = this._internalTextures[0];
  49082. };
  49083. MultiRenderTarget.prototype._createInternalTextures = function () {
  49084. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  49085. };
  49086. MultiRenderTarget.prototype._createTextures = function () {
  49087. this._textures = [];
  49088. for (var i = 0; i < this._internalTextures.length; i++) {
  49089. var texture = new BABYLON.Texture(null, this.getScene());
  49090. texture._texture = this._internalTextures[i];
  49091. this._textures.push(texture);
  49092. }
  49093. // Keeps references to frame buffer and stencil/depth buffer
  49094. this._texture = this._internalTextures[0];
  49095. };
  49096. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  49097. get: function () {
  49098. return this._samples;
  49099. },
  49100. set: function (value) {
  49101. if (this._samples === value) {
  49102. return;
  49103. }
  49104. for (var i = 0; i < this._internalTextures.length; i++) {
  49105. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  49106. }
  49107. },
  49108. enumerable: true,
  49109. configurable: true
  49110. });
  49111. MultiRenderTarget.prototype.resize = function (size) {
  49112. this.releaseInternalTextures();
  49113. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  49114. this._createInternalTextures();
  49115. };
  49116. MultiRenderTarget.prototype.dispose = function () {
  49117. this.releaseInternalTextures();
  49118. _super.prototype.dispose.call(this);
  49119. };
  49120. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  49121. if (!this._internalTextures) {
  49122. return;
  49123. }
  49124. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  49125. if (this._internalTextures[i] !== undefined) {
  49126. this._internalTextures[i].dispose();
  49127. this._internalTextures.splice(i, 1);
  49128. }
  49129. }
  49130. };
  49131. return MultiRenderTarget;
  49132. }(BABYLON.RenderTargetTexture));
  49133. BABYLON.MultiRenderTarget = MultiRenderTarget;
  49134. })(BABYLON || (BABYLON = {}));
  49135. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  49136. /// <reference path="babylon.renderTargetTexture.ts" />
  49137. var BABYLON;
  49138. (function (BABYLON) {
  49139. var MirrorTexture = /** @class */ (function (_super) {
  49140. __extends(MirrorTexture, _super);
  49141. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  49142. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  49143. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  49144. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  49145. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  49146. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  49147. _this._transformMatrix = BABYLON.Matrix.Zero();
  49148. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  49149. _this._blurKernelX = 0;
  49150. _this._blurKernelY = 0;
  49151. _this._blurRatio = 1.0;
  49152. _this.ignoreCameraViewport = true;
  49153. _this.onBeforeRenderObservable.add(function () {
  49154. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  49155. _this._savedViewMatrix = scene.getViewMatrix();
  49156. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  49157. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  49158. scene.clipPlane = _this.mirrorPlane;
  49159. scene.getEngine().cullBackFaces = false;
  49160. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  49161. });
  49162. _this.onAfterRenderObservable.add(function () {
  49163. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  49164. scene.getEngine().cullBackFaces = true;
  49165. scene._mirroredCameraPosition = null;
  49166. delete scene.clipPlane;
  49167. });
  49168. return _this;
  49169. }
  49170. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  49171. get: function () {
  49172. return this._blurRatio;
  49173. },
  49174. set: function (value) {
  49175. if (this._blurRatio === value) {
  49176. return;
  49177. }
  49178. this._blurRatio = value;
  49179. this._preparePostProcesses();
  49180. },
  49181. enumerable: true,
  49182. configurable: true
  49183. });
  49184. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  49185. set: function (value) {
  49186. this.blurKernelX = value;
  49187. this.blurKernelY = value;
  49188. },
  49189. enumerable: true,
  49190. configurable: true
  49191. });
  49192. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  49193. get: function () {
  49194. return this._blurKernelX;
  49195. },
  49196. set: function (value) {
  49197. if (this._blurKernelX === value) {
  49198. return;
  49199. }
  49200. this._blurKernelX = value;
  49201. this._preparePostProcesses();
  49202. },
  49203. enumerable: true,
  49204. configurable: true
  49205. });
  49206. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  49207. get: function () {
  49208. return this._blurKernelY;
  49209. },
  49210. set: function (value) {
  49211. if (this._blurKernelY === value) {
  49212. return;
  49213. }
  49214. this._blurKernelY = value;
  49215. this._preparePostProcesses();
  49216. },
  49217. enumerable: true,
  49218. configurable: true
  49219. });
  49220. MirrorTexture.prototype._preparePostProcesses = function () {
  49221. this.clearPostProcesses(true);
  49222. if (this._blurKernelX && this._blurKernelY) {
  49223. var engine = this.getScene().getEngine();
  49224. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  49225. 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);
  49226. this._blurX.autoClear = false;
  49227. if (this._blurRatio === 1 && this.samples < 2) {
  49228. this._blurX.outputTexture = this._texture;
  49229. }
  49230. else {
  49231. this._blurX.alwaysForcePOT = true;
  49232. }
  49233. 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);
  49234. this._blurY.autoClear = false;
  49235. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  49236. this.addPostProcess(this._blurX);
  49237. this.addPostProcess(this._blurY);
  49238. }
  49239. };
  49240. MirrorTexture.prototype.clone = function () {
  49241. var textureSize = this.getSize();
  49242. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  49243. // Base texture
  49244. newTexture.hasAlpha = this.hasAlpha;
  49245. newTexture.level = this.level;
  49246. // Mirror Texture
  49247. newTexture.mirrorPlane = this.mirrorPlane.clone();
  49248. newTexture.renderList = this.renderList.slice(0);
  49249. return newTexture;
  49250. };
  49251. MirrorTexture.prototype.serialize = function () {
  49252. if (!this.name) {
  49253. return null;
  49254. }
  49255. var serializationObject = _super.prototype.serialize.call(this);
  49256. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  49257. return serializationObject;
  49258. };
  49259. return MirrorTexture;
  49260. }(BABYLON.RenderTargetTexture));
  49261. BABYLON.MirrorTexture = MirrorTexture;
  49262. })(BABYLON || (BABYLON = {}));
  49263. //# sourceMappingURL=babylon.mirrorTexture.js.map
  49264. /// <reference path="babylon.renderTargetTexture.ts" />
  49265. var BABYLON;
  49266. (function (BABYLON) {
  49267. /**
  49268. * Creates a refraction texture used by refraction channel of the standard material.
  49269. * @param name the texture name
  49270. * @param size size of the underlying texture
  49271. * @param scene root scene
  49272. */
  49273. var RefractionTexture = /** @class */ (function (_super) {
  49274. __extends(RefractionTexture, _super);
  49275. function RefractionTexture(name, size, scene, generateMipMaps) {
  49276. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  49277. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  49278. _this.depth = 2.0;
  49279. _this.onBeforeRenderObservable.add(function () {
  49280. scene.clipPlane = _this.refractionPlane;
  49281. });
  49282. _this.onAfterRenderObservable.add(function () {
  49283. delete scene.clipPlane;
  49284. });
  49285. return _this;
  49286. }
  49287. RefractionTexture.prototype.clone = function () {
  49288. var textureSize = this.getSize();
  49289. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  49290. // Base texture
  49291. newTexture.hasAlpha = this.hasAlpha;
  49292. newTexture.level = this.level;
  49293. // Refraction Texture
  49294. newTexture.refractionPlane = this.refractionPlane.clone();
  49295. newTexture.renderList = this.renderList.slice(0);
  49296. newTexture.depth = this.depth;
  49297. return newTexture;
  49298. };
  49299. RefractionTexture.prototype.serialize = function () {
  49300. if (!this.name) {
  49301. return null;
  49302. }
  49303. var serializationObject = _super.prototype.serialize.call(this);
  49304. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  49305. serializationObject.depth = this.depth;
  49306. return serializationObject;
  49307. };
  49308. return RefractionTexture;
  49309. }(BABYLON.RenderTargetTexture));
  49310. BABYLON.RefractionTexture = RefractionTexture;
  49311. })(BABYLON || (BABYLON = {}));
  49312. //# sourceMappingURL=babylon.refractionTexture.js.map
  49313. /// <reference path="babylon.texture.ts" />
  49314. var BABYLON;
  49315. (function (BABYLON) {
  49316. var DynamicTexture = /** @class */ (function (_super) {
  49317. __extends(DynamicTexture, _super);
  49318. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  49319. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49320. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  49321. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  49322. _this.name = name;
  49323. var engine = _this.getScene().getEngine();
  49324. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49325. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49326. _this._generateMipMaps = generateMipMaps;
  49327. if (options.getContext) {
  49328. _this._canvas = options;
  49329. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  49330. }
  49331. else {
  49332. _this._canvas = document.createElement("canvas");
  49333. if (options.width) {
  49334. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  49335. }
  49336. else {
  49337. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  49338. }
  49339. }
  49340. var textureSize = _this.getSize();
  49341. _this._canvas.width = textureSize.width;
  49342. _this._canvas.height = textureSize.height;
  49343. _this._context = _this._canvas.getContext("2d");
  49344. return _this;
  49345. }
  49346. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  49347. get: function () {
  49348. return true;
  49349. },
  49350. enumerable: true,
  49351. configurable: true
  49352. });
  49353. DynamicTexture.prototype._recreate = function (textureSize) {
  49354. this._canvas.width = textureSize.width;
  49355. this._canvas.height = textureSize.height;
  49356. this.releaseInternalTexture();
  49357. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  49358. };
  49359. DynamicTexture.prototype.scale = function (ratio) {
  49360. var textureSize = this.getSize();
  49361. textureSize.width *= ratio;
  49362. textureSize.height *= ratio;
  49363. this._recreate(textureSize);
  49364. };
  49365. DynamicTexture.prototype.scaleTo = function (width, height) {
  49366. var textureSize = this.getSize();
  49367. textureSize.width = width;
  49368. textureSize.height = height;
  49369. this._recreate(textureSize);
  49370. };
  49371. DynamicTexture.prototype.getContext = function () {
  49372. return this._context;
  49373. };
  49374. DynamicTexture.prototype.clear = function () {
  49375. var size = this.getSize();
  49376. this._context.fillRect(0, 0, size.width, size.height);
  49377. };
  49378. DynamicTexture.prototype.update = function (invertY) {
  49379. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  49380. };
  49381. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  49382. if (update === void 0) { update = true; }
  49383. var size = this.getSize();
  49384. if (clearColor) {
  49385. this._context.fillStyle = clearColor;
  49386. this._context.fillRect(0, 0, size.width, size.height);
  49387. }
  49388. this._context.font = font;
  49389. if (x === null || x === undefined) {
  49390. var textSize = this._context.measureText(text);
  49391. x = (size.width - textSize.width) / 2;
  49392. }
  49393. if (y === null || y === undefined) {
  49394. var fontSize = parseInt((font.replace(/\D/g, '')));
  49395. ;
  49396. y = (size.height / 2) + (fontSize / 3.65);
  49397. }
  49398. this._context.fillStyle = color;
  49399. this._context.fillText(text, x, y);
  49400. if (update) {
  49401. this.update(invertY);
  49402. }
  49403. };
  49404. DynamicTexture.prototype.clone = function () {
  49405. var textureSize = this.getSize();
  49406. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  49407. // Base texture
  49408. newTexture.hasAlpha = this.hasAlpha;
  49409. newTexture.level = this.level;
  49410. // Dynamic Texture
  49411. newTexture.wrapU = this.wrapU;
  49412. newTexture.wrapV = this.wrapV;
  49413. return newTexture;
  49414. };
  49415. DynamicTexture.prototype._rebuild = function () {
  49416. this.update();
  49417. };
  49418. return DynamicTexture;
  49419. }(BABYLON.Texture));
  49420. BABYLON.DynamicTexture = DynamicTexture;
  49421. })(BABYLON || (BABYLON = {}));
  49422. //# sourceMappingURL=babylon.dynamicTexture.js.map
  49423. var BABYLON;
  49424. (function (BABYLON) {
  49425. var VideoTexture = /** @class */ (function (_super) {
  49426. __extends(VideoTexture, _super);
  49427. /**
  49428. * Creates a video texture.
  49429. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  49430. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  49431. * @param {BABYLON.Scene} scene is obviously the current scene.
  49432. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  49433. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  49434. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  49435. */
  49436. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  49437. if (generateMipMaps === void 0) { generateMipMaps = false; }
  49438. if (invertY === void 0) { invertY = false; }
  49439. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49440. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  49441. _this._autoLaunch = true;
  49442. var urls;
  49443. _this.name = name;
  49444. if (urlsOrVideo instanceof HTMLVideoElement) {
  49445. _this.video = urlsOrVideo;
  49446. }
  49447. else {
  49448. urls = urlsOrVideo;
  49449. _this.video = document.createElement("video");
  49450. _this.video.autoplay = false;
  49451. _this.video.loop = true;
  49452. }
  49453. _this._generateMipMaps = generateMipMaps;
  49454. _this._samplingMode = samplingMode;
  49455. if (!_this.getScene().getEngine().needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  49456. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  49457. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  49458. }
  49459. else {
  49460. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49461. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49462. _this._generateMipMaps = false;
  49463. }
  49464. if (urls) {
  49465. _this.video.addEventListener("canplay", function () {
  49466. _this._createTexture();
  49467. });
  49468. urls.forEach(function (url) {
  49469. var source = document.createElement("source");
  49470. source.src = url;
  49471. _this.video.appendChild(source);
  49472. });
  49473. }
  49474. else {
  49475. _this._createTexture();
  49476. }
  49477. _this._lastUpdate = BABYLON.Tools.Now;
  49478. return _this;
  49479. }
  49480. VideoTexture.prototype.__setTextureReady = function () {
  49481. this._texture.isReady = true;
  49482. };
  49483. VideoTexture.prototype._createTexture = function () {
  49484. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  49485. if (this._autoLaunch) {
  49486. this._autoLaunch = false;
  49487. this.video.play();
  49488. }
  49489. this._setTextureReady = this.__setTextureReady.bind(this);
  49490. this.video.addEventListener("playing", this._setTextureReady);
  49491. };
  49492. VideoTexture.prototype._rebuild = function () {
  49493. this.update();
  49494. };
  49495. VideoTexture.prototype.update = function () {
  49496. var now = BABYLON.Tools.Now;
  49497. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  49498. return false;
  49499. }
  49500. this._lastUpdate = now;
  49501. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  49502. return true;
  49503. };
  49504. VideoTexture.prototype.dispose = function () {
  49505. _super.prototype.dispose.call(this);
  49506. this.video.removeEventListener("playing", this._setTextureReady);
  49507. };
  49508. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  49509. var video = document.createElement("video");
  49510. var constraintsDeviceId;
  49511. if (constraints && constraints.deviceId) {
  49512. constraintsDeviceId = {
  49513. exact: constraints.deviceId
  49514. };
  49515. }
  49516. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  49517. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  49518. if (navigator.getUserMedia) {
  49519. navigator.getUserMedia({
  49520. video: {
  49521. deviceId: constraintsDeviceId,
  49522. width: {
  49523. min: (constraints && constraints.minWidth) || 256,
  49524. max: (constraints && constraints.maxWidth) || 640
  49525. },
  49526. height: {
  49527. min: (constraints && constraints.minHeight) || 256,
  49528. max: (constraints && constraints.maxHeight) || 480
  49529. }
  49530. }
  49531. }, function (stream) {
  49532. if (video.mozSrcObject !== undefined) {
  49533. video.mozSrcObject = stream;
  49534. }
  49535. else {
  49536. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  49537. }
  49538. video.play();
  49539. if (onReady) {
  49540. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  49541. }
  49542. }, function (e) {
  49543. BABYLON.Tools.Error(e.name);
  49544. });
  49545. }
  49546. };
  49547. return VideoTexture;
  49548. }(BABYLON.Texture));
  49549. BABYLON.VideoTexture = VideoTexture;
  49550. })(BABYLON || (BABYLON = {}));
  49551. //# sourceMappingURL=babylon.videoTexture.js.map
  49552. var BABYLON;
  49553. (function (BABYLON) {
  49554. var RawTexture = /** @class */ (function (_super) {
  49555. __extends(RawTexture, _super);
  49556. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  49557. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49558. if (invertY === void 0) { invertY = false; }
  49559. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49560. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  49561. _this.format = format;
  49562. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  49563. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49564. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49565. return _this;
  49566. }
  49567. RawTexture.prototype.update = function (data) {
  49568. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  49569. };
  49570. // Statics
  49571. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49572. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49573. if (invertY === void 0) { invertY = false; }
  49574. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49575. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  49576. };
  49577. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49578. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49579. if (invertY === void 0) { invertY = false; }
  49580. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49581. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  49582. };
  49583. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49584. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49585. if (invertY === void 0) { invertY = false; }
  49586. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49587. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  49588. };
  49589. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49590. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49591. if (invertY === void 0) { invertY = false; }
  49592. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49593. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  49594. };
  49595. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49596. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49597. if (invertY === void 0) { invertY = false; }
  49598. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49599. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  49600. };
  49601. return RawTexture;
  49602. }(BABYLON.Texture));
  49603. BABYLON.RawTexture = RawTexture;
  49604. })(BABYLON || (BABYLON = {}));
  49605. //# sourceMappingURL=babylon.rawTexture.js.map
  49606. var BABYLON;
  49607. (function (BABYLON) {
  49608. var PostProcess = /** @class */ (function () {
  49609. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  49610. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  49611. if (defines === void 0) { defines = null; }
  49612. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  49613. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  49614. if (blockCompilation === void 0) { blockCompilation = false; }
  49615. this.name = name;
  49616. this.width = -1;
  49617. this.height = -1;
  49618. this.autoClear = true;
  49619. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  49620. /*
  49621. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  49622. Can only be used on a single postprocess or on the last one of a chain.
  49623. */
  49624. this.enablePixelPerfectMode = false;
  49625. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  49626. this.alwaysForcePOT = false;
  49627. this.samples = 1;
  49628. this.adaptScaleToCurrentViewport = false;
  49629. this._reusable = false;
  49630. this._textures = new BABYLON.SmartArray(2);
  49631. this._currentRenderTextureInd = 0;
  49632. this._scaleRatio = new BABYLON.Vector2(1, 1);
  49633. this._texelSize = BABYLON.Vector2.Zero();
  49634. // Events
  49635. /**
  49636. * An event triggered when the postprocess is activated.
  49637. * @type {BABYLON.Observable}
  49638. */
  49639. this.onActivateObservable = new BABYLON.Observable();
  49640. /**
  49641. * An event triggered when the postprocess changes its size.
  49642. * @type {BABYLON.Observable}
  49643. */
  49644. this.onSizeChangedObservable = new BABYLON.Observable();
  49645. /**
  49646. * An event triggered when the postprocess applies its effect.
  49647. * @type {BABYLON.Observable}
  49648. */
  49649. this.onApplyObservable = new BABYLON.Observable();
  49650. /**
  49651. * An event triggered before rendering the postprocess
  49652. * @type {BABYLON.Observable}
  49653. */
  49654. this.onBeforeRenderObservable = new BABYLON.Observable();
  49655. /**
  49656. * An event triggered after rendering the postprocess
  49657. * @type {BABYLON.Observable}
  49658. */
  49659. this.onAfterRenderObservable = new BABYLON.Observable();
  49660. if (camera != null) {
  49661. this._camera = camera;
  49662. this._scene = camera.getScene();
  49663. camera.attachPostProcess(this);
  49664. this._engine = this._scene.getEngine();
  49665. this._scene.postProcesses.push(this);
  49666. }
  49667. else if (engine) {
  49668. this._engine = engine;
  49669. this._engine.postProcesses.push(this);
  49670. }
  49671. this._options = options;
  49672. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  49673. this._reusable = reusable || false;
  49674. this._textureType = textureType;
  49675. this._samplers = samplers || [];
  49676. this._samplers.push("textureSampler");
  49677. this._fragmentUrl = fragmentUrl;
  49678. this._vertexUrl = vertexUrl;
  49679. this._parameters = parameters || [];
  49680. this._parameters.push("scale");
  49681. this._indexParameters = indexParameters;
  49682. if (!blockCompilation) {
  49683. this.updateEffect(defines);
  49684. }
  49685. }
  49686. Object.defineProperty(PostProcess.prototype, "onActivate", {
  49687. set: function (callback) {
  49688. if (this._onActivateObserver) {
  49689. this.onActivateObservable.remove(this._onActivateObserver);
  49690. }
  49691. this._onActivateObserver = this.onActivateObservable.add(callback);
  49692. },
  49693. enumerable: true,
  49694. configurable: true
  49695. });
  49696. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  49697. set: function (callback) {
  49698. if (this._onSizeChangedObserver) {
  49699. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  49700. }
  49701. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  49702. },
  49703. enumerable: true,
  49704. configurable: true
  49705. });
  49706. Object.defineProperty(PostProcess.prototype, "onApply", {
  49707. set: function (callback) {
  49708. if (this._onApplyObserver) {
  49709. this.onApplyObservable.remove(this._onApplyObserver);
  49710. }
  49711. this._onApplyObserver = this.onApplyObservable.add(callback);
  49712. },
  49713. enumerable: true,
  49714. configurable: true
  49715. });
  49716. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  49717. set: function (callback) {
  49718. if (this._onBeforeRenderObserver) {
  49719. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  49720. }
  49721. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  49722. },
  49723. enumerable: true,
  49724. configurable: true
  49725. });
  49726. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  49727. set: function (callback) {
  49728. if (this._onAfterRenderObserver) {
  49729. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  49730. }
  49731. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  49732. },
  49733. enumerable: true,
  49734. configurable: true
  49735. });
  49736. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  49737. get: function () {
  49738. return this._textures.data[this._currentRenderTextureInd];
  49739. },
  49740. set: function (value) {
  49741. this._forcedOutputTexture = value;
  49742. },
  49743. enumerable: true,
  49744. configurable: true
  49745. });
  49746. PostProcess.prototype.getCamera = function () {
  49747. return this._camera;
  49748. };
  49749. Object.defineProperty(PostProcess.prototype, "texelSize", {
  49750. get: function () {
  49751. if (this._shareOutputWithPostProcess) {
  49752. return this._shareOutputWithPostProcess.texelSize;
  49753. }
  49754. if (this._forcedOutputTexture) {
  49755. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  49756. }
  49757. return this._texelSize;
  49758. },
  49759. enumerable: true,
  49760. configurable: true
  49761. });
  49762. PostProcess.prototype.getEngine = function () {
  49763. return this._engine;
  49764. };
  49765. PostProcess.prototype.getEffect = function () {
  49766. return this._effect;
  49767. };
  49768. PostProcess.prototype.shareOutputWith = function (postProcess) {
  49769. this._disposeTextures();
  49770. this._shareOutputWithPostProcess = postProcess;
  49771. return this;
  49772. };
  49773. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  49774. if (defines === void 0) { defines = null; }
  49775. if (uniforms === void 0) { uniforms = null; }
  49776. if (samplers === void 0) { samplers = null; }
  49777. 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);
  49778. };
  49779. PostProcess.prototype.isReusable = function () {
  49780. return this._reusable;
  49781. };
  49782. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  49783. PostProcess.prototype.markTextureDirty = function () {
  49784. this.width = -1;
  49785. };
  49786. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  49787. var _this = this;
  49788. if (sourceTexture === void 0) { sourceTexture = null; }
  49789. camera = camera || this._camera;
  49790. var scene = camera.getScene();
  49791. var engine = scene.getEngine();
  49792. var maxSize = engine.getCaps().maxTextureSize;
  49793. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  49794. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  49795. var desiredWidth = (this._options.width || requiredWidth);
  49796. var desiredHeight = this._options.height || requiredHeight;
  49797. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  49798. if (this.adaptScaleToCurrentViewport) {
  49799. var currentViewport = engine.currentViewport;
  49800. if (currentViewport) {
  49801. desiredWidth *= currentViewport.width;
  49802. desiredHeight *= currentViewport.height;
  49803. }
  49804. }
  49805. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  49806. if (!this._options.width) {
  49807. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  49808. }
  49809. if (!this._options.height) {
  49810. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  49811. }
  49812. }
  49813. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  49814. if (this._textures.length > 0) {
  49815. for (var i = 0; i < this._textures.length; i++) {
  49816. this._engine._releaseTexture(this._textures.data[i]);
  49817. }
  49818. this._textures.reset();
  49819. }
  49820. this.width = desiredWidth;
  49821. this.height = desiredHeight;
  49822. var textureSize = { width: this.width, height: this.height };
  49823. var textureOptions = {
  49824. generateMipMaps: false,
  49825. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  49826. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  49827. samplingMode: this.renderTargetSamplingMode,
  49828. type: this._textureType
  49829. };
  49830. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  49831. if (this._reusable) {
  49832. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  49833. }
  49834. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  49835. this.onSizeChangedObservable.notifyObservers(this);
  49836. }
  49837. this._textures.forEach(function (texture) {
  49838. if (texture.samples !== _this.samples) {
  49839. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  49840. }
  49841. });
  49842. }
  49843. var target;
  49844. if (this._shareOutputWithPostProcess) {
  49845. target = this._shareOutputWithPostProcess.outputTexture;
  49846. }
  49847. else if (this._forcedOutputTexture) {
  49848. target = this._forcedOutputTexture;
  49849. this.width = this._forcedOutputTexture.width;
  49850. this.height = this._forcedOutputTexture.height;
  49851. }
  49852. else {
  49853. target = this.outputTexture;
  49854. }
  49855. if (this.enablePixelPerfectMode) {
  49856. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  49857. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  49858. }
  49859. else {
  49860. this._scaleRatio.copyFromFloats(1, 1);
  49861. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  49862. }
  49863. this.onActivateObservable.notifyObservers(camera);
  49864. // Clear
  49865. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  49866. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  49867. }
  49868. if (this._reusable) {
  49869. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  49870. }
  49871. };
  49872. Object.defineProperty(PostProcess.prototype, "isSupported", {
  49873. get: function () {
  49874. return this._effect.isSupported;
  49875. },
  49876. enumerable: true,
  49877. configurable: true
  49878. });
  49879. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  49880. get: function () {
  49881. if (this._shareOutputWithPostProcess) {
  49882. return this._shareOutputWithPostProcess.aspectRatio;
  49883. }
  49884. if (this._forcedOutputTexture) {
  49885. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  49886. }
  49887. return this.width / this.height;
  49888. },
  49889. enumerable: true,
  49890. configurable: true
  49891. });
  49892. PostProcess.prototype.apply = function () {
  49893. // Check
  49894. if (!this._effect || !this._effect.isReady())
  49895. return null;
  49896. // States
  49897. this._engine.enableEffect(this._effect);
  49898. this._engine.setState(false);
  49899. this._engine.setDepthBuffer(false);
  49900. this._engine.setDepthWrite(false);
  49901. // Alpha
  49902. this._engine.setAlphaMode(this.alphaMode);
  49903. if (this.alphaConstants) {
  49904. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  49905. }
  49906. // Texture
  49907. var source;
  49908. if (this._shareOutputWithPostProcess) {
  49909. source = this._shareOutputWithPostProcess.outputTexture;
  49910. }
  49911. else if (this._forcedOutputTexture) {
  49912. source = this._forcedOutputTexture;
  49913. }
  49914. else {
  49915. source = this.outputTexture;
  49916. }
  49917. this._effect._bindTexture("textureSampler", source);
  49918. // Parameters
  49919. this._effect.setVector2("scale", this._scaleRatio);
  49920. this.onApplyObservable.notifyObservers(this._effect);
  49921. return this._effect;
  49922. };
  49923. PostProcess.prototype._disposeTextures = function () {
  49924. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  49925. return;
  49926. }
  49927. if (this._textures.length > 0) {
  49928. for (var i = 0; i < this._textures.length; i++) {
  49929. this._engine._releaseTexture(this._textures.data[i]);
  49930. }
  49931. }
  49932. this._textures.dispose();
  49933. };
  49934. PostProcess.prototype.dispose = function (camera) {
  49935. camera = camera || this._camera;
  49936. this._disposeTextures();
  49937. if (this._scene) {
  49938. var index_1 = this._scene.postProcesses.indexOf(this);
  49939. if (index_1 !== -1) {
  49940. this._scene.postProcesses.splice(index_1, 1);
  49941. }
  49942. }
  49943. else {
  49944. var index_2 = this._engine.postProcesses.indexOf(this);
  49945. if (index_2 !== -1) {
  49946. this._engine.postProcesses.splice(index_2, 1);
  49947. }
  49948. }
  49949. if (!camera) {
  49950. return;
  49951. }
  49952. camera.detachPostProcess(this);
  49953. var index = camera._postProcesses.indexOf(this);
  49954. if (index === 0 && camera._postProcesses.length > 0) {
  49955. this._camera._postProcesses[0].markTextureDirty();
  49956. }
  49957. this.onActivateObservable.clear();
  49958. this.onAfterRenderObservable.clear();
  49959. this.onApplyObservable.clear();
  49960. this.onBeforeRenderObservable.clear();
  49961. this.onSizeChangedObservable.clear();
  49962. };
  49963. return PostProcess;
  49964. }());
  49965. BABYLON.PostProcess = PostProcess;
  49966. })(BABYLON || (BABYLON = {}));
  49967. //# sourceMappingURL=babylon.postProcess.js.map
  49968. var BABYLON;
  49969. (function (BABYLON) {
  49970. var PassPostProcess = /** @class */ (function (_super) {
  49971. __extends(PassPostProcess, _super);
  49972. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  49973. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  49974. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  49975. }
  49976. return PassPostProcess;
  49977. }(BABYLON.PostProcess));
  49978. BABYLON.PassPostProcess = PassPostProcess;
  49979. })(BABYLON || (BABYLON = {}));
  49980. //# sourceMappingURL=babylon.passPostProcess.js.map
  49981. var BABYLON;
  49982. (function (BABYLON) {
  49983. var ShadowGenerator = /** @class */ (function () {
  49984. /**
  49985. * Creates a ShadowGenerator object.
  49986. * A ShadowGenerator is the required tool to use the shadows.
  49987. * Each light casting shadows needs to use its own ShadowGenerator.
  49988. * Required parameters :
  49989. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  49990. * - `light`: the light object generating the shadows.
  49991. * - `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.
  49992. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  49993. */
  49994. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  49995. // Members
  49996. this._bias = 0.00005;
  49997. this._blurBoxOffset = 1;
  49998. this._blurScale = 2;
  49999. this._blurKernel = 1;
  50000. this._useKernelBlur = false;
  50001. this._filter = ShadowGenerator.FILTER_NONE;
  50002. this._darkness = 0;
  50003. this._transparencyShadow = false;
  50004. /**
  50005. * Controls the extent to which the shadows fade out at the edge of the frustum
  50006. * Used only by directionals and spots
  50007. */
  50008. this.frustumEdgeFalloff = 0;
  50009. this.forceBackFacesOnly = false;
  50010. this._lightDirection = BABYLON.Vector3.Zero();
  50011. this._viewMatrix = BABYLON.Matrix.Zero();
  50012. this._projectionMatrix = BABYLON.Matrix.Zero();
  50013. this._transformMatrix = BABYLON.Matrix.Zero();
  50014. this._currentFaceIndex = 0;
  50015. this._currentFaceIndexCache = 0;
  50016. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  50017. this._mapSize = mapSize;
  50018. this._light = light;
  50019. this._scene = light.getScene();
  50020. light._shadowGenerator = this;
  50021. // Texture type fallback from float to int if not supported.
  50022. var caps = this._scene.getEngine().getCaps();
  50023. if (!useFullFloatFirst) {
  50024. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  50025. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50026. }
  50027. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  50028. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  50029. }
  50030. else {
  50031. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  50032. }
  50033. }
  50034. else {
  50035. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  50036. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  50037. }
  50038. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  50039. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50040. }
  50041. else {
  50042. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  50043. }
  50044. }
  50045. this._initializeGenerator();
  50046. }
  50047. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  50048. // Static
  50049. get: function () {
  50050. return ShadowGenerator._FILTER_NONE;
  50051. },
  50052. enumerable: true,
  50053. configurable: true
  50054. });
  50055. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  50056. get: function () {
  50057. return ShadowGenerator._FILTER_POISSONSAMPLING;
  50058. },
  50059. enumerable: true,
  50060. configurable: true
  50061. });
  50062. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  50063. get: function () {
  50064. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  50065. },
  50066. enumerable: true,
  50067. configurable: true
  50068. });
  50069. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  50070. get: function () {
  50071. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  50072. },
  50073. enumerable: true,
  50074. configurable: true
  50075. });
  50076. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  50077. get: function () {
  50078. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  50079. },
  50080. enumerable: true,
  50081. configurable: true
  50082. });
  50083. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  50084. get: function () {
  50085. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  50086. },
  50087. enumerable: true,
  50088. configurable: true
  50089. });
  50090. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  50091. get: function () {
  50092. return this._bias;
  50093. },
  50094. set: function (bias) {
  50095. this._bias = bias;
  50096. },
  50097. enumerable: true,
  50098. configurable: true
  50099. });
  50100. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  50101. get: function () {
  50102. return this._blurBoxOffset;
  50103. },
  50104. set: function (value) {
  50105. if (this._blurBoxOffset === value) {
  50106. return;
  50107. }
  50108. this._blurBoxOffset = value;
  50109. this._disposeBlurPostProcesses();
  50110. },
  50111. enumerable: true,
  50112. configurable: true
  50113. });
  50114. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  50115. get: function () {
  50116. return this._blurScale;
  50117. },
  50118. set: function (value) {
  50119. if (this._blurScale === value) {
  50120. return;
  50121. }
  50122. this._blurScale = value;
  50123. this._disposeBlurPostProcesses();
  50124. },
  50125. enumerable: true,
  50126. configurable: true
  50127. });
  50128. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  50129. get: function () {
  50130. return this._blurKernel;
  50131. },
  50132. set: function (value) {
  50133. if (this._blurKernel === value) {
  50134. return;
  50135. }
  50136. this._blurKernel = value;
  50137. this._disposeBlurPostProcesses();
  50138. },
  50139. enumerable: true,
  50140. configurable: true
  50141. });
  50142. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  50143. get: function () {
  50144. return this._useKernelBlur;
  50145. },
  50146. set: function (value) {
  50147. if (this._useKernelBlur === value) {
  50148. return;
  50149. }
  50150. this._useKernelBlur = value;
  50151. this._disposeBlurPostProcesses();
  50152. },
  50153. enumerable: true,
  50154. configurable: true
  50155. });
  50156. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  50157. get: function () {
  50158. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  50159. },
  50160. set: function (value) {
  50161. this._depthScale = value;
  50162. },
  50163. enumerable: true,
  50164. configurable: true
  50165. });
  50166. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  50167. get: function () {
  50168. return this._filter;
  50169. },
  50170. set: function (value) {
  50171. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  50172. if (this._light.needCube()) {
  50173. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  50174. this.useExponentialShadowMap = true;
  50175. return;
  50176. }
  50177. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  50178. this.useCloseExponentialShadowMap = true;
  50179. return;
  50180. }
  50181. }
  50182. if (this._filter === value) {
  50183. return;
  50184. }
  50185. this._filter = value;
  50186. this._disposeBlurPostProcesses();
  50187. this._applyFilterValues();
  50188. this._light._markMeshesAsLightDirty();
  50189. },
  50190. enumerable: true,
  50191. configurable: true
  50192. });
  50193. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  50194. get: function () {
  50195. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  50196. },
  50197. set: function (value) {
  50198. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  50199. return;
  50200. }
  50201. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  50202. },
  50203. enumerable: true,
  50204. configurable: true
  50205. });
  50206. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  50207. get: function () {
  50208. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  50209. return this.useExponentialShadowMap;
  50210. },
  50211. set: function (value) {
  50212. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  50213. this.useExponentialShadowMap = value;
  50214. },
  50215. enumerable: true,
  50216. configurable: true
  50217. });
  50218. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  50219. get: function () {
  50220. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  50221. return this.useBlurExponentialShadowMap;
  50222. },
  50223. set: function (value) {
  50224. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  50225. this.useBlurExponentialShadowMap = value;
  50226. },
  50227. enumerable: true,
  50228. configurable: true
  50229. });
  50230. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  50231. get: function () {
  50232. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  50233. },
  50234. set: function (value) {
  50235. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  50236. return;
  50237. }
  50238. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  50239. },
  50240. enumerable: true,
  50241. configurable: true
  50242. });
  50243. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  50244. get: function () {
  50245. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  50246. },
  50247. set: function (value) {
  50248. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  50249. return;
  50250. }
  50251. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  50252. },
  50253. enumerable: true,
  50254. configurable: true
  50255. });
  50256. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  50257. get: function () {
  50258. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  50259. },
  50260. set: function (value) {
  50261. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  50262. return;
  50263. }
  50264. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  50265. },
  50266. enumerable: true,
  50267. configurable: true
  50268. });
  50269. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  50270. get: function () {
  50271. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  50272. },
  50273. set: function (value) {
  50274. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  50275. return;
  50276. }
  50277. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  50278. },
  50279. enumerable: true,
  50280. configurable: true
  50281. });
  50282. /**
  50283. * Returns the darkness value (float).
  50284. */
  50285. ShadowGenerator.prototype.getDarkness = function () {
  50286. return this._darkness;
  50287. };
  50288. /**
  50289. * Sets the ShadowGenerator darkness value (float <= 1.0).
  50290. * Returns the ShadowGenerator.
  50291. */
  50292. ShadowGenerator.prototype.setDarkness = function (darkness) {
  50293. if (darkness >= 1.0)
  50294. this._darkness = 1.0;
  50295. else if (darkness <= 0.0)
  50296. this._darkness = 0.0;
  50297. else
  50298. this._darkness = darkness;
  50299. return this;
  50300. };
  50301. /**
  50302. * Sets the ability to have transparent shadow (boolean).
  50303. * Returns the ShadowGenerator.
  50304. */
  50305. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  50306. this._transparencyShadow = hasShadow;
  50307. return this;
  50308. };
  50309. /**
  50310. * Returns a RenderTargetTexture object : the shadow map texture.
  50311. */
  50312. ShadowGenerator.prototype.getShadowMap = function () {
  50313. return this._shadowMap;
  50314. };
  50315. /**
  50316. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  50317. */
  50318. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  50319. if (this._shadowMap2) {
  50320. return this._shadowMap2;
  50321. }
  50322. return this._shadowMap;
  50323. };
  50324. /**
  50325. * Helper function to add a mesh and its descendants to the list of shadow casters
  50326. * @param mesh Mesh to add
  50327. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  50328. */
  50329. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  50330. if (includeDescendants === void 0) { includeDescendants = true; }
  50331. if (!this._shadowMap) {
  50332. return this;
  50333. }
  50334. if (!this._shadowMap.renderList) {
  50335. this._shadowMap.renderList = [];
  50336. }
  50337. this._shadowMap.renderList.push(mesh);
  50338. if (includeDescendants) {
  50339. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  50340. }
  50341. return this;
  50342. var _a;
  50343. };
  50344. /**
  50345. * Helper function to remove a mesh and its descendants from the list of shadow casters
  50346. * @param mesh Mesh to remove
  50347. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  50348. */
  50349. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  50350. if (includeDescendants === void 0) { includeDescendants = true; }
  50351. if (!this._shadowMap || !this._shadowMap.renderList) {
  50352. return this;
  50353. }
  50354. var index = this._shadowMap.renderList.indexOf(mesh);
  50355. if (index !== -1) {
  50356. this._shadowMap.renderList.splice(index, 1);
  50357. }
  50358. if (includeDescendants) {
  50359. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  50360. var child = _a[_i];
  50361. this.removeShadowCaster(child);
  50362. }
  50363. }
  50364. return this;
  50365. };
  50366. /**
  50367. * Returns the associated light object.
  50368. */
  50369. ShadowGenerator.prototype.getLight = function () {
  50370. return this._light;
  50371. };
  50372. ShadowGenerator.prototype._initializeGenerator = function () {
  50373. this._light._markMeshesAsLightDirty();
  50374. this._initializeShadowMap();
  50375. };
  50376. ShadowGenerator.prototype._initializeShadowMap = function () {
  50377. var _this = this;
  50378. // Render target
  50379. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  50380. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50381. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50382. this._shadowMap.anisotropicFilteringLevel = 1;
  50383. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  50384. this._shadowMap.renderParticles = false;
  50385. this._shadowMap.ignoreCameraViewport = true;
  50386. // Record Face Index before render.
  50387. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  50388. _this._currentFaceIndex = faceIndex;
  50389. });
  50390. // Custom render function.
  50391. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  50392. // Blur if required afer render.
  50393. this._shadowMap.onAfterUnbindObservable.add(function () {
  50394. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  50395. return;
  50396. }
  50397. if (!_this._blurPostProcesses || !_this._blurPostProcesses.length) {
  50398. _this._initializeBlurRTTAndPostProcesses();
  50399. }
  50400. var shadowMap = _this.getShadowMapForRendering();
  50401. if (shadowMap) {
  50402. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  50403. }
  50404. });
  50405. // Clear according to the chosen filter.
  50406. this._shadowMap.onClearObservable.add(function (engine) {
  50407. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  50408. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  50409. }
  50410. else {
  50411. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  50412. }
  50413. });
  50414. };
  50415. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  50416. var _this = this;
  50417. var engine = this._scene.getEngine();
  50418. var targetSize = this._mapSize / this.blurScale;
  50419. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  50420. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  50421. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50422. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50423. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  50424. }
  50425. if (this.useKernelBlur) {
  50426. 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);
  50427. this._kernelBlurXPostprocess.width = targetSize;
  50428. this._kernelBlurXPostprocess.height = targetSize;
  50429. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  50430. effect.setTexture("textureSampler", _this._shadowMap);
  50431. });
  50432. 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);
  50433. this._kernelBlurXPostprocess.autoClear = false;
  50434. this._kernelBlurYPostprocess.autoClear = false;
  50435. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  50436. this._kernelBlurXPostprocess.packedFloat = true;
  50437. this._kernelBlurYPostprocess.packedFloat = true;
  50438. }
  50439. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  50440. }
  50441. else {
  50442. 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);
  50443. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  50444. effect.setFloat2("screenSize", targetSize, targetSize);
  50445. effect.setTexture("textureSampler", _this._shadowMap);
  50446. });
  50447. this._boxBlurPostprocess.autoClear = false;
  50448. this._blurPostProcesses = [this._boxBlurPostprocess];
  50449. }
  50450. };
  50451. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  50452. var index;
  50453. var engine = this._scene.getEngine();
  50454. if (depthOnlySubMeshes.length) {
  50455. engine.setColorWrite(false);
  50456. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  50457. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  50458. }
  50459. engine.setColorWrite(true);
  50460. }
  50461. for (index = 0; index < opaqueSubMeshes.length; index++) {
  50462. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  50463. }
  50464. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  50465. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  50466. }
  50467. if (this._transparencyShadow) {
  50468. for (index = 0; index < transparentSubMeshes.length; index++) {
  50469. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  50470. }
  50471. }
  50472. };
  50473. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  50474. var _this = this;
  50475. var mesh = subMesh.getRenderingMesh();
  50476. var scene = this._scene;
  50477. var engine = scene.getEngine();
  50478. // Culling
  50479. engine.setState(subMesh.getMaterial().backFaceCulling);
  50480. // Managing instances
  50481. var batch = mesh._getInstancesRenderList(subMesh._id);
  50482. if (batch.mustReturn) {
  50483. return;
  50484. }
  50485. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  50486. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  50487. engine.enableEffect(this._effect);
  50488. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  50489. var material = subMesh.getMaterial();
  50490. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  50491. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  50492. this._effect.setVector3("lightPosition", this.getLight().position);
  50493. if (scene.activeCamera) {
  50494. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  50495. }
  50496. // Alpha test
  50497. if (material && material.needAlphaTesting()) {
  50498. var alphaTexture = material.getAlphaTestTexture();
  50499. if (alphaTexture) {
  50500. this._effect.setTexture("diffuseSampler", alphaTexture);
  50501. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  50502. }
  50503. }
  50504. // Bones
  50505. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50506. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  50507. }
  50508. if (this.forceBackFacesOnly) {
  50509. engine.setState(true, 0, false, true);
  50510. }
  50511. // Draw
  50512. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  50513. if (this.forceBackFacesOnly) {
  50514. engine.setState(true, 0, false, false);
  50515. }
  50516. }
  50517. else {
  50518. // Need to reset refresh rate of the shadowMap
  50519. if (this._shadowMap) {
  50520. this._shadowMap.resetRefreshCounter();
  50521. }
  50522. }
  50523. };
  50524. ShadowGenerator.prototype._applyFilterValues = function () {
  50525. if (!this._shadowMap) {
  50526. return;
  50527. }
  50528. if (this.filter === ShadowGenerator.FILTER_NONE) {
  50529. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  50530. }
  50531. else {
  50532. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  50533. }
  50534. };
  50535. /**
  50536. * Force shader compilation including textures ready check
  50537. */
  50538. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  50539. var _this = this;
  50540. var shadowMap = this.getShadowMap();
  50541. if (!shadowMap) {
  50542. return;
  50543. }
  50544. var subMeshes = new Array();
  50545. var currentIndex = 0;
  50546. var renderList = shadowMap.renderList;
  50547. if (!renderList) {
  50548. return;
  50549. }
  50550. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  50551. var mesh = renderList_1[_i];
  50552. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  50553. }
  50554. var checkReady = function () {
  50555. if (!_this._scene || !_this._scene.getEngine()) {
  50556. return;
  50557. }
  50558. var subMesh = subMeshes[currentIndex];
  50559. if (_this.isReady(subMesh, options ? options.useInstances : false)) {
  50560. currentIndex++;
  50561. if (currentIndex >= subMeshes.length) {
  50562. if (onCompiled) {
  50563. onCompiled(_this);
  50564. }
  50565. return;
  50566. }
  50567. }
  50568. setTimeout(checkReady, 16);
  50569. };
  50570. if (subMeshes.length > 0) {
  50571. checkReady();
  50572. }
  50573. };
  50574. /**
  50575. * Boolean : true when the ShadowGenerator is finally computed.
  50576. */
  50577. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  50578. var defines = [];
  50579. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  50580. defines.push("#define FLOAT");
  50581. }
  50582. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  50583. defines.push("#define ESM");
  50584. }
  50585. var attribs = [BABYLON.VertexBuffer.PositionKind];
  50586. var mesh = subMesh.getMesh();
  50587. var material = subMesh.getMaterial();
  50588. // Alpha test
  50589. if (material && material.needAlphaTesting()) {
  50590. var alphaTexture = material.getAlphaTestTexture();
  50591. if (alphaTexture) {
  50592. defines.push("#define ALPHATEST");
  50593. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50594. attribs.push(BABYLON.VertexBuffer.UVKind);
  50595. defines.push("#define UV1");
  50596. }
  50597. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  50598. if (alphaTexture.coordinatesIndex === 1) {
  50599. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  50600. defines.push("#define UV2");
  50601. }
  50602. }
  50603. }
  50604. }
  50605. // Bones
  50606. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50607. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  50608. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  50609. if (mesh.numBoneInfluencers > 4) {
  50610. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  50611. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  50612. }
  50613. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  50614. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  50615. }
  50616. else {
  50617. defines.push("#define NUM_BONE_INFLUENCERS 0");
  50618. }
  50619. // Instances
  50620. if (useInstances) {
  50621. defines.push("#define INSTANCES");
  50622. attribs.push("world0");
  50623. attribs.push("world1");
  50624. attribs.push("world2");
  50625. attribs.push("world3");
  50626. }
  50627. // Get correct effect
  50628. var join = defines.join("\n");
  50629. if (this._cachedDefines !== join) {
  50630. this._cachedDefines = join;
  50631. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  50632. }
  50633. return this._effect.isReady();
  50634. };
  50635. /**
  50636. * This creates the defines related to the standard BJS materials.
  50637. */
  50638. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  50639. var scene = this._scene;
  50640. var light = this._light;
  50641. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  50642. return;
  50643. }
  50644. defines["SHADOW" + lightIndex] = true;
  50645. if (this.usePoissonSampling) {
  50646. defines["SHADOWPCF" + lightIndex] = true;
  50647. }
  50648. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  50649. defines["SHADOWESM" + lightIndex] = true;
  50650. }
  50651. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  50652. defines["SHADOWCLOSEESM" + lightIndex] = true;
  50653. }
  50654. if (light.needCube()) {
  50655. defines["SHADOWCUBE" + lightIndex] = true;
  50656. }
  50657. };
  50658. /**
  50659. * This binds shadow lights related to the standard BJS materials.
  50660. * It implies the unifroms available on the materials are the standard BJS ones.
  50661. */
  50662. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  50663. var light = this._light;
  50664. var scene = this._scene;
  50665. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  50666. return;
  50667. }
  50668. var camera = scene.activeCamera;
  50669. if (!camera) {
  50670. return;
  50671. }
  50672. var shadowMap = this.getShadowMap();
  50673. if (!shadowMap) {
  50674. return;
  50675. }
  50676. if (!light.needCube()) {
  50677. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  50678. }
  50679. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  50680. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  50681. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  50682. };
  50683. // Methods
  50684. /**
  50685. * Returns a Matrix object : the updated transformation matrix.
  50686. */
  50687. ShadowGenerator.prototype.getTransformMatrix = function () {
  50688. var scene = this._scene;
  50689. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  50690. return this._transformMatrix;
  50691. }
  50692. this._currentRenderID = scene.getRenderId();
  50693. this._currentFaceIndexCache = this._currentFaceIndex;
  50694. var lightPosition = this._light.position;
  50695. if (this._light.computeTransformedInformation()) {
  50696. lightPosition = this._light.transformedPosition;
  50697. }
  50698. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  50699. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  50700. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  50701. }
  50702. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  50703. this._cachedPosition = lightPosition.clone();
  50704. this._cachedDirection = this._lightDirection.clone();
  50705. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  50706. var shadowMap = this.getShadowMap();
  50707. if (shadowMap) {
  50708. var renderList = shadowMap.renderList;
  50709. if (renderList) {
  50710. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  50711. }
  50712. }
  50713. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  50714. }
  50715. return this._transformMatrix;
  50716. };
  50717. ShadowGenerator.prototype.recreateShadowMap = function () {
  50718. var shadowMap = this._shadowMap;
  50719. if (!shadowMap) {
  50720. return;
  50721. }
  50722. // Track render list.
  50723. var renderList = shadowMap.renderList;
  50724. // Clean up existing data.
  50725. this._disposeRTTandPostProcesses();
  50726. // Reinitializes.
  50727. this._initializeGenerator();
  50728. // Reaffect the filter to ensure a correct fallback if necessary.
  50729. this.filter = this.filter;
  50730. // Reaffect the filter.
  50731. this._applyFilterValues();
  50732. // Reaffect Render List.
  50733. shadowMap.renderList = renderList;
  50734. };
  50735. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  50736. if (this._shadowMap2) {
  50737. this._shadowMap2.dispose();
  50738. this._shadowMap2 = null;
  50739. }
  50740. if (this._downSamplePostprocess) {
  50741. this._downSamplePostprocess.dispose();
  50742. this._downSamplePostprocess = null;
  50743. }
  50744. if (this._boxBlurPostprocess) {
  50745. this._boxBlurPostprocess.dispose();
  50746. this._boxBlurPostprocess = null;
  50747. }
  50748. if (this._kernelBlurXPostprocess) {
  50749. this._kernelBlurXPostprocess.dispose();
  50750. this._kernelBlurXPostprocess = null;
  50751. }
  50752. if (this._kernelBlurYPostprocess) {
  50753. this._kernelBlurYPostprocess.dispose();
  50754. this._kernelBlurYPostprocess = null;
  50755. }
  50756. this._blurPostProcesses = [];
  50757. };
  50758. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  50759. if (this._shadowMap) {
  50760. this._shadowMap.dispose();
  50761. this._shadowMap = null;
  50762. }
  50763. this._disposeBlurPostProcesses();
  50764. };
  50765. /**
  50766. * Disposes the ShadowGenerator.
  50767. * Returns nothing.
  50768. */
  50769. ShadowGenerator.prototype.dispose = function () {
  50770. this._disposeRTTandPostProcesses();
  50771. if (this._light) {
  50772. this._light._shadowGenerator = null;
  50773. this._light._markMeshesAsLightDirty();
  50774. }
  50775. };
  50776. /**
  50777. * Serializes the ShadowGenerator and returns a serializationObject.
  50778. */
  50779. ShadowGenerator.prototype.serialize = function () {
  50780. var serializationObject = {};
  50781. var shadowMap = this.getShadowMap();
  50782. if (!shadowMap) {
  50783. return serializationObject;
  50784. }
  50785. serializationObject.lightId = this._light.id;
  50786. serializationObject.mapSize = shadowMap.getRenderSize();
  50787. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  50788. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  50789. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  50790. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  50791. serializationObject.usePoissonSampling = this.usePoissonSampling;
  50792. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  50793. serializationObject.depthScale = this.depthScale;
  50794. serializationObject.darkness = this.getDarkness();
  50795. serializationObject.blurBoxOffset = this.blurBoxOffset;
  50796. serializationObject.blurKernel = this.blurKernel;
  50797. serializationObject.blurScale = this.blurScale;
  50798. serializationObject.useKernelBlur = this.useKernelBlur;
  50799. serializationObject.transparencyShadow = this._transparencyShadow;
  50800. serializationObject.renderList = [];
  50801. if (shadowMap.renderList) {
  50802. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  50803. var mesh = shadowMap.renderList[meshIndex];
  50804. serializationObject.renderList.push(mesh.id);
  50805. }
  50806. }
  50807. return serializationObject;
  50808. };
  50809. /**
  50810. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  50811. */
  50812. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  50813. //casting to point light, as light is missing the position attr and typescript complains.
  50814. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  50815. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  50816. var shadowMap = shadowGenerator.getShadowMap();
  50817. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  50818. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  50819. meshes.forEach(function (mesh) {
  50820. if (!shadowMap) {
  50821. return;
  50822. }
  50823. if (!shadowMap.renderList) {
  50824. shadowMap.renderList = [];
  50825. }
  50826. shadowMap.renderList.push(mesh);
  50827. });
  50828. }
  50829. if (parsedShadowGenerator.usePoissonSampling) {
  50830. shadowGenerator.usePoissonSampling = true;
  50831. }
  50832. else if (parsedShadowGenerator.useExponentialShadowMap) {
  50833. shadowGenerator.useExponentialShadowMap = true;
  50834. }
  50835. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  50836. shadowGenerator.useBlurExponentialShadowMap = true;
  50837. }
  50838. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  50839. shadowGenerator.useCloseExponentialShadowMap = true;
  50840. }
  50841. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  50842. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  50843. }
  50844. else if (parsedShadowGenerator.useVarianceShadowMap) {
  50845. shadowGenerator.useExponentialShadowMap = true;
  50846. }
  50847. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  50848. shadowGenerator.useBlurExponentialShadowMap = true;
  50849. }
  50850. if (parsedShadowGenerator.depthScale) {
  50851. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  50852. }
  50853. if (parsedShadowGenerator.blurScale) {
  50854. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  50855. }
  50856. if (parsedShadowGenerator.blurBoxOffset) {
  50857. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  50858. }
  50859. if (parsedShadowGenerator.useKernelBlur) {
  50860. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  50861. }
  50862. if (parsedShadowGenerator.blurKernel) {
  50863. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  50864. }
  50865. if (parsedShadowGenerator.bias !== undefined) {
  50866. shadowGenerator.bias = parsedShadowGenerator.bias;
  50867. }
  50868. if (parsedShadowGenerator.darkness) {
  50869. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  50870. }
  50871. if (parsedShadowGenerator.transparencyShadow) {
  50872. shadowGenerator.setTransparencyShadow(true);
  50873. }
  50874. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  50875. return shadowGenerator;
  50876. };
  50877. ShadowGenerator._FILTER_NONE = 0;
  50878. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  50879. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  50880. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  50881. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  50882. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  50883. return ShadowGenerator;
  50884. }());
  50885. BABYLON.ShadowGenerator = ShadowGenerator;
  50886. })(BABYLON || (BABYLON = {}));
  50887. //# sourceMappingURL=babylon.shadowGenerator.js.map
  50888. var BABYLON;
  50889. (function (BABYLON) {
  50890. var DefaultLoadingScreen = /** @class */ (function () {
  50891. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  50892. if (_loadingText === void 0) { _loadingText = ""; }
  50893. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  50894. var _this = this;
  50895. this._renderingCanvas = _renderingCanvas;
  50896. this._loadingText = _loadingText;
  50897. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  50898. // Resize
  50899. this._resizeLoadingUI = function () {
  50900. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  50901. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  50902. if (!_this._loadingDiv) {
  50903. return;
  50904. }
  50905. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  50906. _this._loadingDiv.style.left = canvasRect.left + "px";
  50907. _this._loadingDiv.style.top = canvasRect.top + "px";
  50908. _this._loadingDiv.style.width = canvasRect.width + "px";
  50909. _this._loadingDiv.style.height = canvasRect.height + "px";
  50910. };
  50911. }
  50912. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  50913. if (this._loadingDiv) {
  50914. // Do not add a loading screen if there is already one
  50915. return;
  50916. }
  50917. this._loadingDiv = document.createElement("div");
  50918. this._loadingDiv.id = "babylonjsLoadingDiv";
  50919. this._loadingDiv.style.opacity = "0";
  50920. this._loadingDiv.style.transition = "opacity 1.5s ease";
  50921. this._loadingDiv.style.pointerEvents = "none";
  50922. // Loading text
  50923. this._loadingTextDiv = document.createElement("div");
  50924. this._loadingTextDiv.style.position = "absolute";
  50925. this._loadingTextDiv.style.left = "0";
  50926. this._loadingTextDiv.style.top = "50%";
  50927. this._loadingTextDiv.style.marginTop = "80px";
  50928. this._loadingTextDiv.style.width = "100%";
  50929. this._loadingTextDiv.style.height = "20px";
  50930. this._loadingTextDiv.style.fontFamily = "Arial";
  50931. this._loadingTextDiv.style.fontSize = "14px";
  50932. this._loadingTextDiv.style.color = "white";
  50933. this._loadingTextDiv.style.textAlign = "center";
  50934. this._loadingTextDiv.innerHTML = "Loading";
  50935. this._loadingDiv.appendChild(this._loadingTextDiv);
  50936. //set the predefined text
  50937. this._loadingTextDiv.innerHTML = this._loadingText;
  50938. // Generating keyframes
  50939. var style = document.createElement('style');
  50940. style.type = 'text/css';
  50941. 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 }";
  50942. style.innerHTML = keyFrames;
  50943. document.getElementsByTagName('head')[0].appendChild(style);
  50944. // Loading img
  50945. var imgBack = new Image();
  50946. 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";
  50947. imgBack.style.position = "absolute";
  50948. imgBack.style.left = "50%";
  50949. imgBack.style.top = "50%";
  50950. imgBack.style.marginLeft = "-60px";
  50951. imgBack.style.marginTop = "-60px";
  50952. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  50953. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  50954. imgBack.style.transformOrigin = "50% 50%";
  50955. imgBack.style.webkitTransformOrigin = "50% 50%";
  50956. this._loadingDiv.appendChild(imgBack);
  50957. this._resizeLoadingUI();
  50958. window.addEventListener("resize", this._resizeLoadingUI);
  50959. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  50960. document.body.appendChild(this._loadingDiv);
  50961. this._loadingDiv.style.opacity = "1";
  50962. };
  50963. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  50964. var _this = this;
  50965. if (!this._loadingDiv) {
  50966. return;
  50967. }
  50968. var onTransitionEnd = function () {
  50969. if (!_this._loadingDiv) {
  50970. return;
  50971. }
  50972. document.body.removeChild(_this._loadingDiv);
  50973. window.removeEventListener("resize", _this._resizeLoadingUI);
  50974. _this._loadingDiv = null;
  50975. };
  50976. this._loadingDiv.style.opacity = "0";
  50977. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  50978. };
  50979. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  50980. set: function (text) {
  50981. this._loadingText = text;
  50982. if (this._loadingTextDiv) {
  50983. this._loadingTextDiv.innerHTML = this._loadingText;
  50984. }
  50985. },
  50986. enumerable: true,
  50987. configurable: true
  50988. });
  50989. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  50990. get: function () {
  50991. return this._loadingDivBackgroundColor;
  50992. },
  50993. set: function (color) {
  50994. this._loadingDivBackgroundColor = color;
  50995. if (!this._loadingDiv) {
  50996. return;
  50997. }
  50998. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  50999. },
  51000. enumerable: true,
  51001. configurable: true
  51002. });
  51003. return DefaultLoadingScreen;
  51004. }());
  51005. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  51006. })(BABYLON || (BABYLON = {}));
  51007. //# sourceMappingURL=babylon.loadingScreen.js.map
  51008. var BABYLON;
  51009. (function (BABYLON) {
  51010. var SceneLoader = /** @class */ (function () {
  51011. function SceneLoader() {
  51012. }
  51013. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  51014. get: function () {
  51015. return 0;
  51016. },
  51017. enumerable: true,
  51018. configurable: true
  51019. });
  51020. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  51021. get: function () {
  51022. return 1;
  51023. },
  51024. enumerable: true,
  51025. configurable: true
  51026. });
  51027. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  51028. get: function () {
  51029. return 2;
  51030. },
  51031. enumerable: true,
  51032. configurable: true
  51033. });
  51034. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  51035. get: function () {
  51036. return 3;
  51037. },
  51038. enumerable: true,
  51039. configurable: true
  51040. });
  51041. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  51042. get: function () {
  51043. return SceneLoader._ForceFullSceneLoadingForIncremental;
  51044. },
  51045. set: function (value) {
  51046. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  51047. },
  51048. enumerable: true,
  51049. configurable: true
  51050. });
  51051. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  51052. get: function () {
  51053. return SceneLoader._ShowLoadingScreen;
  51054. },
  51055. set: function (value) {
  51056. SceneLoader._ShowLoadingScreen = value;
  51057. },
  51058. enumerable: true,
  51059. configurable: true
  51060. });
  51061. Object.defineProperty(SceneLoader, "loggingLevel", {
  51062. get: function () {
  51063. return SceneLoader._loggingLevel;
  51064. },
  51065. set: function (value) {
  51066. SceneLoader._loggingLevel = value;
  51067. },
  51068. enumerable: true,
  51069. configurable: true
  51070. });
  51071. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  51072. get: function () {
  51073. return SceneLoader._CleanBoneMatrixWeights;
  51074. },
  51075. set: function (value) {
  51076. SceneLoader._CleanBoneMatrixWeights = value;
  51077. },
  51078. enumerable: true,
  51079. configurable: true
  51080. });
  51081. SceneLoader._getDefaultPlugin = function () {
  51082. return SceneLoader._registeredPlugins[".babylon"];
  51083. };
  51084. SceneLoader._getPluginForExtension = function (extension) {
  51085. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  51086. if (registeredPlugin) {
  51087. return registeredPlugin;
  51088. }
  51089. return SceneLoader._getDefaultPlugin();
  51090. };
  51091. SceneLoader._getPluginForDirectLoad = function (data) {
  51092. for (var extension in SceneLoader._registeredPlugins) {
  51093. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  51094. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  51095. return SceneLoader._registeredPlugins[extension];
  51096. }
  51097. }
  51098. return SceneLoader._getDefaultPlugin();
  51099. };
  51100. SceneLoader._getPluginForFilename = function (sceneFilename) {
  51101. if (sceneFilename.name) {
  51102. sceneFilename = sceneFilename.name;
  51103. }
  51104. var dotPosition = sceneFilename.lastIndexOf(".");
  51105. var queryStringPosition = sceneFilename.indexOf("?");
  51106. if (queryStringPosition === -1) {
  51107. queryStringPosition = sceneFilename.length;
  51108. }
  51109. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  51110. return SceneLoader._getPluginForExtension(extension);
  51111. };
  51112. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  51113. SceneLoader._getDirectLoad = function (sceneFilename) {
  51114. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  51115. return sceneFilename.substr(5);
  51116. }
  51117. return null;
  51118. };
  51119. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  51120. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  51121. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  51122. var plugin = registeredPlugin.plugin;
  51123. var useArrayBuffer = registeredPlugin.isBinary;
  51124. var database;
  51125. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  51126. var dataCallback = function (data) {
  51127. if (scene.isDisposed) {
  51128. onError("Scene has been disposed");
  51129. return;
  51130. }
  51131. scene.database = database;
  51132. try {
  51133. onSuccess(plugin, data);
  51134. }
  51135. catch (e) {
  51136. onError(null, e);
  51137. }
  51138. };
  51139. var manifestChecked = function (success) {
  51140. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  51141. if (request) {
  51142. onError(request.status + " " + request.statusText);
  51143. }
  51144. });
  51145. };
  51146. if (directLoad) {
  51147. dataCallback(directLoad);
  51148. return;
  51149. }
  51150. if (rootUrl.indexOf("file:") === -1) {
  51151. if (scene.getEngine().enableOfflineSupport) {
  51152. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  51153. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  51154. }
  51155. else {
  51156. manifestChecked(true);
  51157. }
  51158. }
  51159. else {
  51160. var fileOrString = sceneFilename;
  51161. if (fileOrString.name) {
  51162. BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  51163. }
  51164. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  51165. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  51166. }
  51167. else {
  51168. onError("Unable to find file named " + sceneFilename);
  51169. return;
  51170. }
  51171. }
  51172. };
  51173. // Public functions
  51174. SceneLoader.GetPluginForExtension = function (extension) {
  51175. return SceneLoader._getPluginForExtension(extension).plugin;
  51176. };
  51177. SceneLoader.RegisterPlugin = function (plugin) {
  51178. if (typeof plugin.extensions === "string") {
  51179. var extension = plugin.extensions;
  51180. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  51181. plugin: plugin,
  51182. isBinary: false
  51183. };
  51184. }
  51185. else {
  51186. var extensions = plugin.extensions;
  51187. Object.keys(extensions).forEach(function (extension) {
  51188. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  51189. plugin: plugin,
  51190. isBinary: extensions[extension].isBinary
  51191. };
  51192. });
  51193. }
  51194. };
  51195. /**
  51196. * Import meshes into a scene
  51197. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  51198. * @param rootUrl a string that defines the root url for scene and resources
  51199. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  51200. * @param scene the instance of BABYLON.Scene to append to
  51201. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  51202. * @param onProgress a callback with a progress event for each file being loaded
  51203. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  51204. */
  51205. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  51206. if (onSuccess === void 0) { onSuccess = null; }
  51207. if (onProgress === void 0) { onProgress = null; }
  51208. if (onError === void 0) { onError = null; }
  51209. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  51210. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  51211. return;
  51212. }
  51213. var loadingToken = {};
  51214. scene._addPendingData(loadingToken);
  51215. var errorHandler = function (message, exception) {
  51216. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  51217. if (onError) {
  51218. onError(scene, errorMessage, exception);
  51219. }
  51220. else {
  51221. BABYLON.Tools.Error(errorMessage);
  51222. // should the exception be thrown?
  51223. }
  51224. scene._removePendingData(loadingToken);
  51225. };
  51226. var progressHandler = function (event) {
  51227. if (onProgress) {
  51228. onProgress(event);
  51229. }
  51230. };
  51231. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  51232. if (plugin.importMesh) {
  51233. var syncedPlugin = plugin;
  51234. var meshes = new Array();
  51235. var particleSystems = new Array();
  51236. var skeletons = new Array();
  51237. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  51238. return;
  51239. }
  51240. if (onSuccess) {
  51241. // wrap onSuccess with try-catch to know if something went wrong.
  51242. try {
  51243. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  51244. onSuccess(meshes, particleSystems, skeletons);
  51245. scene._removePendingData(loadingToken);
  51246. }
  51247. catch (e) {
  51248. var message = 'Error in onSuccess callback.';
  51249. errorHandler(message, e);
  51250. }
  51251. }
  51252. }
  51253. else {
  51254. var asyncedPlugin = plugin;
  51255. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  51256. if (onSuccess) {
  51257. try {
  51258. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  51259. onSuccess(meshes, particleSystems, skeletons);
  51260. scene._removePendingData(loadingToken);
  51261. }
  51262. catch (e) {
  51263. var message = 'Error in onSuccess callback.';
  51264. errorHandler(message, e);
  51265. }
  51266. }
  51267. }, progressHandler, errorHandler);
  51268. }
  51269. }, progressHandler, errorHandler);
  51270. };
  51271. /**
  51272. * Load a scene
  51273. * @param rootUrl a string that defines the root url for scene and resources
  51274. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  51275. * @param engine is the instance of BABYLON.Engine to use to create the scene
  51276. * @param onSuccess a callback with the scene when import succeeds
  51277. * @param onProgress a callback with a progress event for each file being loaded
  51278. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  51279. */
  51280. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError) {
  51281. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError);
  51282. };
  51283. /**
  51284. * Append a scene
  51285. * @param rootUrl a string that defines the root url for scene and resources
  51286. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  51287. * @param scene is the instance of BABYLON.Scene to append to
  51288. * @param onSuccess a callback with the scene when import succeeds
  51289. * @param onProgress a callback with a progress event for each file being loaded
  51290. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  51291. */
  51292. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  51293. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  51294. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  51295. return;
  51296. }
  51297. if (SceneLoader.ShowLoadingScreen) {
  51298. scene.getEngine().displayLoadingUI();
  51299. }
  51300. var loadingToken = {};
  51301. scene._addPendingData(loadingToken);
  51302. var errorHandler = function (message, exception) {
  51303. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  51304. if (onError) {
  51305. onError(scene, errorMessage, exception);
  51306. }
  51307. else {
  51308. BABYLON.Tools.Error(errorMessage);
  51309. // should the exception be thrown?
  51310. }
  51311. scene._removePendingData(loadingToken);
  51312. scene.getEngine().hideLoadingUI();
  51313. };
  51314. var progressHandler = function (event) {
  51315. if (onProgress) {
  51316. onProgress(event);
  51317. }
  51318. };
  51319. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  51320. if (plugin.load) {
  51321. var syncedPlugin = plugin;
  51322. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  51323. return;
  51324. }
  51325. if (onSuccess) {
  51326. try {
  51327. onSuccess(scene);
  51328. }
  51329. catch (e) {
  51330. errorHandler("Error in onSuccess callback", e);
  51331. }
  51332. }
  51333. scene.loadingPluginName = plugin.name;
  51334. scene._removePendingData(loadingToken);
  51335. }
  51336. else {
  51337. var asyncedPlugin = plugin;
  51338. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  51339. if (onSuccess) {
  51340. onSuccess(scene);
  51341. }
  51342. scene.loadingPluginName = plugin.name;
  51343. scene._removePendingData(loadingToken);
  51344. }, progressHandler, errorHandler);
  51345. }
  51346. if (SceneLoader.ShowLoadingScreen) {
  51347. scene.executeWhenReady(function () {
  51348. scene.getEngine().hideLoadingUI();
  51349. });
  51350. }
  51351. }, progressHandler, errorHandler);
  51352. };
  51353. // Flags
  51354. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  51355. SceneLoader._ShowLoadingScreen = true;
  51356. SceneLoader._CleanBoneMatrixWeights = false;
  51357. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  51358. // Members
  51359. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  51360. SceneLoader._registeredPlugins = {};
  51361. return SceneLoader;
  51362. }());
  51363. BABYLON.SceneLoader = SceneLoader;
  51364. ;
  51365. })(BABYLON || (BABYLON = {}));
  51366. //# sourceMappingURL=babylon.sceneLoader.js.map
  51367. var BABYLON;
  51368. (function (BABYLON) {
  51369. var Internals;
  51370. (function (Internals) {
  51371. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  51372. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  51373. var parsedMaterial = parsedData.materials[index];
  51374. if (parsedMaterial.id === id) {
  51375. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  51376. }
  51377. }
  51378. return null;
  51379. };
  51380. var isDescendantOf = function (mesh, names, hierarchyIds) {
  51381. for (var i in names) {
  51382. if (mesh.name === names[i]) {
  51383. hierarchyIds.push(mesh.id);
  51384. return true;
  51385. }
  51386. }
  51387. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  51388. hierarchyIds.push(mesh.id);
  51389. return true;
  51390. }
  51391. return false;
  51392. };
  51393. var logOperation = function (operation, producer) {
  51394. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  51395. };
  51396. BABYLON.SceneLoader.RegisterPlugin({
  51397. name: "babylon.js",
  51398. extensions: ".babylon",
  51399. canDirectLoad: function (data) {
  51400. if (data.indexOf("babylon") !== -1) {
  51401. return true;
  51402. }
  51403. return false;
  51404. },
  51405. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  51406. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  51407. // when SceneLoader.debugLogging = true (default), or exception encountered.
  51408. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  51409. // and avoid problems with multiple concurrent .babylon loads.
  51410. var log = "importMesh has failed JSON parse";
  51411. try {
  51412. var parsedData = JSON.parse(data);
  51413. log = "";
  51414. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  51415. if (!meshesNames) {
  51416. meshesNames = null;
  51417. }
  51418. else if (!Array.isArray(meshesNames)) {
  51419. meshesNames = [meshesNames];
  51420. }
  51421. var hierarchyIds = new Array();
  51422. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  51423. var loadedSkeletonsIds = [];
  51424. var loadedMaterialsIds = [];
  51425. var index;
  51426. var cache;
  51427. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  51428. var parsedMesh = parsedData.meshes[index];
  51429. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  51430. if (meshesNames !== null) {
  51431. // Remove found mesh name from list.
  51432. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  51433. }
  51434. //Geometry?
  51435. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  51436. //does the file contain geometries?
  51437. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  51438. //find the correct geometry and add it to the scene
  51439. var found = false;
  51440. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  51441. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  51442. return;
  51443. }
  51444. else {
  51445. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  51446. if (parsedGeometryData.id === parsedMesh.geometryId) {
  51447. switch (geometryType) {
  51448. case "boxes":
  51449. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  51450. break;
  51451. case "spheres":
  51452. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  51453. break;
  51454. case "cylinders":
  51455. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  51456. break;
  51457. case "toruses":
  51458. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  51459. break;
  51460. case "grounds":
  51461. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  51462. break;
  51463. case "planes":
  51464. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  51465. break;
  51466. case "torusKnots":
  51467. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  51468. break;
  51469. case "vertexData":
  51470. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  51471. break;
  51472. }
  51473. found = true;
  51474. }
  51475. });
  51476. }
  51477. });
  51478. if (found === false) {
  51479. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  51480. }
  51481. }
  51482. }
  51483. // Material ?
  51484. if (parsedMesh.materialId) {
  51485. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  51486. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  51487. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  51488. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  51489. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  51490. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  51491. var subMatId = parsedMultiMaterial.materials[matIndex];
  51492. loadedMaterialsIds.push(subMatId);
  51493. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  51494. log += "\n\tMaterial " + mat.toString(fullDetails);
  51495. }
  51496. loadedMaterialsIds.push(parsedMultiMaterial.id);
  51497. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  51498. materialFound = true;
  51499. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  51500. break;
  51501. }
  51502. }
  51503. }
  51504. if (materialFound === false) {
  51505. loadedMaterialsIds.push(parsedMesh.materialId);
  51506. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  51507. if (!mat) {
  51508. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  51509. }
  51510. else {
  51511. log += "\n\tMaterial " + mat.toString(fullDetails);
  51512. }
  51513. }
  51514. }
  51515. // Skeleton ?
  51516. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  51517. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  51518. if (skeletonAlreadyLoaded === false) {
  51519. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  51520. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  51521. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  51522. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  51523. skeletons.push(skeleton);
  51524. loadedSkeletonsIds.push(parsedSkeleton.id);
  51525. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  51526. }
  51527. }
  51528. }
  51529. }
  51530. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  51531. meshes.push(mesh);
  51532. log += "\n\tMesh " + mesh.toString(fullDetails);
  51533. }
  51534. }
  51535. // Connecting parents
  51536. var currentMesh;
  51537. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  51538. currentMesh = scene.meshes[index];
  51539. if (currentMesh._waitingParentId) {
  51540. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  51541. currentMesh._waitingParentId = null;
  51542. }
  51543. }
  51544. // freeze and compute world matrix application
  51545. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  51546. currentMesh = scene.meshes[index];
  51547. if (currentMesh._waitingFreezeWorldMatrix) {
  51548. currentMesh.freezeWorldMatrix();
  51549. currentMesh._waitingFreezeWorldMatrix = null;
  51550. }
  51551. else {
  51552. currentMesh.computeWorldMatrix(true);
  51553. }
  51554. }
  51555. }
  51556. // Particles
  51557. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  51558. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  51559. var parsedParticleSystem = parsedData.particleSystems[index];
  51560. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  51561. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  51562. }
  51563. }
  51564. }
  51565. return true;
  51566. }
  51567. catch (err) {
  51568. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  51569. if (onError) {
  51570. onError(msg, err);
  51571. }
  51572. else {
  51573. BABYLON.Tools.Log(msg);
  51574. throw err;
  51575. }
  51576. }
  51577. finally {
  51578. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  51579. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  51580. }
  51581. }
  51582. return false;
  51583. },
  51584. load: function (scene, data, rootUrl, onError) {
  51585. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  51586. // when SceneLoader.debugLogging = true (default), or exception encountered.
  51587. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  51588. // and avoid problems with multiple concurrent .babylon loads.
  51589. var log = "importScene has failed JSON parse";
  51590. try {
  51591. var parsedData = JSON.parse(data);
  51592. log = "";
  51593. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  51594. // Scene
  51595. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  51596. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  51597. }
  51598. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  51599. scene.autoClear = parsedData.autoClear;
  51600. }
  51601. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  51602. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  51603. }
  51604. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  51605. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  51606. }
  51607. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  51608. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  51609. }
  51610. // Fog
  51611. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  51612. scene.fogMode = parsedData.fogMode;
  51613. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  51614. scene.fogStart = parsedData.fogStart;
  51615. scene.fogEnd = parsedData.fogEnd;
  51616. scene.fogDensity = parsedData.fogDensity;
  51617. log += "\tFog mode for scene: ";
  51618. switch (scene.fogMode) {
  51619. // getters not compiling, so using hardcoded
  51620. case 1:
  51621. log += "exp\n";
  51622. break;
  51623. case 2:
  51624. log += "exp2\n";
  51625. break;
  51626. case 3:
  51627. log += "linear\n";
  51628. break;
  51629. }
  51630. }
  51631. //Physics
  51632. if (parsedData.physicsEnabled) {
  51633. var physicsPlugin;
  51634. if (parsedData.physicsEngine === "cannon") {
  51635. physicsPlugin = new BABYLON.CannonJSPlugin();
  51636. }
  51637. else if (parsedData.physicsEngine === "oimo") {
  51638. physicsPlugin = new BABYLON.OimoJSPlugin();
  51639. }
  51640. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  51641. //else - default engine, which is currently oimo
  51642. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  51643. scene.enablePhysics(physicsGravity, physicsPlugin);
  51644. }
  51645. // Metadata
  51646. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  51647. scene.metadata = parsedData.metadata;
  51648. }
  51649. //collisions, if defined. otherwise, default is true
  51650. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  51651. scene.collisionsEnabled = parsedData.collisionsEnabled;
  51652. }
  51653. scene.workerCollisions = !!parsedData.workerCollisions;
  51654. var index;
  51655. var cache;
  51656. // Lights
  51657. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  51658. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  51659. var parsedLight = parsedData.lights[index];
  51660. var light = BABYLON.Light.Parse(parsedLight, scene);
  51661. if (light) {
  51662. log += (index === 0 ? "\n\tLights:" : "");
  51663. log += "\n\t\t" + light.toString(fullDetails);
  51664. }
  51665. }
  51666. }
  51667. // Animations
  51668. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  51669. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  51670. var parsedAnimation = parsedData.animations[index];
  51671. var animation = BABYLON.Animation.Parse(parsedAnimation);
  51672. scene.animations.push(animation);
  51673. log += (index === 0 ? "\n\tAnimations:" : "");
  51674. log += "\n\t\t" + animation.toString(fullDetails);
  51675. }
  51676. }
  51677. if (parsedData.autoAnimate) {
  51678. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  51679. }
  51680. // Materials
  51681. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  51682. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  51683. var parsedMaterial = parsedData.materials[index];
  51684. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  51685. log += (index === 0 ? "\n\tMaterials:" : "");
  51686. log += "\n\t\t" + mat.toString(fullDetails);
  51687. }
  51688. }
  51689. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  51690. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  51691. var parsedMultiMaterial = parsedData.multiMaterials[index];
  51692. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  51693. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  51694. log += "\n\t\t" + mmat.toString(fullDetails);
  51695. }
  51696. }
  51697. // Morph targets
  51698. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  51699. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  51700. var managerData = _a[_i];
  51701. BABYLON.MorphTargetManager.Parse(managerData, scene);
  51702. }
  51703. }
  51704. // Skeletons
  51705. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  51706. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  51707. var parsedSkeleton = parsedData.skeletons[index];
  51708. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  51709. log += (index === 0 ? "\n\tSkeletons:" : "");
  51710. log += "\n\t\t" + skeleton.toString(fullDetails);
  51711. }
  51712. }
  51713. // Geometries
  51714. var geometries = parsedData.geometries;
  51715. if (geometries !== undefined && geometries !== null) {
  51716. // Boxes
  51717. var boxes = geometries.boxes;
  51718. if (boxes !== undefined && boxes !== null) {
  51719. for (index = 0, cache = boxes.length; index < cache; index++) {
  51720. var parsedBox = boxes[index];
  51721. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  51722. }
  51723. }
  51724. // Spheres
  51725. var spheres = geometries.spheres;
  51726. if (spheres !== undefined && spheres !== null) {
  51727. for (index = 0, cache = spheres.length; index < cache; index++) {
  51728. var parsedSphere = spheres[index];
  51729. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  51730. }
  51731. }
  51732. // Cylinders
  51733. var cylinders = geometries.cylinders;
  51734. if (cylinders !== undefined && cylinders !== null) {
  51735. for (index = 0, cache = cylinders.length; index < cache; index++) {
  51736. var parsedCylinder = cylinders[index];
  51737. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  51738. }
  51739. }
  51740. // Toruses
  51741. var toruses = geometries.toruses;
  51742. if (toruses !== undefined && toruses !== null) {
  51743. for (index = 0, cache = toruses.length; index < cache; index++) {
  51744. var parsedTorus = toruses[index];
  51745. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  51746. }
  51747. }
  51748. // Grounds
  51749. var grounds = geometries.grounds;
  51750. if (grounds !== undefined && grounds !== null) {
  51751. for (index = 0, cache = grounds.length; index < cache; index++) {
  51752. var parsedGround = grounds[index];
  51753. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  51754. }
  51755. }
  51756. // Planes
  51757. var planes = geometries.planes;
  51758. if (planes !== undefined && planes !== null) {
  51759. for (index = 0, cache = planes.length; index < cache; index++) {
  51760. var parsedPlane = planes[index];
  51761. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  51762. }
  51763. }
  51764. // TorusKnots
  51765. var torusKnots = geometries.torusKnots;
  51766. if (torusKnots !== undefined && torusKnots !== null) {
  51767. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  51768. var parsedTorusKnot = torusKnots[index];
  51769. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  51770. }
  51771. }
  51772. // VertexData
  51773. var vertexData = geometries.vertexData;
  51774. if (vertexData !== undefined && vertexData !== null) {
  51775. for (index = 0, cache = vertexData.length; index < cache; index++) {
  51776. var parsedVertexData = vertexData[index];
  51777. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  51778. }
  51779. }
  51780. }
  51781. // Meshes
  51782. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  51783. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  51784. var parsedMesh = parsedData.meshes[index];
  51785. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  51786. log += (index === 0 ? "\n\tMeshes:" : "");
  51787. log += "\n\t\t" + mesh.toString(fullDetails);
  51788. }
  51789. }
  51790. // Cameras
  51791. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  51792. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  51793. var parsedCamera = parsedData.cameras[index];
  51794. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  51795. log += (index === 0 ? "\n\tCameras:" : "");
  51796. log += "\n\t\t" + camera.toString(fullDetails);
  51797. }
  51798. }
  51799. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  51800. scene.setActiveCameraByID(parsedData.activeCameraID);
  51801. }
  51802. // Browsing all the graph to connect the dots
  51803. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  51804. var camera = scene.cameras[index];
  51805. if (camera._waitingParentId) {
  51806. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  51807. camera._waitingParentId = null;
  51808. }
  51809. }
  51810. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  51811. var light_1 = scene.lights[index];
  51812. if (light_1 && light_1._waitingParentId) {
  51813. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  51814. light_1._waitingParentId = null;
  51815. }
  51816. }
  51817. // Sounds
  51818. var loadedSounds = [];
  51819. var loadedSound;
  51820. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  51821. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  51822. var parsedSound = parsedData.sounds[index];
  51823. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  51824. if (!parsedSound.url)
  51825. parsedSound.url = parsedSound.name;
  51826. if (!loadedSounds[parsedSound.url]) {
  51827. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  51828. loadedSounds[parsedSound.url] = loadedSound;
  51829. }
  51830. else {
  51831. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  51832. }
  51833. }
  51834. else {
  51835. new BABYLON.Sound(parsedSound.name, null, scene);
  51836. }
  51837. }
  51838. }
  51839. loadedSounds = [];
  51840. // Connect parents & children and parse actions
  51841. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  51842. var mesh = scene.meshes[index];
  51843. if (mesh._waitingParentId) {
  51844. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  51845. mesh._waitingParentId = null;
  51846. }
  51847. if (mesh._waitingActions) {
  51848. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  51849. mesh._waitingActions = null;
  51850. }
  51851. }
  51852. // freeze world matrix application
  51853. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  51854. var currentMesh = scene.meshes[index];
  51855. if (currentMesh._waitingFreezeWorldMatrix) {
  51856. currentMesh.freezeWorldMatrix();
  51857. currentMesh._waitingFreezeWorldMatrix = null;
  51858. }
  51859. else {
  51860. currentMesh.computeWorldMatrix(true);
  51861. }
  51862. }
  51863. // Particles Systems
  51864. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  51865. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  51866. var parsedParticleSystem = parsedData.particleSystems[index];
  51867. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  51868. }
  51869. }
  51870. // Lens flares
  51871. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  51872. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  51873. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  51874. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  51875. }
  51876. }
  51877. // Shadows
  51878. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  51879. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  51880. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  51881. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  51882. }
  51883. }
  51884. // Lights exclusions / inclusions
  51885. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  51886. var light_2 = scene.lights[index];
  51887. // Excluded check
  51888. if (light_2._excludedMeshesIds.length > 0) {
  51889. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  51890. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  51891. if (excludedMesh) {
  51892. light_2.excludedMeshes.push(excludedMesh);
  51893. }
  51894. }
  51895. light_2._excludedMeshesIds = [];
  51896. }
  51897. // Included check
  51898. if (light_2._includedOnlyMeshesIds.length > 0) {
  51899. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  51900. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  51901. if (includedOnlyMesh) {
  51902. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  51903. }
  51904. }
  51905. light_2._includedOnlyMeshesIds = [];
  51906. }
  51907. }
  51908. // Actions (scene)
  51909. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  51910. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  51911. }
  51912. // Finish
  51913. return true;
  51914. }
  51915. catch (err) {
  51916. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  51917. if (onError) {
  51918. onError(msg, err);
  51919. }
  51920. else {
  51921. BABYLON.Tools.Log(msg);
  51922. throw err;
  51923. }
  51924. }
  51925. finally {
  51926. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  51927. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  51928. }
  51929. }
  51930. return false;
  51931. }
  51932. });
  51933. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51934. })(BABYLON || (BABYLON = {}));
  51935. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  51936. var BABYLON;
  51937. (function (BABYLON) {
  51938. var FilesInput = /** @class */ (function () {
  51939. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  51940. this.onProcessFileCallback = function () { return true; };
  51941. this._engine = engine;
  51942. this._currentScene = scene;
  51943. this._sceneLoadedCallback = sceneLoadedCallback;
  51944. this._progressCallback = progressCallback;
  51945. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  51946. this._textureLoadingCallback = textureLoadingCallback;
  51947. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  51948. this._onReloadCallback = onReloadCallback;
  51949. this._errorCallback = errorCallback;
  51950. }
  51951. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  51952. var _this = this;
  51953. if (elementToMonitor) {
  51954. this._elementToMonitor = elementToMonitor;
  51955. this._dragEnterHandler = function (e) { _this.drag(e); };
  51956. this._dragOverHandler = function (e) { _this.drag(e); };
  51957. this._dropHandler = function (e) { _this.drop(e); };
  51958. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  51959. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  51960. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  51961. }
  51962. };
  51963. FilesInput.prototype.dispose = function () {
  51964. if (!this._elementToMonitor) {
  51965. return;
  51966. }
  51967. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  51968. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  51969. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  51970. };
  51971. FilesInput.prototype.renderFunction = function () {
  51972. if (this._additionalRenderLoopLogicCallback) {
  51973. this._additionalRenderLoopLogicCallback();
  51974. }
  51975. if (this._currentScene) {
  51976. if (this._textureLoadingCallback) {
  51977. var remaining = this._currentScene.getWaitingItemsCount();
  51978. if (remaining > 0) {
  51979. this._textureLoadingCallback(remaining);
  51980. }
  51981. }
  51982. this._currentScene.render();
  51983. }
  51984. };
  51985. FilesInput.prototype.drag = function (e) {
  51986. e.stopPropagation();
  51987. e.preventDefault();
  51988. };
  51989. FilesInput.prototype.drop = function (eventDrop) {
  51990. eventDrop.stopPropagation();
  51991. eventDrop.preventDefault();
  51992. this.loadFiles(eventDrop);
  51993. };
  51994. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  51995. var _this = this;
  51996. var reader = folder.createReader();
  51997. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  51998. reader.readEntries(function (entries) {
  51999. remaining.count += entries.length;
  52000. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  52001. var entry = entries_1[_i];
  52002. if (entry.isFile) {
  52003. entry.file(function (file) {
  52004. file.correctName = relativePath + file.name;
  52005. files.push(file);
  52006. if (--remaining.count === 0) {
  52007. callback();
  52008. }
  52009. });
  52010. }
  52011. else if (entry.isDirectory) {
  52012. _this._traverseFolder(entry, files, remaining, callback);
  52013. }
  52014. }
  52015. if (--remaining.count) {
  52016. callback();
  52017. }
  52018. });
  52019. };
  52020. FilesInput.prototype._processFiles = function (files) {
  52021. var skippedFiles = 0;
  52022. for (var i = 0; i < files.length; i++) {
  52023. var name = files[i].correctName.toLowerCase();
  52024. var extension = name.split('.').pop();
  52025. if (!this.onProcessFileCallback(files[i], name, extension)) {
  52026. skippedFiles++;
  52027. continue;
  52028. }
  52029. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  52030. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  52031. this._sceneFileToLoad = files[i];
  52032. }
  52033. else {
  52034. FilesInput.FilesToLoad[name] = files[i];
  52035. }
  52036. }
  52037. if (this._onReloadCallback) {
  52038. this._onReloadCallback(this._sceneFileToLoad);
  52039. }
  52040. else if (skippedFiles < files.length) {
  52041. this.reload();
  52042. }
  52043. };
  52044. FilesInput.prototype.loadFiles = function (event) {
  52045. var _this = this;
  52046. if (this._startingProcessingFilesCallback)
  52047. this._startingProcessingFilesCallback();
  52048. // Handling data transfer via drag'n'drop
  52049. if (event && event.dataTransfer && event.dataTransfer.files) {
  52050. this._filesToLoad = event.dataTransfer.files;
  52051. }
  52052. // Handling files from input files
  52053. if (event && event.target && event.target.files) {
  52054. this._filesToLoad = event.target.files;
  52055. }
  52056. if (this._filesToLoad && this._filesToLoad.length > 0) {
  52057. var files_1 = new Array();
  52058. var folders = [];
  52059. var items = event.dataTransfer ? event.dataTransfer.items : null;
  52060. for (var i = 0; i < this._filesToLoad.length; i++) {
  52061. var fileToLoad = this._filesToLoad[i];
  52062. var name_1 = fileToLoad.name.toLowerCase();
  52063. var entry = void 0;
  52064. fileToLoad.correctName = name_1;
  52065. if (items) {
  52066. var item = items[i];
  52067. if (item.getAsEntry) {
  52068. entry = item.getAsEntry();
  52069. }
  52070. else if (item.webkitGetAsEntry) {
  52071. entry = item.webkitGetAsEntry();
  52072. }
  52073. }
  52074. if (!entry) {
  52075. files_1.push(fileToLoad);
  52076. }
  52077. else {
  52078. if (entry.isDirectory) {
  52079. folders.push(entry);
  52080. }
  52081. else {
  52082. files_1.push(fileToLoad);
  52083. }
  52084. }
  52085. }
  52086. if (folders.length === 0) {
  52087. this._processFiles(files_1);
  52088. }
  52089. else {
  52090. var remaining = { count: folders.length };
  52091. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  52092. var folder = folders_1[_i];
  52093. this._traverseFolder(folder, files_1, remaining, function () {
  52094. _this._processFiles(files_1);
  52095. });
  52096. }
  52097. }
  52098. }
  52099. };
  52100. FilesInput.prototype.reload = function () {
  52101. var _this = this;
  52102. // If a ".babylon" file has been provided
  52103. if (this._sceneFileToLoad) {
  52104. if (this._currentScene) {
  52105. if (BABYLON.Tools.errorsCount > 0) {
  52106. BABYLON.Tools.ClearLogCache();
  52107. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  52108. }
  52109. this._engine.stopRenderLoop();
  52110. this._currentScene.dispose();
  52111. }
  52112. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  52113. _this._currentScene = newScene;
  52114. if (_this._sceneLoadedCallback) {
  52115. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  52116. }
  52117. // Wait for textures and shaders to be ready
  52118. _this._currentScene.executeWhenReady(function () {
  52119. _this._engine.runRenderLoop(function () {
  52120. _this.renderFunction();
  52121. });
  52122. });
  52123. }, function (progress) {
  52124. if (_this._progressCallback) {
  52125. _this._progressCallback(progress);
  52126. }
  52127. }, function (scene, message) {
  52128. _this._currentScene = scene;
  52129. if (_this._errorCallback) {
  52130. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  52131. }
  52132. });
  52133. }
  52134. else {
  52135. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  52136. }
  52137. };
  52138. FilesInput.FilesToLoad = {};
  52139. return FilesInput;
  52140. }());
  52141. BABYLON.FilesInput = FilesInput;
  52142. })(BABYLON || (BABYLON = {}));
  52143. //# sourceMappingURL=babylon.filesInput.js.map
  52144. var BABYLON;
  52145. (function (BABYLON) {
  52146. /**
  52147. * This class implement a typical dictionary using a string as key and the generic type T as value.
  52148. * The underlying implementation relies on an associative array to ensure the best performances.
  52149. * The value can be anything including 'null' but except 'undefined'
  52150. */
  52151. var StringDictionary = /** @class */ (function () {
  52152. function StringDictionary() {
  52153. this._count = 0;
  52154. this._data = {};
  52155. }
  52156. /**
  52157. * This will clear this dictionary and copy the content from the 'source' one.
  52158. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  52159. * @param source the dictionary to take the content from and copy to this dictionary
  52160. */
  52161. StringDictionary.prototype.copyFrom = function (source) {
  52162. var _this = this;
  52163. this.clear();
  52164. source.forEach(function (t, v) { return _this.add(t, v); });
  52165. };
  52166. /**
  52167. * Get a value based from its key
  52168. * @param key the given key to get the matching value from
  52169. * @return the value if found, otherwise undefined is returned
  52170. */
  52171. StringDictionary.prototype.get = function (key) {
  52172. var val = this._data[key];
  52173. if (val !== undefined) {
  52174. return val;
  52175. }
  52176. return undefined;
  52177. };
  52178. /**
  52179. * Get a value from its key or add it if it doesn't exist.
  52180. * This method will ensure you that a given key/data will be present in the dictionary.
  52181. * @param key the given key to get the matching value from
  52182. * @param factory the factory that will create the value if the key is not present in the dictionary.
  52183. * The factory will only be invoked if there's no data for the given key.
  52184. * @return the value corresponding to the key.
  52185. */
  52186. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  52187. var val = this.get(key);
  52188. if (val !== undefined) {
  52189. return val;
  52190. }
  52191. val = factory(key);
  52192. if (val) {
  52193. this.add(key, val);
  52194. }
  52195. return val;
  52196. };
  52197. /**
  52198. * Get a value from its key if present in the dictionary otherwise add it
  52199. * @param key the key to get the value from
  52200. * @param val if there's no such key/value pair in the dictionary add it with this value
  52201. * @return the value corresponding to the key
  52202. */
  52203. StringDictionary.prototype.getOrAdd = function (key, val) {
  52204. var curVal = this.get(key);
  52205. if (curVal !== undefined) {
  52206. return curVal;
  52207. }
  52208. this.add(key, val);
  52209. return val;
  52210. };
  52211. /**
  52212. * Check if there's a given key in the dictionary
  52213. * @param key the key to check for
  52214. * @return true if the key is present, false otherwise
  52215. */
  52216. StringDictionary.prototype.contains = function (key) {
  52217. return this._data[key] !== undefined;
  52218. };
  52219. /**
  52220. * Add a new key and its corresponding value
  52221. * @param key the key to add
  52222. * @param value the value corresponding to the key
  52223. * @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
  52224. */
  52225. StringDictionary.prototype.add = function (key, value) {
  52226. if (this._data[key] !== undefined) {
  52227. return false;
  52228. }
  52229. this._data[key] = value;
  52230. ++this._count;
  52231. return true;
  52232. };
  52233. StringDictionary.prototype.set = function (key, value) {
  52234. if (this._data[key] === undefined) {
  52235. return false;
  52236. }
  52237. this._data[key] = value;
  52238. return true;
  52239. };
  52240. /**
  52241. * Get the element of the given key and remove it from the dictionary
  52242. * @param key
  52243. */
  52244. StringDictionary.prototype.getAndRemove = function (key) {
  52245. var val = this.get(key);
  52246. if (val !== undefined) {
  52247. delete this._data[key];
  52248. --this._count;
  52249. return val;
  52250. }
  52251. return null;
  52252. };
  52253. /**
  52254. * Remove a key/value from the dictionary.
  52255. * @param key the key to remove
  52256. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  52257. */
  52258. StringDictionary.prototype.remove = function (key) {
  52259. if (this.contains(key)) {
  52260. delete this._data[key];
  52261. --this._count;
  52262. return true;
  52263. }
  52264. return false;
  52265. };
  52266. /**
  52267. * Clear the whole content of the dictionary
  52268. */
  52269. StringDictionary.prototype.clear = function () {
  52270. this._data = {};
  52271. this._count = 0;
  52272. };
  52273. Object.defineProperty(StringDictionary.prototype, "count", {
  52274. get: function () {
  52275. return this._count;
  52276. },
  52277. enumerable: true,
  52278. configurable: true
  52279. });
  52280. /**
  52281. * Execute a callback on each key/val of the dictionary.
  52282. * Note that you can remove any element in this dictionary in the callback implementation
  52283. * @param callback the callback to execute on a given key/value pair
  52284. */
  52285. StringDictionary.prototype.forEach = function (callback) {
  52286. for (var cur in this._data) {
  52287. var val = this._data[cur];
  52288. callback(cur, val);
  52289. }
  52290. };
  52291. /**
  52292. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  52293. * If the callback returns null or undefined the method will iterate to the next key/value pair
  52294. * Note that you can remove any element in this dictionary in the callback implementation
  52295. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  52296. */
  52297. StringDictionary.prototype.first = function (callback) {
  52298. for (var cur in this._data) {
  52299. var val = this._data[cur];
  52300. var res = callback(cur, val);
  52301. if (res) {
  52302. return res;
  52303. }
  52304. }
  52305. return null;
  52306. };
  52307. return StringDictionary;
  52308. }());
  52309. BABYLON.StringDictionary = StringDictionary;
  52310. })(BABYLON || (BABYLON = {}));
  52311. //# sourceMappingURL=babylon.stringDictionary.js.map
  52312. var BABYLON;
  52313. (function (BABYLON) {
  52314. var Tags = /** @class */ (function () {
  52315. function Tags() {
  52316. }
  52317. Tags.EnableFor = function (obj) {
  52318. obj._tags = obj._tags || {};
  52319. obj.hasTags = function () {
  52320. return Tags.HasTags(obj);
  52321. };
  52322. obj.addTags = function (tagsString) {
  52323. return Tags.AddTagsTo(obj, tagsString);
  52324. };
  52325. obj.removeTags = function (tagsString) {
  52326. return Tags.RemoveTagsFrom(obj, tagsString);
  52327. };
  52328. obj.matchesTagsQuery = function (tagsQuery) {
  52329. return Tags.MatchesQuery(obj, tagsQuery);
  52330. };
  52331. };
  52332. Tags.DisableFor = function (obj) {
  52333. delete obj._tags;
  52334. delete obj.hasTags;
  52335. delete obj.addTags;
  52336. delete obj.removeTags;
  52337. delete obj.matchesTagsQuery;
  52338. };
  52339. Tags.HasTags = function (obj) {
  52340. if (!obj._tags) {
  52341. return false;
  52342. }
  52343. return !BABYLON.Tools.IsEmpty(obj._tags);
  52344. };
  52345. Tags.GetTags = function (obj, asString) {
  52346. if (asString === void 0) { asString = true; }
  52347. if (!obj._tags) {
  52348. return null;
  52349. }
  52350. if (asString) {
  52351. var tagsArray = [];
  52352. for (var tag in obj._tags) {
  52353. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  52354. tagsArray.push(tag);
  52355. }
  52356. }
  52357. return tagsArray.join(" ");
  52358. }
  52359. else {
  52360. return obj._tags;
  52361. }
  52362. };
  52363. // the tags 'true' and 'false' are reserved and cannot be used as tags
  52364. // a tag cannot start with '||', '&&', and '!'
  52365. // it cannot contain whitespaces
  52366. Tags.AddTagsTo = function (obj, tagsString) {
  52367. if (!tagsString) {
  52368. return;
  52369. }
  52370. if (typeof tagsString !== "string") {
  52371. return;
  52372. }
  52373. var tags = tagsString.split(" ");
  52374. tags.forEach(function (tag, index, array) {
  52375. Tags._AddTagTo(obj, tag);
  52376. });
  52377. };
  52378. Tags._AddTagTo = function (obj, tag) {
  52379. tag = tag.trim();
  52380. if (tag === "" || tag === "true" || tag === "false") {
  52381. return;
  52382. }
  52383. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  52384. return;
  52385. }
  52386. Tags.EnableFor(obj);
  52387. obj._tags[tag] = true;
  52388. };
  52389. Tags.RemoveTagsFrom = function (obj, tagsString) {
  52390. if (!Tags.HasTags(obj)) {
  52391. return;
  52392. }
  52393. var tags = tagsString.split(" ");
  52394. for (var t in tags) {
  52395. Tags._RemoveTagFrom(obj, tags[t]);
  52396. }
  52397. };
  52398. Tags._RemoveTagFrom = function (obj, tag) {
  52399. delete obj._tags[tag];
  52400. };
  52401. Tags.MatchesQuery = function (obj, tagsQuery) {
  52402. if (tagsQuery === undefined) {
  52403. return true;
  52404. }
  52405. if (tagsQuery === "") {
  52406. return Tags.HasTags(obj);
  52407. }
  52408. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  52409. };
  52410. return Tags;
  52411. }());
  52412. BABYLON.Tags = Tags;
  52413. })(BABYLON || (BABYLON = {}));
  52414. //# sourceMappingURL=babylon.tags.js.map
  52415. var BABYLON;
  52416. (function (BABYLON) {
  52417. var Internals;
  52418. (function (Internals) {
  52419. var AndOrNotEvaluator = /** @class */ (function () {
  52420. function AndOrNotEvaluator() {
  52421. }
  52422. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  52423. if (!query.match(/\([^\(\)]*\)/g)) {
  52424. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  52425. }
  52426. else {
  52427. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  52428. // remove parenthesis
  52429. r = r.slice(1, r.length - 1);
  52430. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  52431. });
  52432. }
  52433. if (query === "true") {
  52434. return true;
  52435. }
  52436. if (query === "false") {
  52437. return false;
  52438. }
  52439. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  52440. };
  52441. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  52442. evaluateCallback = evaluateCallback || (function (r) {
  52443. return r === "true" ? true : false;
  52444. });
  52445. var result;
  52446. var or = parenthesisContent.split("||");
  52447. for (var i in or) {
  52448. if (or.hasOwnProperty(i)) {
  52449. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  52450. var and = ori.split("&&");
  52451. if (and.length > 1) {
  52452. for (var j = 0; j < and.length; ++j) {
  52453. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  52454. if (andj !== "true" && andj !== "false") {
  52455. if (andj[0] === "!") {
  52456. result = !evaluateCallback(andj.substring(1));
  52457. }
  52458. else {
  52459. result = evaluateCallback(andj);
  52460. }
  52461. }
  52462. else {
  52463. result = andj === "true" ? true : false;
  52464. }
  52465. if (!result) {
  52466. ori = "false";
  52467. break;
  52468. }
  52469. }
  52470. }
  52471. if (result || ori === "true") {
  52472. result = true;
  52473. break;
  52474. }
  52475. // result equals false (or undefined)
  52476. if (ori !== "true" && ori !== "false") {
  52477. if (ori[0] === "!") {
  52478. result = !evaluateCallback(ori.substring(1));
  52479. }
  52480. else {
  52481. result = evaluateCallback(ori);
  52482. }
  52483. }
  52484. else {
  52485. result = ori === "true" ? true : false;
  52486. }
  52487. }
  52488. }
  52489. // the whole parenthesis scope is replaced by 'true' or 'false'
  52490. return result ? "true" : "false";
  52491. };
  52492. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  52493. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  52494. // remove whitespaces
  52495. r = r.replace(/[\s]/g, function () { return ""; });
  52496. return r.length % 2 ? "!" : "";
  52497. });
  52498. booleanString = booleanString.trim();
  52499. if (booleanString === "!true") {
  52500. booleanString = "false";
  52501. }
  52502. else if (booleanString === "!false") {
  52503. booleanString = "true";
  52504. }
  52505. return booleanString;
  52506. };
  52507. return AndOrNotEvaluator;
  52508. }());
  52509. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  52510. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  52511. })(BABYLON || (BABYLON = {}));
  52512. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  52513. var BABYLON;
  52514. (function (BABYLON) {
  52515. var Database = /** @class */ (function () {
  52516. function Database(urlToScene, callbackManifestChecked) {
  52517. // Handling various flavors of prefixed version of IndexedDB
  52518. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  52519. this.callbackManifestChecked = callbackManifestChecked;
  52520. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  52521. this.db = null;
  52522. this._enableSceneOffline = false;
  52523. this._enableTexturesOffline = false;
  52524. this.manifestVersionFound = 0;
  52525. this.mustUpdateRessources = false;
  52526. this.hasReachedQuota = false;
  52527. if (!Database.IDBStorageEnabled) {
  52528. this.callbackManifestChecked(true);
  52529. }
  52530. else {
  52531. this.checkManifestFile();
  52532. }
  52533. }
  52534. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  52535. get: function () {
  52536. return this._enableSceneOffline;
  52537. },
  52538. enumerable: true,
  52539. configurable: true
  52540. });
  52541. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  52542. get: function () {
  52543. return this._enableTexturesOffline;
  52544. },
  52545. enumerable: true,
  52546. configurable: true
  52547. });
  52548. Database.prototype.checkManifestFile = function () {
  52549. var _this = this;
  52550. var noManifestFile = function () {
  52551. _this._enableSceneOffline = false;
  52552. _this._enableTexturesOffline = false;
  52553. _this.callbackManifestChecked(false);
  52554. };
  52555. var timeStampUsed = false;
  52556. var manifestURL = this.currentSceneUrl + ".manifest";
  52557. var xhr = new XMLHttpRequest();
  52558. if (navigator.onLine) {
  52559. // Adding a timestamp to by-pass browsers' cache
  52560. timeStampUsed = true;
  52561. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  52562. }
  52563. xhr.open("GET", manifestURL, true);
  52564. xhr.addEventListener("load", function () {
  52565. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  52566. try {
  52567. var manifestFile = JSON.parse(xhr.response);
  52568. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  52569. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  52570. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  52571. _this.manifestVersionFound = manifestFile.version;
  52572. }
  52573. if (_this.callbackManifestChecked) {
  52574. _this.callbackManifestChecked(true);
  52575. }
  52576. }
  52577. catch (ex) {
  52578. noManifestFile();
  52579. }
  52580. }
  52581. else {
  52582. noManifestFile();
  52583. }
  52584. }, false);
  52585. xhr.addEventListener("error", function (event) {
  52586. if (timeStampUsed) {
  52587. timeStampUsed = false;
  52588. // Let's retry without the timeStamp
  52589. // It could fail when coupled with HTML5 Offline API
  52590. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  52591. xhr.open("GET", retryManifestURL, true);
  52592. xhr.send();
  52593. }
  52594. else {
  52595. noManifestFile();
  52596. }
  52597. }, false);
  52598. try {
  52599. xhr.send();
  52600. }
  52601. catch (ex) {
  52602. BABYLON.Tools.Error("Error on XHR send request.");
  52603. this.callbackManifestChecked(false);
  52604. }
  52605. };
  52606. Database.prototype.openAsync = function (successCallback, errorCallback) {
  52607. var _this = this;
  52608. function handleError() {
  52609. that.isSupported = false;
  52610. if (errorCallback)
  52611. errorCallback();
  52612. }
  52613. var that = this;
  52614. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  52615. // Your browser doesn't support IndexedDB
  52616. this.isSupported = false;
  52617. if (errorCallback)
  52618. errorCallback();
  52619. }
  52620. else {
  52621. // If the DB hasn't been opened or created yet
  52622. if (!this.db) {
  52623. this.hasReachedQuota = false;
  52624. this.isSupported = true;
  52625. var request = this.idbFactory.open("babylonjs", 1);
  52626. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  52627. request.onerror = function (event) {
  52628. handleError();
  52629. };
  52630. // executes when a version change transaction cannot complete due to other active transactions
  52631. request.onblocked = function (event) {
  52632. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  52633. handleError();
  52634. };
  52635. // DB has been opened successfully
  52636. request.onsuccess = function (event) {
  52637. _this.db = request.result;
  52638. successCallback();
  52639. };
  52640. // Initialization of the DB. Creating Scenes & Textures stores
  52641. request.onupgradeneeded = function (event) {
  52642. _this.db = (event.target).result;
  52643. if (_this.db) {
  52644. try {
  52645. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  52646. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  52647. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  52648. }
  52649. catch (ex) {
  52650. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  52651. handleError();
  52652. }
  52653. }
  52654. };
  52655. }
  52656. else {
  52657. if (successCallback)
  52658. successCallback();
  52659. }
  52660. }
  52661. };
  52662. Database.prototype.loadImageFromDB = function (url, image) {
  52663. var _this = this;
  52664. var completeURL = Database.ReturnFullUrlLocation(url);
  52665. var saveAndLoadImage = function () {
  52666. if (!_this.hasReachedQuota && _this.db !== null) {
  52667. // the texture is not yet in the DB, let's try to save it
  52668. _this._saveImageIntoDBAsync(completeURL, image);
  52669. }
  52670. else {
  52671. image.src = url;
  52672. }
  52673. };
  52674. if (!this.mustUpdateRessources) {
  52675. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  52676. }
  52677. else {
  52678. saveAndLoadImage();
  52679. }
  52680. };
  52681. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  52682. if (this.isSupported && this.db !== null) {
  52683. var texture;
  52684. var transaction = this.db.transaction(["textures"]);
  52685. transaction.onabort = function (event) {
  52686. image.src = url;
  52687. };
  52688. transaction.oncomplete = function (event) {
  52689. var blobTextureURL;
  52690. if (texture) {
  52691. var URL = window.URL || window.webkitURL;
  52692. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  52693. image.onerror = function () {
  52694. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  52695. image.src = url;
  52696. };
  52697. image.src = blobTextureURL;
  52698. }
  52699. else {
  52700. notInDBCallback();
  52701. }
  52702. };
  52703. var getRequest = transaction.objectStore("textures").get(url);
  52704. getRequest.onsuccess = function (event) {
  52705. texture = (event.target).result;
  52706. };
  52707. getRequest.onerror = function (event) {
  52708. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  52709. image.src = url;
  52710. };
  52711. }
  52712. else {
  52713. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  52714. image.src = url;
  52715. }
  52716. };
  52717. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  52718. var _this = this;
  52719. if (this.isSupported) {
  52720. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  52721. var generateBlobUrl = function () {
  52722. var blobTextureURL;
  52723. if (blob) {
  52724. var URL = window.URL || window.webkitURL;
  52725. try {
  52726. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  52727. }
  52728. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  52729. catch (ex) {
  52730. blobTextureURL = URL.createObjectURL(blob);
  52731. }
  52732. }
  52733. if (blobTextureURL) {
  52734. image.src = blobTextureURL;
  52735. }
  52736. };
  52737. if (Database.IsUASupportingBlobStorage) {
  52738. var xhr = new XMLHttpRequest(), blob;
  52739. xhr.open("GET", url, true);
  52740. xhr.responseType = "blob";
  52741. xhr.addEventListener("load", function () {
  52742. if (xhr.status === 200 && _this.db) {
  52743. // Blob as response (XHR2)
  52744. blob = xhr.response;
  52745. var transaction = _this.db.transaction(["textures"], "readwrite");
  52746. // the transaction could abort because of a QuotaExceededError error
  52747. transaction.onabort = function (event) {
  52748. try {
  52749. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  52750. var error = event.srcElement['error'];
  52751. if (error && error.name === "QuotaExceededError") {
  52752. _this.hasReachedQuota = true;
  52753. }
  52754. }
  52755. catch (ex) { }
  52756. generateBlobUrl();
  52757. };
  52758. transaction.oncomplete = function (event) {
  52759. generateBlobUrl();
  52760. };
  52761. var newTexture = { textureUrl: url, data: blob };
  52762. try {
  52763. // Put the blob into the dabase
  52764. var addRequest = transaction.objectStore("textures").put(newTexture);
  52765. addRequest.onsuccess = function (event) {
  52766. };
  52767. addRequest.onerror = function (event) {
  52768. generateBlobUrl();
  52769. };
  52770. }
  52771. catch (ex) {
  52772. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  52773. if (ex.code === 25) {
  52774. Database.IsUASupportingBlobStorage = false;
  52775. }
  52776. image.src = url;
  52777. }
  52778. }
  52779. else {
  52780. image.src = url;
  52781. }
  52782. }, false);
  52783. xhr.addEventListener("error", function (event) {
  52784. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  52785. image.src = url;
  52786. }, false);
  52787. xhr.send();
  52788. }
  52789. else {
  52790. image.src = url;
  52791. }
  52792. }
  52793. else {
  52794. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  52795. image.src = url;
  52796. }
  52797. };
  52798. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  52799. var _this = this;
  52800. var updateVersion = function () {
  52801. // the version is not yet in the DB or we need to update it
  52802. _this._saveVersionIntoDBAsync(url, versionLoaded);
  52803. };
  52804. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  52805. };
  52806. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  52807. var _this = this;
  52808. if (this.isSupported && this.db) {
  52809. var version;
  52810. try {
  52811. var transaction = this.db.transaction(["versions"]);
  52812. transaction.oncomplete = function (event) {
  52813. if (version) {
  52814. // If the version in the JSON file is > than the version in DB
  52815. if (_this.manifestVersionFound > version.data) {
  52816. _this.mustUpdateRessources = true;
  52817. updateInDBCallback();
  52818. }
  52819. else {
  52820. callback(version.data);
  52821. }
  52822. }
  52823. else {
  52824. _this.mustUpdateRessources = true;
  52825. updateInDBCallback();
  52826. }
  52827. };
  52828. transaction.onabort = function (event) {
  52829. callback(-1);
  52830. };
  52831. var getRequest = transaction.objectStore("versions").get(url);
  52832. getRequest.onsuccess = function (event) {
  52833. version = (event.target).result;
  52834. };
  52835. getRequest.onerror = function (event) {
  52836. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  52837. callback(-1);
  52838. };
  52839. }
  52840. catch (ex) {
  52841. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  52842. callback(-1);
  52843. }
  52844. }
  52845. else {
  52846. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  52847. callback(-1);
  52848. }
  52849. };
  52850. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  52851. var _this = this;
  52852. if (this.isSupported && !this.hasReachedQuota && this.db) {
  52853. try {
  52854. // Open a transaction to the database
  52855. var transaction = this.db.transaction(["versions"], "readwrite");
  52856. // the transaction could abort because of a QuotaExceededError error
  52857. transaction.onabort = function (event) {
  52858. try {
  52859. var error = event.srcElement['error'];
  52860. if (error && error.name === "QuotaExceededError") {
  52861. _this.hasReachedQuota = true;
  52862. }
  52863. }
  52864. catch (ex) { }
  52865. callback(-1);
  52866. };
  52867. transaction.oncomplete = function (event) {
  52868. callback(_this.manifestVersionFound);
  52869. };
  52870. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  52871. // Put the scene into the database
  52872. var addRequest = transaction.objectStore("versions").put(newVersion);
  52873. addRequest.onsuccess = function (event) {
  52874. };
  52875. addRequest.onerror = function (event) {
  52876. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  52877. };
  52878. }
  52879. catch (ex) {
  52880. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  52881. callback(-1);
  52882. }
  52883. }
  52884. else {
  52885. callback(-1);
  52886. }
  52887. };
  52888. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  52889. var _this = this;
  52890. var completeUrl = Database.ReturnFullUrlLocation(url);
  52891. var saveAndLoadFile = function () {
  52892. // the scene is not yet in the DB, let's try to save it
  52893. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  52894. };
  52895. this._checkVersionFromDB(completeUrl, function (version) {
  52896. if (version !== -1) {
  52897. if (!_this.mustUpdateRessources) {
  52898. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  52899. }
  52900. else {
  52901. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  52902. }
  52903. }
  52904. else {
  52905. if (errorCallback) {
  52906. errorCallback();
  52907. }
  52908. }
  52909. });
  52910. };
  52911. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  52912. if (this.isSupported && this.db) {
  52913. var targetStore;
  52914. if (url.indexOf(".babylon") !== -1) {
  52915. targetStore = "scenes";
  52916. }
  52917. else {
  52918. targetStore = "textures";
  52919. }
  52920. var file;
  52921. var transaction = this.db.transaction([targetStore]);
  52922. transaction.oncomplete = function (event) {
  52923. if (file) {
  52924. callback(file.data);
  52925. }
  52926. else {
  52927. notInDBCallback();
  52928. }
  52929. };
  52930. transaction.onabort = function (event) {
  52931. notInDBCallback();
  52932. };
  52933. var getRequest = transaction.objectStore(targetStore).get(url);
  52934. getRequest.onsuccess = function (event) {
  52935. file = (event.target).result;
  52936. };
  52937. getRequest.onerror = function (event) {
  52938. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  52939. notInDBCallback();
  52940. };
  52941. }
  52942. else {
  52943. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  52944. callback();
  52945. }
  52946. };
  52947. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  52948. var _this = this;
  52949. if (this.isSupported) {
  52950. var targetStore;
  52951. if (url.indexOf(".babylon") !== -1) {
  52952. targetStore = "scenes";
  52953. }
  52954. else {
  52955. targetStore = "textures";
  52956. }
  52957. // Create XHR
  52958. var xhr = new XMLHttpRequest();
  52959. var fileData;
  52960. xhr.open("GET", url, true);
  52961. if (useArrayBuffer) {
  52962. xhr.responseType = "arraybuffer";
  52963. }
  52964. if (progressCallback) {
  52965. xhr.onprogress = progressCallback;
  52966. }
  52967. xhr.addEventListener("load", function () {
  52968. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  52969. // Blob as response (XHR2)
  52970. //fileData = xhr.responseText;
  52971. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  52972. if (!_this.hasReachedQuota && _this.db) {
  52973. // Open a transaction to the database
  52974. var transaction = _this.db.transaction([targetStore], "readwrite");
  52975. // the transaction could abort because of a QuotaExceededError error
  52976. transaction.onabort = function (event) {
  52977. try {
  52978. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  52979. var error = event.srcElement['error'];
  52980. if (error && error.name === "QuotaExceededError") {
  52981. _this.hasReachedQuota = true;
  52982. }
  52983. }
  52984. catch (ex) { }
  52985. callback(fileData);
  52986. };
  52987. transaction.oncomplete = function (event) {
  52988. callback(fileData);
  52989. };
  52990. var newFile;
  52991. if (targetStore === "scenes") {
  52992. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  52993. }
  52994. else {
  52995. newFile = { textureUrl: url, data: fileData };
  52996. }
  52997. try {
  52998. // Put the scene into the database
  52999. var addRequest = transaction.objectStore(targetStore).put(newFile);
  53000. addRequest.onsuccess = function (event) {
  53001. };
  53002. addRequest.onerror = function (event) {
  53003. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  53004. };
  53005. }
  53006. catch (ex) {
  53007. callback(fileData);
  53008. }
  53009. }
  53010. else {
  53011. callback(fileData);
  53012. }
  53013. }
  53014. else {
  53015. callback();
  53016. }
  53017. }, false);
  53018. xhr.addEventListener("error", function (event) {
  53019. BABYLON.Tools.Error("error on XHR request.");
  53020. callback();
  53021. }, false);
  53022. xhr.send();
  53023. }
  53024. else {
  53025. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53026. callback();
  53027. }
  53028. };
  53029. Database.IsUASupportingBlobStorage = true;
  53030. Database.IDBStorageEnabled = true;
  53031. Database.parseURL = function (url) {
  53032. var a = document.createElement('a');
  53033. a.href = url;
  53034. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  53035. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  53036. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  53037. return absLocation;
  53038. };
  53039. Database.ReturnFullUrlLocation = function (url) {
  53040. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  53041. return (Database.parseURL(window.location.href) + url);
  53042. }
  53043. else {
  53044. return url;
  53045. }
  53046. };
  53047. return Database;
  53048. }());
  53049. BABYLON.Database = Database;
  53050. })(BABYLON || (BABYLON = {}));
  53051. //# sourceMappingURL=babylon.database.js.map
  53052. var BABYLON;
  53053. (function (BABYLON) {
  53054. var FresnelParameters = /** @class */ (function () {
  53055. function FresnelParameters() {
  53056. this._isEnabled = true;
  53057. this.leftColor = BABYLON.Color3.White();
  53058. this.rightColor = BABYLON.Color3.Black();
  53059. this.bias = 0;
  53060. this.power = 1;
  53061. }
  53062. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  53063. get: function () {
  53064. return this._isEnabled;
  53065. },
  53066. set: function (value) {
  53067. if (this._isEnabled === value) {
  53068. return;
  53069. }
  53070. this._isEnabled = value;
  53071. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  53072. },
  53073. enumerable: true,
  53074. configurable: true
  53075. });
  53076. FresnelParameters.prototype.clone = function () {
  53077. var newFresnelParameters = new FresnelParameters();
  53078. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  53079. return newFresnelParameters;
  53080. };
  53081. FresnelParameters.prototype.serialize = function () {
  53082. var serializationObject = {};
  53083. serializationObject.isEnabled = this.isEnabled;
  53084. serializationObject.leftColor = this.leftColor;
  53085. serializationObject.rightColor = this.rightColor;
  53086. serializationObject.bias = this.bias;
  53087. serializationObject.power = this.power;
  53088. return serializationObject;
  53089. };
  53090. FresnelParameters.Parse = function (parsedFresnelParameters) {
  53091. var fresnelParameters = new FresnelParameters();
  53092. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  53093. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  53094. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  53095. fresnelParameters.bias = parsedFresnelParameters.bias;
  53096. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  53097. return fresnelParameters;
  53098. };
  53099. return FresnelParameters;
  53100. }());
  53101. BABYLON.FresnelParameters = FresnelParameters;
  53102. })(BABYLON || (BABYLON = {}));
  53103. //# sourceMappingURL=babylon.fresnelParameters.js.map
  53104. var BABYLON;
  53105. (function (BABYLON) {
  53106. var MultiMaterial = /** @class */ (function (_super) {
  53107. __extends(MultiMaterial, _super);
  53108. function MultiMaterial(name, scene) {
  53109. var _this = _super.call(this, name, scene, true) || this;
  53110. scene.multiMaterials.push(_this);
  53111. _this.subMaterials = new Array();
  53112. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  53113. return _this;
  53114. }
  53115. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  53116. get: function () {
  53117. return this._subMaterials;
  53118. },
  53119. set: function (value) {
  53120. this._subMaterials = value;
  53121. this._hookArray(value);
  53122. },
  53123. enumerable: true,
  53124. configurable: true
  53125. });
  53126. MultiMaterial.prototype._hookArray = function (array) {
  53127. var _this = this;
  53128. var oldPush = array.push;
  53129. array.push = function () {
  53130. var items = [];
  53131. for (var _i = 0; _i < arguments.length; _i++) {
  53132. items[_i] = arguments[_i];
  53133. }
  53134. var result = oldPush.apply(array, items);
  53135. _this._markAllSubMeshesAsTexturesDirty();
  53136. return result;
  53137. };
  53138. var oldSplice = array.splice;
  53139. array.splice = function (index, deleteCount) {
  53140. var deleted = oldSplice.apply(array, [index, deleteCount]);
  53141. _this._markAllSubMeshesAsTexturesDirty();
  53142. return deleted;
  53143. };
  53144. };
  53145. // Properties
  53146. MultiMaterial.prototype.getSubMaterial = function (index) {
  53147. if (index < 0 || index >= this.subMaterials.length) {
  53148. return this.getScene().defaultMaterial;
  53149. }
  53150. return this.subMaterials[index];
  53151. };
  53152. MultiMaterial.prototype.getActiveTextures = function () {
  53153. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { return subMaterial.getActiveTextures(); }));
  53154. var _a;
  53155. };
  53156. // Methods
  53157. MultiMaterial.prototype.getClassName = function () {
  53158. return "MultiMaterial";
  53159. };
  53160. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  53161. for (var index = 0; index < this.subMaterials.length; index++) {
  53162. var subMaterial = this.subMaterials[index];
  53163. if (subMaterial) {
  53164. if (this.subMaterials[index].storeEffectOnSubMeshes) {
  53165. if (!this.subMaterials[index].isReadyForSubMesh(mesh, subMesh, useInstances)) {
  53166. return false;
  53167. }
  53168. continue;
  53169. }
  53170. if (!this.subMaterials[index].isReady(mesh)) {
  53171. return false;
  53172. }
  53173. }
  53174. }
  53175. return true;
  53176. };
  53177. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  53178. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  53179. for (var index = 0; index < this.subMaterials.length; index++) {
  53180. var subMaterial = null;
  53181. if (cloneChildren) {
  53182. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  53183. }
  53184. else {
  53185. subMaterial = this.subMaterials[index];
  53186. }
  53187. newMultiMaterial.subMaterials.push(subMaterial);
  53188. }
  53189. return newMultiMaterial;
  53190. };
  53191. MultiMaterial.prototype.serialize = function () {
  53192. var serializationObject = {};
  53193. serializationObject.name = this.name;
  53194. serializationObject.id = this.id;
  53195. serializationObject.tags = BABYLON.Tags.GetTags(this);
  53196. serializationObject.materials = [];
  53197. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  53198. var subMat = this.subMaterials[matIndex];
  53199. if (subMat) {
  53200. serializationObject.materials.push(subMat.id);
  53201. }
  53202. else {
  53203. serializationObject.materials.push(null);
  53204. }
  53205. }
  53206. return serializationObject;
  53207. };
  53208. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  53209. var scene = this.getScene();
  53210. if (!scene) {
  53211. return;
  53212. }
  53213. var index = scene.multiMaterials.indexOf(this);
  53214. if (index >= 0) {
  53215. scene.multiMaterials.splice(index, 1);
  53216. }
  53217. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  53218. };
  53219. return MultiMaterial;
  53220. }(BABYLON.Material));
  53221. BABYLON.MultiMaterial = MultiMaterial;
  53222. })(BABYLON || (BABYLON = {}));
  53223. //# sourceMappingURL=babylon.multiMaterial.js.map
  53224. var BABYLON;
  53225. (function (BABYLON) {
  53226. var FreeCameraTouchInput = /** @class */ (function () {
  53227. function FreeCameraTouchInput() {
  53228. this._offsetX = null;
  53229. this._offsetY = null;
  53230. this._pointerCount = 0;
  53231. this._pointerPressed = new Array();
  53232. this.touchAngularSensibility = 200000.0;
  53233. this.touchMoveSensibility = 250.0;
  53234. }
  53235. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  53236. var _this = this;
  53237. var previousPosition = null;
  53238. if (this._pointerInput === undefined) {
  53239. this._onLostFocus = function (evt) {
  53240. _this._offsetX = null;
  53241. _this._offsetY = null;
  53242. };
  53243. this._pointerInput = function (p, s) {
  53244. var evt = p.event;
  53245. if (evt.pointerType === "mouse") {
  53246. return;
  53247. }
  53248. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  53249. if (!noPreventDefault) {
  53250. evt.preventDefault();
  53251. }
  53252. _this._pointerPressed.push(evt.pointerId);
  53253. if (_this._pointerPressed.length !== 1) {
  53254. return;
  53255. }
  53256. previousPosition = {
  53257. x: evt.clientX,
  53258. y: evt.clientY
  53259. };
  53260. }
  53261. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  53262. if (!noPreventDefault) {
  53263. evt.preventDefault();
  53264. }
  53265. var index = _this._pointerPressed.indexOf(evt.pointerId);
  53266. if (index === -1) {
  53267. return;
  53268. }
  53269. _this._pointerPressed.splice(index, 1);
  53270. if (index != 0) {
  53271. return;
  53272. }
  53273. previousPosition = null;
  53274. _this._offsetX = null;
  53275. _this._offsetY = null;
  53276. }
  53277. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  53278. if (!noPreventDefault) {
  53279. evt.preventDefault();
  53280. }
  53281. if (!previousPosition) {
  53282. return;
  53283. }
  53284. var index = _this._pointerPressed.indexOf(evt.pointerId);
  53285. if (index != 0) {
  53286. return;
  53287. }
  53288. _this._offsetX = evt.clientX - previousPosition.x;
  53289. _this._offsetY = -(evt.clientY - previousPosition.y);
  53290. }
  53291. };
  53292. }
  53293. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  53294. if (this._onLostFocus) {
  53295. element.addEventListener("blur", this._onLostFocus);
  53296. }
  53297. };
  53298. FreeCameraTouchInput.prototype.detachControl = function (element) {
  53299. if (this._pointerInput && element) {
  53300. if (this._observer) {
  53301. this.camera.getScene().onPointerObservable.remove(this._observer);
  53302. this._observer = null;
  53303. }
  53304. if (this._onLostFocus) {
  53305. element.removeEventListener("blur", this._onLostFocus);
  53306. this._onLostFocus = null;
  53307. }
  53308. this._pointerPressed = [];
  53309. this._offsetX = null;
  53310. this._offsetY = null;
  53311. this._pointerCount = 0;
  53312. }
  53313. };
  53314. FreeCameraTouchInput.prototype.checkInputs = function () {
  53315. if (this._offsetX && this._offsetY) {
  53316. var camera = this.camera;
  53317. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  53318. if (this._pointerPressed.length > 1) {
  53319. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  53320. }
  53321. else {
  53322. var speed = camera._computeLocalCameraSpeed();
  53323. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  53324. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  53325. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  53326. }
  53327. }
  53328. };
  53329. FreeCameraTouchInput.prototype.getClassName = function () {
  53330. return "FreeCameraTouchInput";
  53331. };
  53332. FreeCameraTouchInput.prototype.getSimpleName = function () {
  53333. return "touch";
  53334. };
  53335. __decorate([
  53336. BABYLON.serialize()
  53337. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  53338. __decorate([
  53339. BABYLON.serialize()
  53340. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  53341. return FreeCameraTouchInput;
  53342. }());
  53343. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  53344. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  53345. })(BABYLON || (BABYLON = {}));
  53346. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  53347. /// <reference path="babylon.freeCamera.ts" />
  53348. var BABYLON;
  53349. (function (BABYLON) {
  53350. // We're mainly based on the logic defined into the FreeCamera code
  53351. var TouchCamera = /** @class */ (function (_super) {
  53352. __extends(TouchCamera, _super);
  53353. //-- end properties for backward compatibility for inputs
  53354. function TouchCamera(name, position, scene) {
  53355. var _this = _super.call(this, name, position, scene) || this;
  53356. _this.inputs.addTouch();
  53357. _this._setupInputs();
  53358. return _this;
  53359. }
  53360. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  53361. //-- Begin properties for backward compatibility for inputs
  53362. get: function () {
  53363. var touch = this.inputs.attached["touch"];
  53364. if (touch)
  53365. return touch.touchAngularSensibility;
  53366. return 0;
  53367. },
  53368. set: function (value) {
  53369. var touch = this.inputs.attached["touch"];
  53370. if (touch)
  53371. touch.touchAngularSensibility = value;
  53372. },
  53373. enumerable: true,
  53374. configurable: true
  53375. });
  53376. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  53377. get: function () {
  53378. var touch = this.inputs.attached["touch"];
  53379. if (touch)
  53380. return touch.touchMoveSensibility;
  53381. return 0;
  53382. },
  53383. set: function (value) {
  53384. var touch = this.inputs.attached["touch"];
  53385. if (touch)
  53386. touch.touchMoveSensibility = value;
  53387. },
  53388. enumerable: true,
  53389. configurable: true
  53390. });
  53391. TouchCamera.prototype.getClassName = function () {
  53392. return "TouchCamera";
  53393. };
  53394. TouchCamera.prototype._setupInputs = function () {
  53395. var mouse = this.inputs.attached["mouse"];
  53396. if (mouse) {
  53397. mouse.touchEnabled = false;
  53398. }
  53399. };
  53400. return TouchCamera;
  53401. }(BABYLON.FreeCamera));
  53402. BABYLON.TouchCamera = TouchCamera;
  53403. })(BABYLON || (BABYLON = {}));
  53404. //# sourceMappingURL=babylon.touchCamera.js.map
  53405. var BABYLON;
  53406. (function (BABYLON) {
  53407. var ProceduralTexture = /** @class */ (function (_super) {
  53408. __extends(ProceduralTexture, _super);
  53409. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  53410. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53411. if (isCube === void 0) { isCube = false; }
  53412. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  53413. _this.isCube = isCube;
  53414. _this.isEnabled = true;
  53415. _this._currentRefreshId = -1;
  53416. _this._refreshRate = 1;
  53417. _this._vertexBuffers = {};
  53418. _this._uniforms = new Array();
  53419. _this._samplers = new Array();
  53420. _this._textures = {};
  53421. _this._floats = {};
  53422. _this._floatsArrays = {};
  53423. _this._colors3 = {};
  53424. _this._colors4 = {};
  53425. _this._vectors2 = {};
  53426. _this._vectors3 = {};
  53427. _this._matrices = {};
  53428. _this._fallbackTextureUsed = false;
  53429. scene._proceduralTextures.push(_this);
  53430. _this.name = name;
  53431. _this.isRenderTarget = true;
  53432. _this._size = size;
  53433. _this._generateMipMaps = generateMipMaps;
  53434. _this.setFragment(fragment);
  53435. _this._fallbackTexture = fallbackTexture;
  53436. var engine = scene.getEngine();
  53437. if (isCube) {
  53438. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  53439. _this.setFloat("face", 0);
  53440. }
  53441. else {
  53442. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  53443. }
  53444. // VBO
  53445. var vertices = [];
  53446. vertices.push(1, 1);
  53447. vertices.push(-1, 1);
  53448. vertices.push(-1, -1);
  53449. vertices.push(1, -1);
  53450. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  53451. _this._createIndexBuffer();
  53452. return _this;
  53453. }
  53454. ProceduralTexture.prototype._createIndexBuffer = function () {
  53455. var engine = this.getScene().getEngine();
  53456. // Indices
  53457. var indices = [];
  53458. indices.push(0);
  53459. indices.push(1);
  53460. indices.push(2);
  53461. indices.push(0);
  53462. indices.push(2);
  53463. indices.push(3);
  53464. this._indexBuffer = engine.createIndexBuffer(indices);
  53465. };
  53466. ProceduralTexture.prototype._rebuild = function () {
  53467. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  53468. this._createIndexBuffer();
  53469. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  53470. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  53471. }
  53472. };
  53473. ProceduralTexture.prototype.reset = function () {
  53474. if (this._effect === undefined) {
  53475. return;
  53476. }
  53477. var engine = this.getScene().getEngine();
  53478. engine._releaseEffect(this._effect);
  53479. };
  53480. ProceduralTexture.prototype.isReady = function () {
  53481. var _this = this;
  53482. var engine = this.getScene().getEngine();
  53483. var shaders;
  53484. if (!this._fragment) {
  53485. return false;
  53486. }
  53487. if (this._fallbackTextureUsed) {
  53488. return true;
  53489. }
  53490. if (this._fragment.fragmentElement !== undefined) {
  53491. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  53492. }
  53493. else {
  53494. shaders = { vertex: "procedural", fragment: this._fragment };
  53495. }
  53496. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  53497. _this.releaseInternalTexture();
  53498. if (_this._fallbackTexture) {
  53499. _this._texture = _this._fallbackTexture._texture;
  53500. _this._texture.incrementReferences();
  53501. }
  53502. _this._fallbackTextureUsed = true;
  53503. });
  53504. return this._effect.isReady();
  53505. };
  53506. ProceduralTexture.prototype.resetRefreshCounter = function () {
  53507. this._currentRefreshId = -1;
  53508. };
  53509. ProceduralTexture.prototype.setFragment = function (fragment) {
  53510. this._fragment = fragment;
  53511. };
  53512. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  53513. get: function () {
  53514. return this._refreshRate;
  53515. },
  53516. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  53517. set: function (value) {
  53518. this._refreshRate = value;
  53519. this.resetRefreshCounter();
  53520. },
  53521. enumerable: true,
  53522. configurable: true
  53523. });
  53524. ProceduralTexture.prototype._shouldRender = function () {
  53525. if (!this.isEnabled || !this.isReady() || !this._texture) {
  53526. return false;
  53527. }
  53528. if (this._fallbackTextureUsed) {
  53529. return false;
  53530. }
  53531. if (this._currentRefreshId === -1) {
  53532. this._currentRefreshId = 1;
  53533. return true;
  53534. }
  53535. if (this.refreshRate === this._currentRefreshId) {
  53536. this._currentRefreshId = 1;
  53537. return true;
  53538. }
  53539. this._currentRefreshId++;
  53540. return false;
  53541. };
  53542. ProceduralTexture.prototype.getRenderSize = function () {
  53543. return this._size;
  53544. };
  53545. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  53546. if (this._fallbackTextureUsed) {
  53547. return;
  53548. }
  53549. this.releaseInternalTexture();
  53550. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  53551. };
  53552. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  53553. if (this._uniforms.indexOf(uniformName) === -1) {
  53554. this._uniforms.push(uniformName);
  53555. }
  53556. };
  53557. ProceduralTexture.prototype.setTexture = function (name, texture) {
  53558. if (this._samplers.indexOf(name) === -1) {
  53559. this._samplers.push(name);
  53560. }
  53561. this._textures[name] = texture;
  53562. return this;
  53563. };
  53564. ProceduralTexture.prototype.setFloat = function (name, value) {
  53565. this._checkUniform(name);
  53566. this._floats[name] = value;
  53567. return this;
  53568. };
  53569. ProceduralTexture.prototype.setFloats = function (name, value) {
  53570. this._checkUniform(name);
  53571. this._floatsArrays[name] = value;
  53572. return this;
  53573. };
  53574. ProceduralTexture.prototype.setColor3 = function (name, value) {
  53575. this._checkUniform(name);
  53576. this._colors3[name] = value;
  53577. return this;
  53578. };
  53579. ProceduralTexture.prototype.setColor4 = function (name, value) {
  53580. this._checkUniform(name);
  53581. this._colors4[name] = value;
  53582. return this;
  53583. };
  53584. ProceduralTexture.prototype.setVector2 = function (name, value) {
  53585. this._checkUniform(name);
  53586. this._vectors2[name] = value;
  53587. return this;
  53588. };
  53589. ProceduralTexture.prototype.setVector3 = function (name, value) {
  53590. this._checkUniform(name);
  53591. this._vectors3[name] = value;
  53592. return this;
  53593. };
  53594. ProceduralTexture.prototype.setMatrix = function (name, value) {
  53595. this._checkUniform(name);
  53596. this._matrices[name] = value;
  53597. return this;
  53598. };
  53599. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  53600. var scene = this.getScene();
  53601. var engine = scene.getEngine();
  53602. // Render
  53603. engine.enableEffect(this._effect);
  53604. engine.setState(false);
  53605. // Texture
  53606. for (var name in this._textures) {
  53607. this._effect.setTexture(name, this._textures[name]);
  53608. }
  53609. // Float
  53610. for (name in this._floats) {
  53611. this._effect.setFloat(name, this._floats[name]);
  53612. }
  53613. // Floats
  53614. for (name in this._floatsArrays) {
  53615. this._effect.setArray(name, this._floatsArrays[name]);
  53616. }
  53617. // Color3
  53618. for (name in this._colors3) {
  53619. this._effect.setColor3(name, this._colors3[name]);
  53620. }
  53621. // Color4
  53622. for (name in this._colors4) {
  53623. var color = this._colors4[name];
  53624. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  53625. }
  53626. // Vector2
  53627. for (name in this._vectors2) {
  53628. this._effect.setVector2(name, this._vectors2[name]);
  53629. }
  53630. // Vector3
  53631. for (name in this._vectors3) {
  53632. this._effect.setVector3(name, this._vectors3[name]);
  53633. }
  53634. // Matrix
  53635. for (name in this._matrices) {
  53636. this._effect.setMatrix(name, this._matrices[name]);
  53637. }
  53638. if (this.isCube) {
  53639. for (var face = 0; face < 6; face++) {
  53640. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  53641. // VBOs
  53642. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  53643. this._effect.setFloat("face", face);
  53644. // Clear
  53645. engine.clear(scene.clearColor, true, true, true);
  53646. // Draw order
  53647. engine.draw(true, 0, 6);
  53648. // Mipmaps
  53649. if (face === 5) {
  53650. engine.generateMipMapsForCubemap(this._texture);
  53651. }
  53652. }
  53653. }
  53654. else {
  53655. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  53656. // VBOs
  53657. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  53658. // Clear
  53659. engine.clear(scene.clearColor, true, true, true);
  53660. // Draw order
  53661. engine.draw(true, 0, 6);
  53662. }
  53663. // Unbind
  53664. engine.unBindFramebuffer(this._texture, this.isCube);
  53665. if (this.onGenerated) {
  53666. this.onGenerated();
  53667. }
  53668. };
  53669. ProceduralTexture.prototype.clone = function () {
  53670. var textureSize = this.getSize();
  53671. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  53672. // Base texture
  53673. newTexture.hasAlpha = this.hasAlpha;
  53674. newTexture.level = this.level;
  53675. // RenderTarget Texture
  53676. newTexture.coordinatesMode = this.coordinatesMode;
  53677. return newTexture;
  53678. };
  53679. ProceduralTexture.prototype.dispose = function () {
  53680. var index = this.getScene()._proceduralTextures.indexOf(this);
  53681. if (index >= 0) {
  53682. this.getScene()._proceduralTextures.splice(index, 1);
  53683. }
  53684. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  53685. if (vertexBuffer) {
  53686. vertexBuffer.dispose();
  53687. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  53688. }
  53689. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  53690. this._indexBuffer = null;
  53691. }
  53692. _super.prototype.dispose.call(this);
  53693. };
  53694. return ProceduralTexture;
  53695. }(BABYLON.Texture));
  53696. BABYLON.ProceduralTexture = ProceduralTexture;
  53697. })(BABYLON || (BABYLON = {}));
  53698. //# sourceMappingURL=babylon.proceduralTexture.js.map
  53699. /// <reference path="babylon.proceduralTexture.ts" />
  53700. var BABYLON;
  53701. (function (BABYLON) {
  53702. var CustomProceduralTexture = /** @class */ (function (_super) {
  53703. __extends(CustomProceduralTexture, _super);
  53704. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  53705. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  53706. _this._animate = true;
  53707. _this._time = 0;
  53708. _this._texturePath = texturePath;
  53709. //Try to load json
  53710. _this.loadJson(texturePath);
  53711. _this.refreshRate = 1;
  53712. return _this;
  53713. }
  53714. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  53715. var _this = this;
  53716. var that = this;
  53717. function noConfigFile() {
  53718. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  53719. try {
  53720. that.setFragment(that._texturePath);
  53721. }
  53722. catch (ex) {
  53723. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  53724. }
  53725. }
  53726. var configFileUrl = jsonUrl + "/config.json";
  53727. var xhr = new XMLHttpRequest();
  53728. xhr.open("GET", configFileUrl, true);
  53729. xhr.addEventListener("load", function () {
  53730. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  53731. try {
  53732. _this._config = JSON.parse(xhr.response);
  53733. _this.updateShaderUniforms();
  53734. _this.updateTextures();
  53735. _this.setFragment(_this._texturePath + "/custom");
  53736. _this._animate = _this._config.animate;
  53737. _this.refreshRate = _this._config.refreshrate;
  53738. }
  53739. catch (ex) {
  53740. noConfigFile();
  53741. }
  53742. }
  53743. else {
  53744. noConfigFile();
  53745. }
  53746. }, false);
  53747. xhr.addEventListener("error", function () {
  53748. noConfigFile();
  53749. }, false);
  53750. try {
  53751. xhr.send();
  53752. }
  53753. catch (ex) {
  53754. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  53755. }
  53756. };
  53757. CustomProceduralTexture.prototype.isReady = function () {
  53758. if (!_super.prototype.isReady.call(this)) {
  53759. return false;
  53760. }
  53761. for (var name in this._textures) {
  53762. var texture = this._textures[name];
  53763. if (!texture.isReady()) {
  53764. return false;
  53765. }
  53766. }
  53767. return true;
  53768. };
  53769. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  53770. if (this._animate) {
  53771. this._time += this.getScene().getAnimationRatio() * 0.03;
  53772. this.updateShaderUniforms();
  53773. }
  53774. _super.prototype.render.call(this, useCameraPostProcess);
  53775. };
  53776. CustomProceduralTexture.prototype.updateTextures = function () {
  53777. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  53778. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  53779. }
  53780. };
  53781. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  53782. if (this._config) {
  53783. for (var j = 0; j < this._config.uniforms.length; j++) {
  53784. var uniform = this._config.uniforms[j];
  53785. switch (uniform.type) {
  53786. case "float":
  53787. this.setFloat(uniform.name, uniform.value);
  53788. break;
  53789. case "color3":
  53790. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  53791. break;
  53792. case "color4":
  53793. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  53794. break;
  53795. case "vector2":
  53796. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  53797. break;
  53798. case "vector3":
  53799. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  53800. break;
  53801. }
  53802. }
  53803. }
  53804. this.setFloat("time", this._time);
  53805. };
  53806. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  53807. get: function () {
  53808. return this._animate;
  53809. },
  53810. set: function (value) {
  53811. this._animate = value;
  53812. },
  53813. enumerable: true,
  53814. configurable: true
  53815. });
  53816. return CustomProceduralTexture;
  53817. }(BABYLON.ProceduralTexture));
  53818. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  53819. })(BABYLON || (BABYLON = {}));
  53820. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  53821. var BABYLON;
  53822. (function (BABYLON) {
  53823. var FreeCameraGamepadInput = /** @class */ (function () {
  53824. function FreeCameraGamepadInput() {
  53825. this.gamepadAngularSensibility = 200;
  53826. this.gamepadMoveSensibility = 40;
  53827. // private members
  53828. this._cameraTransform = BABYLON.Matrix.Identity();
  53829. this._deltaTransform = BABYLON.Vector3.Zero();
  53830. this._vector3 = BABYLON.Vector3.Zero();
  53831. this._vector2 = BABYLON.Vector2.Zero();
  53832. }
  53833. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  53834. var _this = this;
  53835. var manager = this.camera.getScene().gamepadManager;
  53836. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  53837. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  53838. // prioritize XBOX gamepads.
  53839. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  53840. _this.gamepad = gamepad;
  53841. }
  53842. }
  53843. });
  53844. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  53845. if (_this.gamepad === gamepad) {
  53846. _this.gamepad = null;
  53847. }
  53848. });
  53849. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  53850. };
  53851. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  53852. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  53853. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  53854. this.gamepad = null;
  53855. };
  53856. FreeCameraGamepadInput.prototype.checkInputs = function () {
  53857. if (this.gamepad && this.gamepad.leftStick) {
  53858. var camera = this.camera;
  53859. var LSValues = this.gamepad.leftStick;
  53860. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  53861. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  53862. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  53863. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  53864. var RSValues = this.gamepad.rightStick;
  53865. if (RSValues) {
  53866. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  53867. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  53868. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  53869. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  53870. }
  53871. else {
  53872. RSValues = { x: 0, y: 0 };
  53873. }
  53874. if (!camera.rotationQuaternion) {
  53875. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  53876. }
  53877. else {
  53878. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  53879. }
  53880. var speed = camera._computeLocalCameraSpeed() * 50.0;
  53881. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  53882. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  53883. camera.cameraDirection.addInPlace(this._deltaTransform);
  53884. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  53885. camera.cameraRotation.addInPlace(this._vector2);
  53886. }
  53887. };
  53888. FreeCameraGamepadInput.prototype.getClassName = function () {
  53889. return "FreeCameraGamepadInput";
  53890. };
  53891. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  53892. return "gamepad";
  53893. };
  53894. __decorate([
  53895. BABYLON.serialize()
  53896. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  53897. __decorate([
  53898. BABYLON.serialize()
  53899. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  53900. return FreeCameraGamepadInput;
  53901. }());
  53902. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  53903. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  53904. })(BABYLON || (BABYLON = {}));
  53905. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  53906. var BABYLON;
  53907. (function (BABYLON) {
  53908. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  53909. function ArcRotateCameraGamepadInput() {
  53910. this.gamepadRotationSensibility = 80;
  53911. this.gamepadMoveSensibility = 40;
  53912. }
  53913. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  53914. var _this = this;
  53915. var manager = this.camera.getScene().gamepadManager;
  53916. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  53917. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  53918. // prioritize XBOX gamepads.
  53919. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  53920. _this.gamepad = gamepad;
  53921. }
  53922. }
  53923. });
  53924. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  53925. if (_this.gamepad === gamepad) {
  53926. _this.gamepad = null;
  53927. }
  53928. });
  53929. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  53930. };
  53931. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  53932. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  53933. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  53934. this.gamepad = null;
  53935. };
  53936. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  53937. if (this.gamepad) {
  53938. var camera = this.camera;
  53939. var RSValues = this.gamepad.rightStick;
  53940. if (RSValues) {
  53941. if (RSValues.x != 0) {
  53942. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  53943. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  53944. camera.inertialAlphaOffset += normalizedRX;
  53945. }
  53946. }
  53947. if (RSValues.y != 0) {
  53948. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  53949. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  53950. camera.inertialBetaOffset += normalizedRY;
  53951. }
  53952. }
  53953. }
  53954. var LSValues = this.gamepad.leftStick;
  53955. if (LSValues && LSValues.y != 0) {
  53956. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  53957. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  53958. this.camera.inertialRadiusOffset -= normalizedLY;
  53959. }
  53960. }
  53961. }
  53962. };
  53963. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  53964. return "ArcRotateCameraGamepadInput";
  53965. };
  53966. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  53967. return "gamepad";
  53968. };
  53969. __decorate([
  53970. BABYLON.serialize()
  53971. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  53972. __decorate([
  53973. BABYLON.serialize()
  53974. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  53975. return ArcRotateCameraGamepadInput;
  53976. }());
  53977. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  53978. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  53979. })(BABYLON || (BABYLON = {}));
  53980. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  53981. var BABYLON;
  53982. (function (BABYLON) {
  53983. var GamepadManager = /** @class */ (function () {
  53984. function GamepadManager() {
  53985. var _this = this;
  53986. this._babylonGamepads = [];
  53987. this._oneGamepadConnected = false;
  53988. this._isMonitoring = false;
  53989. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  53990. if (!BABYLON.Tools.IsWindowObjectExist()) {
  53991. this._gamepadEventSupported = false;
  53992. }
  53993. else {
  53994. this._gamepadEventSupported = 'GamepadEvent' in window;
  53995. this._gamepadSupport = (navigator.getGamepads ||
  53996. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  53997. }
  53998. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  53999. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  54000. for (var i in _this._babylonGamepads) {
  54001. var gamepad = _this._babylonGamepads[i];
  54002. if (gamepad && gamepad._isConnected) {
  54003. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  54004. }
  54005. }
  54006. });
  54007. this._onGamepadConnectedEvent = function (evt) {
  54008. var gamepad = evt.gamepad;
  54009. if (gamepad.index in _this._babylonGamepads) {
  54010. if (_this._babylonGamepads[gamepad.index].isConnected) {
  54011. return;
  54012. }
  54013. }
  54014. var newGamepad;
  54015. if (_this._babylonGamepads[gamepad.index]) {
  54016. newGamepad = _this._babylonGamepads[gamepad.index];
  54017. newGamepad.browserGamepad = gamepad;
  54018. newGamepad._isConnected = true;
  54019. }
  54020. else {
  54021. newGamepad = _this._addNewGamepad(gamepad);
  54022. }
  54023. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  54024. _this._startMonitoringGamepads();
  54025. };
  54026. this._onGamepadDisconnectedEvent = function (evt) {
  54027. var gamepad = evt.gamepad;
  54028. // Remove the gamepad from the list of gamepads to monitor.
  54029. for (var i in _this._babylonGamepads) {
  54030. if (_this._babylonGamepads[i].index === gamepad.index) {
  54031. var disconnectedGamepad = _this._babylonGamepads[i];
  54032. disconnectedGamepad._isConnected = false;
  54033. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  54034. break;
  54035. }
  54036. }
  54037. };
  54038. if (this._gamepadSupport) {
  54039. //first add already-connected gamepads
  54040. this._updateGamepadObjects();
  54041. if (this._babylonGamepads.length) {
  54042. this._startMonitoringGamepads();
  54043. }
  54044. // Checking if the gamepad connected event is supported (like in Firefox)
  54045. if (this._gamepadEventSupported) {
  54046. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  54047. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  54048. }
  54049. else {
  54050. this._startMonitoringGamepads();
  54051. }
  54052. }
  54053. }
  54054. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  54055. get: function () {
  54056. return this._babylonGamepads;
  54057. },
  54058. enumerable: true,
  54059. configurable: true
  54060. });
  54061. GamepadManager.prototype.getGamepadByType = function (type) {
  54062. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  54063. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  54064. var gamepad = _a[_i];
  54065. if (gamepad && gamepad.type === type) {
  54066. return gamepad;
  54067. }
  54068. }
  54069. return null;
  54070. };
  54071. GamepadManager.prototype.dispose = function () {
  54072. if (this._gamepadEventSupported) {
  54073. if (this._onGamepadConnectedEvent) {
  54074. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  54075. }
  54076. if (this._onGamepadDisconnectedEvent) {
  54077. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  54078. }
  54079. this._onGamepadConnectedEvent = null;
  54080. this._onGamepadDisconnectedEvent = null;
  54081. }
  54082. this._babylonGamepads.forEach(function (gamepad) {
  54083. gamepad.dispose();
  54084. });
  54085. this.onGamepadConnectedObservable.clear();
  54086. this.onGamepadDisconnectedObservable.clear();
  54087. this._oneGamepadConnected = false;
  54088. this._stopMonitoringGamepads();
  54089. this._babylonGamepads = [];
  54090. };
  54091. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  54092. if (!this._oneGamepadConnected) {
  54093. this._oneGamepadConnected = true;
  54094. }
  54095. var newGamepad;
  54096. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  54097. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  54098. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  54099. }
  54100. else if (gamepad.pose) {
  54101. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  54102. }
  54103. else {
  54104. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  54105. }
  54106. this._babylonGamepads[newGamepad.index] = newGamepad;
  54107. return newGamepad;
  54108. };
  54109. GamepadManager.prototype._startMonitoringGamepads = function () {
  54110. if (!this._isMonitoring) {
  54111. this._isMonitoring = true;
  54112. this._checkGamepadsStatus();
  54113. }
  54114. };
  54115. GamepadManager.prototype._stopMonitoringGamepads = function () {
  54116. this._isMonitoring = false;
  54117. };
  54118. GamepadManager.prototype._checkGamepadsStatus = function () {
  54119. var _this = this;
  54120. // Hack to be compatible Chrome
  54121. this._updateGamepadObjects();
  54122. for (var i in this._babylonGamepads) {
  54123. var gamepad = this._babylonGamepads[i];
  54124. if (!gamepad || !gamepad.isConnected) {
  54125. continue;
  54126. }
  54127. gamepad.update();
  54128. }
  54129. if (this._isMonitoring) {
  54130. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  54131. }
  54132. };
  54133. // This function is called only on Chrome, which does not properly support
  54134. // connection/disconnection events and forces you to recopy again the gamepad object
  54135. GamepadManager.prototype._updateGamepadObjects = function () {
  54136. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  54137. for (var i = 0; i < gamepads.length; i++) {
  54138. if (gamepads[i]) {
  54139. if (!this._babylonGamepads[gamepads[i].index]) {
  54140. var newGamepad = this._addNewGamepad(gamepads[i]);
  54141. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  54142. }
  54143. else {
  54144. // Forced to copy again this object for Chrome for unknown reason
  54145. this._babylonGamepads[i].browserGamepad = gamepads[i];
  54146. if (!this._babylonGamepads[i].isConnected) {
  54147. this._babylonGamepads[i]._isConnected = true;
  54148. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  54149. }
  54150. }
  54151. }
  54152. }
  54153. };
  54154. return GamepadManager;
  54155. }());
  54156. BABYLON.GamepadManager = GamepadManager;
  54157. })(BABYLON || (BABYLON = {}));
  54158. //# sourceMappingURL=babylon.gamepadManager.js.map
  54159. var BABYLON;
  54160. (function (BABYLON) {
  54161. var StickValues = /** @class */ (function () {
  54162. function StickValues(x, y) {
  54163. this.x = x;
  54164. this.y = y;
  54165. }
  54166. return StickValues;
  54167. }());
  54168. BABYLON.StickValues = StickValues;
  54169. var Gamepad = /** @class */ (function () {
  54170. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  54171. if (leftStickX === void 0) { leftStickX = 0; }
  54172. if (leftStickY === void 0) { leftStickY = 1; }
  54173. if (rightStickX === void 0) { rightStickX = 2; }
  54174. if (rightStickY === void 0) { rightStickY = 3; }
  54175. this.id = id;
  54176. this.index = index;
  54177. this.browserGamepad = browserGamepad;
  54178. this._isConnected = true;
  54179. this.type = Gamepad.GAMEPAD;
  54180. this._leftStickAxisX = leftStickX;
  54181. this._leftStickAxisY = leftStickY;
  54182. this._rightStickAxisX = rightStickX;
  54183. this._rightStickAxisY = rightStickY;
  54184. if (this.browserGamepad.axes.length >= 2) {
  54185. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  54186. }
  54187. if (this.browserGamepad.axes.length >= 4) {
  54188. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  54189. }
  54190. }
  54191. Object.defineProperty(Gamepad.prototype, "isConnected", {
  54192. get: function () {
  54193. return this._isConnected;
  54194. },
  54195. enumerable: true,
  54196. configurable: true
  54197. });
  54198. Gamepad.prototype.onleftstickchanged = function (callback) {
  54199. this._onleftstickchanged = callback;
  54200. };
  54201. Gamepad.prototype.onrightstickchanged = function (callback) {
  54202. this._onrightstickchanged = callback;
  54203. };
  54204. Object.defineProperty(Gamepad.prototype, "leftStick", {
  54205. get: function () {
  54206. return this._leftStick;
  54207. },
  54208. set: function (newValues) {
  54209. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  54210. this._onleftstickchanged(newValues);
  54211. }
  54212. this._leftStick = newValues;
  54213. },
  54214. enumerable: true,
  54215. configurable: true
  54216. });
  54217. Object.defineProperty(Gamepad.prototype, "rightStick", {
  54218. get: function () {
  54219. return this._rightStick;
  54220. },
  54221. set: function (newValues) {
  54222. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  54223. this._onrightstickchanged(newValues);
  54224. }
  54225. this._rightStick = newValues;
  54226. },
  54227. enumerable: true,
  54228. configurable: true
  54229. });
  54230. Gamepad.prototype.update = function () {
  54231. if (this._leftStick) {
  54232. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  54233. }
  54234. if (this._rightStick) {
  54235. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  54236. }
  54237. };
  54238. Gamepad.prototype.dispose = function () {
  54239. };
  54240. Gamepad.GAMEPAD = 0;
  54241. Gamepad.GENERIC = 1;
  54242. Gamepad.XBOX = 2;
  54243. Gamepad.POSE_ENABLED = 3;
  54244. return Gamepad;
  54245. }());
  54246. BABYLON.Gamepad = Gamepad;
  54247. var GenericPad = /** @class */ (function (_super) {
  54248. __extends(GenericPad, _super);
  54249. function GenericPad(id, index, browserGamepad) {
  54250. var _this = _super.call(this, id, index, browserGamepad) || this;
  54251. _this.onButtonDownObservable = new BABYLON.Observable();
  54252. _this.onButtonUpObservable = new BABYLON.Observable();
  54253. _this.type = Gamepad.GENERIC;
  54254. _this._buttons = new Array(browserGamepad.buttons.length);
  54255. return _this;
  54256. }
  54257. GenericPad.prototype.onbuttondown = function (callback) {
  54258. this._onbuttondown = callback;
  54259. };
  54260. GenericPad.prototype.onbuttonup = function (callback) {
  54261. this._onbuttonup = callback;
  54262. };
  54263. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  54264. if (newValue !== currentValue) {
  54265. if (newValue === 1) {
  54266. if (this._onbuttondown) {
  54267. this._onbuttondown(buttonIndex);
  54268. }
  54269. this.onButtonDownObservable.notifyObservers(buttonIndex);
  54270. }
  54271. if (newValue === 0) {
  54272. if (this._onbuttonup) {
  54273. this._onbuttonup(buttonIndex);
  54274. }
  54275. this.onButtonUpObservable.notifyObservers(buttonIndex);
  54276. }
  54277. }
  54278. return newValue;
  54279. };
  54280. GenericPad.prototype.update = function () {
  54281. _super.prototype.update.call(this);
  54282. for (var index = 0; index < this._buttons.length; index++) {
  54283. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  54284. }
  54285. };
  54286. return GenericPad;
  54287. }(Gamepad));
  54288. BABYLON.GenericPad = GenericPad;
  54289. })(BABYLON || (BABYLON = {}));
  54290. //# sourceMappingURL=babylon.gamepad.js.map
  54291. var BABYLON;
  54292. (function (BABYLON) {
  54293. var Xbox360Button;
  54294. (function (Xbox360Button) {
  54295. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  54296. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  54297. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  54298. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  54299. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  54300. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  54301. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  54302. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  54303. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  54304. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  54305. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  54306. var Xbox360Dpad;
  54307. (function (Xbox360Dpad) {
  54308. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  54309. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  54310. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  54311. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  54312. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  54313. var Xbox360Pad = /** @class */ (function (_super) {
  54314. __extends(Xbox360Pad, _super);
  54315. function Xbox360Pad(id, index, gamepad, xboxOne) {
  54316. if (xboxOne === void 0) { xboxOne = false; }
  54317. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  54318. _this._leftTrigger = 0;
  54319. _this._rightTrigger = 0;
  54320. _this.onButtonDownObservable = new BABYLON.Observable();
  54321. _this.onButtonUpObservable = new BABYLON.Observable();
  54322. _this.onPadDownObservable = new BABYLON.Observable();
  54323. _this.onPadUpObservable = new BABYLON.Observable();
  54324. _this._buttonA = 0;
  54325. _this._buttonB = 0;
  54326. _this._buttonX = 0;
  54327. _this._buttonY = 0;
  54328. _this._buttonBack = 0;
  54329. _this._buttonStart = 0;
  54330. _this._buttonLB = 0;
  54331. _this._buttonRB = 0;
  54332. _this._buttonLeftStick = 0;
  54333. _this._buttonRightStick = 0;
  54334. _this._dPadUp = 0;
  54335. _this._dPadDown = 0;
  54336. _this._dPadLeft = 0;
  54337. _this._dPadRight = 0;
  54338. _this._isXboxOnePad = false;
  54339. _this.type = BABYLON.Gamepad.XBOX;
  54340. _this._isXboxOnePad = xboxOne;
  54341. return _this;
  54342. }
  54343. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  54344. this._onlefttriggerchanged = callback;
  54345. };
  54346. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  54347. this._onrighttriggerchanged = callback;
  54348. };
  54349. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  54350. get: function () {
  54351. return this._leftTrigger;
  54352. },
  54353. set: function (newValue) {
  54354. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  54355. this._onlefttriggerchanged(newValue);
  54356. }
  54357. this._leftTrigger = newValue;
  54358. },
  54359. enumerable: true,
  54360. configurable: true
  54361. });
  54362. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  54363. get: function () {
  54364. return this._rightTrigger;
  54365. },
  54366. set: function (newValue) {
  54367. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  54368. this._onrighttriggerchanged(newValue);
  54369. }
  54370. this._rightTrigger = newValue;
  54371. },
  54372. enumerable: true,
  54373. configurable: true
  54374. });
  54375. Xbox360Pad.prototype.onbuttondown = function (callback) {
  54376. this._onbuttondown = callback;
  54377. };
  54378. Xbox360Pad.prototype.onbuttonup = function (callback) {
  54379. this._onbuttonup = callback;
  54380. };
  54381. Xbox360Pad.prototype.ondpaddown = function (callback) {
  54382. this._ondpaddown = callback;
  54383. };
  54384. Xbox360Pad.prototype.ondpadup = function (callback) {
  54385. this._ondpadup = callback;
  54386. };
  54387. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  54388. if (newValue !== currentValue) {
  54389. if (newValue === 1) {
  54390. if (this._onbuttondown) {
  54391. this._onbuttondown(buttonType);
  54392. }
  54393. this.onButtonDownObservable.notifyObservers(buttonType);
  54394. }
  54395. if (newValue === 0) {
  54396. if (this._onbuttonup) {
  54397. this._onbuttonup(buttonType);
  54398. }
  54399. this.onButtonUpObservable.notifyObservers(buttonType);
  54400. }
  54401. }
  54402. return newValue;
  54403. };
  54404. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  54405. if (newValue !== currentValue) {
  54406. if (newValue === 1) {
  54407. if (this._ondpaddown) {
  54408. this._ondpaddown(buttonType);
  54409. }
  54410. this.onPadDownObservable.notifyObservers(buttonType);
  54411. }
  54412. if (newValue === 0) {
  54413. if (this._ondpadup) {
  54414. this._ondpadup(buttonType);
  54415. }
  54416. this.onPadUpObservable.notifyObservers(buttonType);
  54417. }
  54418. }
  54419. return newValue;
  54420. };
  54421. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  54422. get: function () {
  54423. return this._buttonA;
  54424. },
  54425. set: function (value) {
  54426. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  54427. },
  54428. enumerable: true,
  54429. configurable: true
  54430. });
  54431. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  54432. get: function () {
  54433. return this._buttonB;
  54434. },
  54435. set: function (value) {
  54436. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  54437. },
  54438. enumerable: true,
  54439. configurable: true
  54440. });
  54441. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  54442. get: function () {
  54443. return this._buttonX;
  54444. },
  54445. set: function (value) {
  54446. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  54447. },
  54448. enumerable: true,
  54449. configurable: true
  54450. });
  54451. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  54452. get: function () {
  54453. return this._buttonY;
  54454. },
  54455. set: function (value) {
  54456. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  54457. },
  54458. enumerable: true,
  54459. configurable: true
  54460. });
  54461. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  54462. get: function () {
  54463. return this._buttonStart;
  54464. },
  54465. set: function (value) {
  54466. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  54467. },
  54468. enumerable: true,
  54469. configurable: true
  54470. });
  54471. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  54472. get: function () {
  54473. return this._buttonBack;
  54474. },
  54475. set: function (value) {
  54476. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  54477. },
  54478. enumerable: true,
  54479. configurable: true
  54480. });
  54481. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  54482. get: function () {
  54483. return this._buttonLB;
  54484. },
  54485. set: function (value) {
  54486. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  54487. },
  54488. enumerable: true,
  54489. configurable: true
  54490. });
  54491. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  54492. get: function () {
  54493. return this._buttonRB;
  54494. },
  54495. set: function (value) {
  54496. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  54497. },
  54498. enumerable: true,
  54499. configurable: true
  54500. });
  54501. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  54502. get: function () {
  54503. return this._buttonLeftStick;
  54504. },
  54505. set: function (value) {
  54506. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  54507. },
  54508. enumerable: true,
  54509. configurable: true
  54510. });
  54511. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  54512. get: function () {
  54513. return this._buttonRightStick;
  54514. },
  54515. set: function (value) {
  54516. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  54517. },
  54518. enumerable: true,
  54519. configurable: true
  54520. });
  54521. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  54522. get: function () {
  54523. return this._dPadUp;
  54524. },
  54525. set: function (value) {
  54526. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  54527. },
  54528. enumerable: true,
  54529. configurable: true
  54530. });
  54531. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  54532. get: function () {
  54533. return this._dPadDown;
  54534. },
  54535. set: function (value) {
  54536. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  54537. },
  54538. enumerable: true,
  54539. configurable: true
  54540. });
  54541. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  54542. get: function () {
  54543. return this._dPadLeft;
  54544. },
  54545. set: function (value) {
  54546. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  54547. },
  54548. enumerable: true,
  54549. configurable: true
  54550. });
  54551. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  54552. get: function () {
  54553. return this._dPadRight;
  54554. },
  54555. set: function (value) {
  54556. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  54557. },
  54558. enumerable: true,
  54559. configurable: true
  54560. });
  54561. Xbox360Pad.prototype.update = function () {
  54562. _super.prototype.update.call(this);
  54563. if (this._isXboxOnePad) {
  54564. this.buttonA = this.browserGamepad.buttons[0].value;
  54565. this.buttonB = this.browserGamepad.buttons[1].value;
  54566. this.buttonX = this.browserGamepad.buttons[2].value;
  54567. this.buttonY = this.browserGamepad.buttons[3].value;
  54568. this.buttonLB = this.browserGamepad.buttons[4].value;
  54569. this.buttonRB = this.browserGamepad.buttons[5].value;
  54570. this.leftTrigger = this.browserGamepad.axes[2];
  54571. this.rightTrigger = this.browserGamepad.axes[5];
  54572. this.buttonBack = this.browserGamepad.buttons[9].value;
  54573. this.buttonStart = this.browserGamepad.buttons[8].value;
  54574. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  54575. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  54576. this.dPadUp = this.browserGamepad.buttons[11].value;
  54577. this.dPadDown = this.browserGamepad.buttons[12].value;
  54578. this.dPadLeft = this.browserGamepad.buttons[13].value;
  54579. this.dPadRight = this.browserGamepad.buttons[14].value;
  54580. }
  54581. else {
  54582. this.buttonA = this.browserGamepad.buttons[0].value;
  54583. this.buttonB = this.browserGamepad.buttons[1].value;
  54584. this.buttonX = this.browserGamepad.buttons[2].value;
  54585. this.buttonY = this.browserGamepad.buttons[3].value;
  54586. this.buttonLB = this.browserGamepad.buttons[4].value;
  54587. this.buttonRB = this.browserGamepad.buttons[5].value;
  54588. this.leftTrigger = this.browserGamepad.buttons[6].value;
  54589. this.rightTrigger = this.browserGamepad.buttons[7].value;
  54590. this.buttonBack = this.browserGamepad.buttons[8].value;
  54591. this.buttonStart = this.browserGamepad.buttons[9].value;
  54592. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  54593. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  54594. this.dPadUp = this.browserGamepad.buttons[12].value;
  54595. this.dPadDown = this.browserGamepad.buttons[13].value;
  54596. this.dPadLeft = this.browserGamepad.buttons[14].value;
  54597. this.dPadRight = this.browserGamepad.buttons[15].value;
  54598. }
  54599. };
  54600. return Xbox360Pad;
  54601. }(BABYLON.Gamepad));
  54602. BABYLON.Xbox360Pad = Xbox360Pad;
  54603. })(BABYLON || (BABYLON = {}));
  54604. //# sourceMappingURL=babylon.xboxGamepad.js.map
  54605. var BABYLON;
  54606. (function (BABYLON) {
  54607. var PoseEnabledControllerType;
  54608. (function (PoseEnabledControllerType) {
  54609. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  54610. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  54611. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  54612. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  54613. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  54614. var PoseEnabledControllerHelper = /** @class */ (function () {
  54615. function PoseEnabledControllerHelper() {
  54616. }
  54617. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  54618. // Oculus Touch
  54619. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  54620. return new BABYLON.OculusTouchController(vrGamepad);
  54621. }
  54622. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  54623. return new BABYLON.WindowsMotionController(vrGamepad);
  54624. }
  54625. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  54626. return new BABYLON.ViveController(vrGamepad);
  54627. }
  54628. else {
  54629. return new BABYLON.GenericController(vrGamepad);
  54630. }
  54631. };
  54632. return PoseEnabledControllerHelper;
  54633. }());
  54634. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  54635. var PoseEnabledController = /** @class */ (function (_super) {
  54636. __extends(PoseEnabledController, _super);
  54637. function PoseEnabledController(browserGamepad) {
  54638. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  54639. _this.deviceScaleFactor = 1;
  54640. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  54641. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  54642. _this.controllerType = PoseEnabledControllerType.GENERIC;
  54643. _this.position = BABYLON.Vector3.Zero();
  54644. _this.rotationQuaternion = new BABYLON.Quaternion();
  54645. _this.devicePosition = BABYLON.Vector3.Zero();
  54646. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  54647. _this._calculatedPosition = BABYLON.Vector3.Zero();
  54648. _this._calculatedRotation = new BABYLON.Quaternion();
  54649. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  54650. return _this;
  54651. }
  54652. PoseEnabledController.prototype.update = function () {
  54653. _super.prototype.update.call(this);
  54654. var pose = this.browserGamepad.pose;
  54655. this.updateFromDevice(pose);
  54656. if (this._mesh) {
  54657. this._mesh.position.copyFrom(this._calculatedPosition);
  54658. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  54659. }
  54660. };
  54661. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  54662. if (poseData) {
  54663. this.rawPose = poseData;
  54664. if (poseData.position) {
  54665. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  54666. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  54667. this.devicePosition.z *= -1;
  54668. }
  54669. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  54670. this._calculatedPosition.addInPlace(this.position);
  54671. }
  54672. var pose = this.rawPose;
  54673. if (poseData.orientation && pose.orientation) {
  54674. this.deviceRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  54675. if (this._mesh) {
  54676. if (this._mesh.getScene().useRightHandedSystem) {
  54677. this.deviceRotationQuaternion.z *= -1;
  54678. this.deviceRotationQuaternion.w *= -1;
  54679. }
  54680. else {
  54681. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  54682. }
  54683. }
  54684. // if the camera is set, rotate to the camera's rotation
  54685. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  54686. }
  54687. }
  54688. };
  54689. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  54690. if (this._mesh) {
  54691. this._mesh.parent = null;
  54692. }
  54693. this._mesh = mesh;
  54694. if (this._poseControlledCamera) {
  54695. this._mesh.parent = this._poseControlledCamera;
  54696. }
  54697. if (!this._mesh.rotationQuaternion) {
  54698. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  54699. }
  54700. };
  54701. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  54702. this._poseControlledCamera = camera;
  54703. if (this._mesh) {
  54704. this._mesh.parent = this._poseControlledCamera;
  54705. }
  54706. };
  54707. PoseEnabledController.prototype.dispose = function () {
  54708. if (this._mesh) {
  54709. this._mesh.dispose();
  54710. }
  54711. this._mesh = null;
  54712. _super.prototype.dispose.call(this);
  54713. };
  54714. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  54715. get: function () {
  54716. return this._mesh;
  54717. },
  54718. enumerable: true,
  54719. configurable: true
  54720. });
  54721. PoseEnabledController.prototype.getForwardRay = function (length) {
  54722. if (length === void 0) { length = 100; }
  54723. if (!this.mesh) {
  54724. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  54725. }
  54726. var m = this.mesh.getWorldMatrix();
  54727. var origin = m.getTranslation();
  54728. var forward = new BABYLON.Vector3(0, 0, -1);
  54729. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  54730. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  54731. return new BABYLON.Ray(origin, direction, length);
  54732. };
  54733. return PoseEnabledController;
  54734. }(BABYLON.Gamepad));
  54735. BABYLON.PoseEnabledController = PoseEnabledController;
  54736. })(BABYLON || (BABYLON = {}));
  54737. //# sourceMappingURL=babylon.poseEnabledController.js.map
  54738. var BABYLON;
  54739. (function (BABYLON) {
  54740. var WebVRController = /** @class */ (function (_super) {
  54741. __extends(WebVRController, _super);
  54742. function WebVRController(vrGamepad) {
  54743. var _this = _super.call(this, vrGamepad) || this;
  54744. // Observables
  54745. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  54746. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  54747. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  54748. _this.onPadStateChangedObservable = new BABYLON.Observable();
  54749. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  54750. _this.pad = { x: 0, y: 0 };
  54751. // avoid GC, store state in a tmp object
  54752. _this._changes = {
  54753. pressChanged: false,
  54754. touchChanged: false,
  54755. valueChanged: false,
  54756. changed: false
  54757. };
  54758. _this._buttons = new Array(vrGamepad.buttons.length);
  54759. _this.hand = vrGamepad.hand;
  54760. return _this;
  54761. }
  54762. WebVRController.prototype.onButtonStateChange = function (callback) {
  54763. this._onButtonStateChange = callback;
  54764. };
  54765. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  54766. get: function () {
  54767. return this._defaultModel;
  54768. },
  54769. enumerable: true,
  54770. configurable: true
  54771. });
  54772. WebVRController.prototype.update = function () {
  54773. _super.prototype.update.call(this);
  54774. for (var index = 0; index < this._buttons.length; index++) {
  54775. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  54776. }
  54777. ;
  54778. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  54779. this.pad.x = this.leftStick.x;
  54780. this.pad.y = this.leftStick.y;
  54781. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  54782. }
  54783. };
  54784. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  54785. if (!newState) {
  54786. newState = {
  54787. pressed: false,
  54788. touched: false,
  54789. value: 0
  54790. };
  54791. }
  54792. if (!currentState) {
  54793. this._buttons[buttonIndex] = {
  54794. pressed: newState.pressed,
  54795. touched: newState.touched,
  54796. value: newState.value
  54797. };
  54798. return;
  54799. }
  54800. this._checkChanges(newState, currentState);
  54801. if (this._changes.changed) {
  54802. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  54803. this.handleButtonChange(buttonIndex, newState, this._changes);
  54804. }
  54805. this._buttons[buttonIndex].pressed = newState.pressed;
  54806. this._buttons[buttonIndex].touched = newState.touched;
  54807. // oculus triggers are never 0, thou not touched.
  54808. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  54809. };
  54810. WebVRController.prototype._checkChanges = function (newState, currentState) {
  54811. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  54812. this._changes.touchChanged = newState.touched !== currentState.touched;
  54813. this._changes.valueChanged = newState.value !== currentState.value;
  54814. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  54815. return this._changes;
  54816. };
  54817. WebVRController.prototype.dispose = function () {
  54818. _super.prototype.dispose.call(this);
  54819. this.onTriggerStateChangedObservable.clear();
  54820. this.onMainButtonStateChangedObservable.clear();
  54821. this.onSecondaryButtonStateChangedObservable.clear();
  54822. this.onPadStateChangedObservable.clear();
  54823. this.onPadValuesChangedObservable.clear();
  54824. };
  54825. return WebVRController;
  54826. }(BABYLON.PoseEnabledController));
  54827. BABYLON.WebVRController = WebVRController;
  54828. })(BABYLON || (BABYLON = {}));
  54829. //# sourceMappingURL=babylon.webVRController.js.map
  54830. var BABYLON;
  54831. (function (BABYLON) {
  54832. var OculusTouchController = /** @class */ (function (_super) {
  54833. __extends(OculusTouchController, _super);
  54834. function OculusTouchController(vrGamepad) {
  54835. var _this = _super.call(this, vrGamepad) || this;
  54836. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  54837. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  54838. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  54839. return _this;
  54840. }
  54841. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  54842. var _this = this;
  54843. var meshName;
  54844. // Hand
  54845. if (this.hand === 'left') {
  54846. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  54847. }
  54848. else {
  54849. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  54850. }
  54851. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  54852. /*
  54853. Parent Mesh name: oculus_touch_left
  54854. - body
  54855. - trigger
  54856. - thumbstick
  54857. - grip
  54858. - button_y
  54859. - button_x
  54860. - button_enter
  54861. */
  54862. _this._defaultModel = newMeshes[1];
  54863. _this.attachToMesh(_this._defaultModel);
  54864. if (meshLoaded) {
  54865. meshLoaded(_this._defaultModel);
  54866. }
  54867. });
  54868. };
  54869. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  54870. // helper getters for left and right hand.
  54871. get: function () {
  54872. if (this.hand === 'right') {
  54873. return this.onMainButtonStateChangedObservable;
  54874. }
  54875. else {
  54876. throw new Error('No A button on left hand');
  54877. }
  54878. },
  54879. enumerable: true,
  54880. configurable: true
  54881. });
  54882. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  54883. get: function () {
  54884. if (this.hand === 'right') {
  54885. return this.onSecondaryButtonStateChangedObservable;
  54886. }
  54887. else {
  54888. throw new Error('No B button on left hand');
  54889. }
  54890. },
  54891. enumerable: true,
  54892. configurable: true
  54893. });
  54894. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  54895. get: function () {
  54896. if (this.hand === 'left') {
  54897. return this.onMainButtonStateChangedObservable;
  54898. }
  54899. else {
  54900. throw new Error('No X button on right hand');
  54901. }
  54902. },
  54903. enumerable: true,
  54904. configurable: true
  54905. });
  54906. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  54907. get: function () {
  54908. if (this.hand === 'left') {
  54909. return this.onSecondaryButtonStateChangedObservable;
  54910. }
  54911. else {
  54912. throw new Error('No Y button on right hand');
  54913. }
  54914. },
  54915. enumerable: true,
  54916. configurable: true
  54917. });
  54918. /*
  54919. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  54920. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  54921. 2) secondary trigger (same)
  54922. 3) A (right) X (left), touch, pressed = value
  54923. 4) B / Y
  54924. 5) thumb rest
  54925. */
  54926. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  54927. var notifyObject = state; //{ state: state, changes: changes };
  54928. var triggerDirection = this.hand === 'right' ? -1 : 1;
  54929. switch (buttonIdx) {
  54930. case 0:
  54931. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  54932. return;
  54933. case 1:// index trigger
  54934. if (this._defaultModel) {
  54935. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  54936. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  54937. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  54938. }
  54939. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  54940. return;
  54941. case 2:// secondary trigger
  54942. if (this._defaultModel) {
  54943. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  54944. }
  54945. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  54946. return;
  54947. case 3:
  54948. if (this._defaultModel) {
  54949. if (notifyObject.pressed) {
  54950. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  54951. }
  54952. else {
  54953. (this._defaultModel.getChildren()[1]).position.y = 0;
  54954. }
  54955. }
  54956. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  54957. return;
  54958. case 4:
  54959. if (this._defaultModel) {
  54960. if (notifyObject.pressed) {
  54961. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  54962. }
  54963. else {
  54964. (this._defaultModel.getChildren()[2]).position.y = 0;
  54965. }
  54966. }
  54967. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  54968. return;
  54969. case 5:
  54970. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  54971. return;
  54972. }
  54973. };
  54974. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  54975. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  54976. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  54977. return OculusTouchController;
  54978. }(BABYLON.WebVRController));
  54979. BABYLON.OculusTouchController = OculusTouchController;
  54980. })(BABYLON || (BABYLON = {}));
  54981. //# sourceMappingURL=babylon.oculusTouchController.js.map
  54982. var BABYLON;
  54983. (function (BABYLON) {
  54984. var ViveController = /** @class */ (function (_super) {
  54985. __extends(ViveController, _super);
  54986. function ViveController(vrGamepad) {
  54987. var _this = _super.call(this, vrGamepad) || this;
  54988. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  54989. return _this;
  54990. }
  54991. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  54992. var _this = this;
  54993. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  54994. /*
  54995. Parent Mesh name: ViveWand
  54996. - body
  54997. - r_gripper
  54998. - l_gripper
  54999. - menu_button
  55000. - system_button
  55001. - trackpad
  55002. - trigger
  55003. - LED
  55004. */
  55005. _this._defaultModel = newMeshes[1];
  55006. _this.attachToMesh(_this._defaultModel);
  55007. if (meshLoaded) {
  55008. meshLoaded(_this._defaultModel);
  55009. }
  55010. });
  55011. };
  55012. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  55013. get: function () {
  55014. return this.onMainButtonStateChangedObservable;
  55015. },
  55016. enumerable: true,
  55017. configurable: true
  55018. });
  55019. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  55020. get: function () {
  55021. return this.onMainButtonStateChangedObservable;
  55022. },
  55023. enumerable: true,
  55024. configurable: true
  55025. });
  55026. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  55027. get: function () {
  55028. return this.onSecondaryButtonStateChangedObservable;
  55029. },
  55030. enumerable: true,
  55031. configurable: true
  55032. });
  55033. /**
  55034. * Vive mapping:
  55035. * 0: touchpad
  55036. * 1: trigger
  55037. * 2: left AND right buttons
  55038. * 3: menu button
  55039. */
  55040. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  55041. var notifyObject = state; //{ state: state, changes: changes };
  55042. switch (buttonIdx) {
  55043. case 0:
  55044. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  55045. return;
  55046. case 1:// index trigger
  55047. if (this._defaultModel) {
  55048. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  55049. }
  55050. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  55051. return;
  55052. case 2:// left AND right button
  55053. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  55054. return;
  55055. case 3:
  55056. if (this._defaultModel) {
  55057. if (notifyObject.pressed) {
  55058. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  55059. }
  55060. else {
  55061. (this._defaultModel.getChildren()[2]).position.y = 0;
  55062. }
  55063. }
  55064. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  55065. return;
  55066. }
  55067. };
  55068. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  55069. ViveController.MODEL_FILENAME = 'wand.babylon';
  55070. return ViveController;
  55071. }(BABYLON.WebVRController));
  55072. BABYLON.ViveController = ViveController;
  55073. })(BABYLON || (BABYLON = {}));
  55074. //# sourceMappingURL=babylon.viveController.js.map
  55075. var BABYLON;
  55076. (function (BABYLON) {
  55077. var GenericController = /** @class */ (function (_super) {
  55078. __extends(GenericController, _super);
  55079. function GenericController(vrGamepad) {
  55080. return _super.call(this, vrGamepad) || this;
  55081. }
  55082. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  55083. var _this = this;
  55084. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  55085. _this._defaultModel = newMeshes[1];
  55086. _this.attachToMesh(_this._defaultModel);
  55087. if (meshLoaded) {
  55088. meshLoaded(_this._defaultModel);
  55089. }
  55090. });
  55091. };
  55092. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  55093. console.log("Button id: " + buttonIdx + "state: ");
  55094. console.dir(state);
  55095. };
  55096. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  55097. GenericController.MODEL_FILENAME = 'generic.babylon';
  55098. return GenericController;
  55099. }(BABYLON.WebVRController));
  55100. BABYLON.GenericController = GenericController;
  55101. })(BABYLON || (BABYLON = {}));
  55102. //# sourceMappingURL=babylon.genericController.js.map
  55103. var BABYLON;
  55104. (function (BABYLON) {
  55105. var LoadedMeshInfo = /** @class */ (function () {
  55106. function LoadedMeshInfo() {
  55107. this.buttonMeshes = {};
  55108. this.axisMeshes = {};
  55109. }
  55110. return LoadedMeshInfo;
  55111. }());
  55112. var WindowsMotionController = /** @class */ (function (_super) {
  55113. __extends(WindowsMotionController, _super);
  55114. function WindowsMotionController(vrGamepad) {
  55115. var _this = _super.call(this, vrGamepad) || this;
  55116. _this._mapping = {
  55117. // Semantic button names
  55118. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  55119. // A mapping of the button name to glTF model node name
  55120. // that should be transformed by button value.
  55121. buttonMeshNames: {
  55122. 'trigger': 'SELECT',
  55123. 'menu': 'MENU',
  55124. 'grip': 'GRASP',
  55125. 'thumbstick': 'THUMBSTICK_PRESS',
  55126. 'trackpad': 'TOUCHPAD_PRESS'
  55127. },
  55128. // This mapping is used to translate from the Motion Controller to Babylon semantics
  55129. buttonObservableNames: {
  55130. 'trigger': 'onTriggerStateChangedObservable',
  55131. 'menu': 'onSecondaryButtonStateChangedObservable',
  55132. 'grip': 'onMainButtonStateChangedObservable',
  55133. 'thumbstick': 'onPadStateChangedObservable',
  55134. 'trackpad': 'onTrackpadChangedObservable'
  55135. },
  55136. // A mapping of the axis name to glTF model node name
  55137. // that should be transformed by axis value.
  55138. // This array mirrors the browserGamepad.axes array, such that
  55139. // the mesh corresponding to axis 0 is in this array index 0.
  55140. axisMeshNames: [
  55141. 'THUMBSTICK_X',
  55142. 'THUMBSTICK_Y',
  55143. 'TOUCHPAD_TOUCH_X',
  55144. 'TOUCHPAD_TOUCH_Y'
  55145. ],
  55146. pointingPoseMeshName: 'POINTING_POSE'
  55147. };
  55148. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  55149. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  55150. _this._loadedMeshInfo = null;
  55151. return _this;
  55152. }
  55153. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  55154. get: function () {
  55155. return this.onTriggerStateChangedObservable;
  55156. },
  55157. enumerable: true,
  55158. configurable: true
  55159. });
  55160. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  55161. get: function () {
  55162. return this.onSecondaryButtonStateChangedObservable;
  55163. },
  55164. enumerable: true,
  55165. configurable: true
  55166. });
  55167. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  55168. get: function () {
  55169. return this.onMainButtonStateChangedObservable;
  55170. },
  55171. enumerable: true,
  55172. configurable: true
  55173. });
  55174. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  55175. get: function () {
  55176. return this.onPadStateChangedObservable;
  55177. },
  55178. enumerable: true,
  55179. configurable: true
  55180. });
  55181. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  55182. get: function () {
  55183. return this.onTrackpadChangedObservable;
  55184. },
  55185. enumerable: true,
  55186. configurable: true
  55187. });
  55188. /**
  55189. * Called once per frame by the engine.
  55190. */
  55191. WindowsMotionController.prototype.update = function () {
  55192. _super.prototype.update.call(this);
  55193. // Only need to animate axes if there is a loaded mesh
  55194. if (this._loadedMeshInfo) {
  55195. if (this.browserGamepad.axes) {
  55196. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  55197. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  55198. }
  55199. }
  55200. }
  55201. };
  55202. /**
  55203. * Called once for each button that changed state since the last frame
  55204. * @param buttonIdx Which button index changed
  55205. * @param state New state of the button
  55206. * @param changes Which properties on the state changed since last frame
  55207. */
  55208. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  55209. var buttonName = this._mapping.buttons[buttonIdx];
  55210. if (!buttonName) {
  55211. return;
  55212. }
  55213. // Only emit events for buttons that we know how to map from index to name
  55214. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  55215. if (observable) {
  55216. observable.notifyObservers(state);
  55217. }
  55218. this.lerpButtonTransform(buttonName, state.value);
  55219. };
  55220. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  55221. // If there is no loaded mesh, there is nothing to transform.
  55222. if (!this._loadedMeshInfo) {
  55223. return;
  55224. }
  55225. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  55226. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  55227. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  55228. };
  55229. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  55230. if (!this._loadedMeshInfo) {
  55231. return;
  55232. }
  55233. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  55234. if (!meshInfo) {
  55235. return;
  55236. }
  55237. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  55238. var lerpValue = axisValue * 0.5 + 0.5;
  55239. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  55240. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  55241. };
  55242. /**
  55243. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  55244. * @param scene scene in which to add meshes
  55245. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  55246. */
  55247. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  55248. var _this = this;
  55249. if (forceDefault === void 0) { forceDefault = false; }
  55250. var path;
  55251. var filename;
  55252. // Checking if GLB loader is present
  55253. if (BABYLON.SceneLoader.GetPluginForExtension("glb")) {
  55254. // Determine the device specific folder based on the ID suffix
  55255. var device = 'default';
  55256. if (this.id && !forceDefault) {
  55257. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  55258. device = ((match && match[0]) || device);
  55259. }
  55260. // Hand
  55261. if (this.hand === 'left') {
  55262. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  55263. }
  55264. else {
  55265. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  55266. }
  55267. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  55268. }
  55269. else {
  55270. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  55271. path = BABYLON.GenericController.MODEL_BASE_URL;
  55272. filename = BABYLON.GenericController.MODEL_FILENAME;
  55273. }
  55274. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  55275. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  55276. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  55277. if (!_this._loadedMeshInfo) {
  55278. return;
  55279. }
  55280. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  55281. _this.attachToMesh(_this._defaultModel);
  55282. if (meshLoaded) {
  55283. meshLoaded(_this._defaultModel);
  55284. }
  55285. }, null, function (scene, message) {
  55286. BABYLON.Tools.Log(message);
  55287. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  55288. if (!forceDefault) {
  55289. _this.initControllerMesh(scene, meshLoaded, true);
  55290. }
  55291. });
  55292. };
  55293. /**
  55294. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  55295. * can be transformed by button presses and axes values, based on this._mapping.
  55296. *
  55297. * @param scene scene in which the meshes exist
  55298. * @param meshes list of meshes that make up the controller model to process
  55299. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  55300. */
  55301. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  55302. var loadedMeshInfo = null;
  55303. // Create a new mesh to contain the glTF hierarchy
  55304. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  55305. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  55306. var childMesh = null;
  55307. for (var i = 0; i < meshes.length; i++) {
  55308. var mesh = meshes[i];
  55309. if (!mesh.parent) {
  55310. // Exclude controller meshes from picking results
  55311. mesh.isPickable = false;
  55312. // Handle root node, attach to the new parentMesh
  55313. childMesh = mesh;
  55314. break;
  55315. }
  55316. }
  55317. if (childMesh) {
  55318. childMesh.setParent(parentMesh);
  55319. // Create our mesh info. Note that this method will always return non-null.
  55320. loadedMeshInfo = this.createMeshInfo(parentMesh);
  55321. }
  55322. else {
  55323. BABYLON.Tools.Warn('Could not find root node in model file.');
  55324. }
  55325. return loadedMeshInfo;
  55326. };
  55327. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  55328. var loadedMeshInfo = new LoadedMeshInfo();
  55329. var i;
  55330. loadedMeshInfo.rootNode = rootNode;
  55331. // Reset the caches
  55332. loadedMeshInfo.buttonMeshes = {};
  55333. loadedMeshInfo.axisMeshes = {};
  55334. // Button Meshes
  55335. for (i = 0; i < this._mapping.buttons.length; i++) {
  55336. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  55337. if (!buttonMeshName) {
  55338. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  55339. continue;
  55340. }
  55341. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  55342. if (!buttonMesh) {
  55343. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  55344. continue;
  55345. }
  55346. var buttonMeshInfo = {
  55347. index: i,
  55348. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  55349. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  55350. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  55351. };
  55352. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  55353. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  55354. }
  55355. else {
  55356. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  55357. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  55358. '(VALUE: ' + !!buttonMeshInfo.value +
  55359. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  55360. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  55361. ')');
  55362. }
  55363. }
  55364. // Axis Meshes
  55365. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  55366. var axisMeshName = this._mapping.axisMeshNames[i];
  55367. if (!axisMeshName) {
  55368. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  55369. continue;
  55370. }
  55371. var axisMesh = getChildByName(rootNode, axisMeshName);
  55372. if (!axisMesh) {
  55373. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  55374. continue;
  55375. }
  55376. var axisMeshInfo = {
  55377. index: i,
  55378. value: getImmediateChildByName(axisMesh, 'VALUE'),
  55379. min: getImmediateChildByName(axisMesh, 'MIN'),
  55380. max: getImmediateChildByName(axisMesh, 'MAX')
  55381. };
  55382. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  55383. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  55384. }
  55385. else {
  55386. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  55387. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  55388. '(VALUE: ' + !!axisMeshInfo.value +
  55389. ', MIN: ' + !!axisMeshInfo.min +
  55390. ', MAX:' + !!axisMeshInfo.max +
  55391. ')');
  55392. }
  55393. }
  55394. // Pointing Ray
  55395. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  55396. if (!loadedMeshInfo.pointingPoseNode) {
  55397. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  55398. }
  55399. return loadedMeshInfo;
  55400. // Look through all children recursively. This will return null if no mesh exists with the given name.
  55401. function getChildByName(node, name) {
  55402. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  55403. }
  55404. // Look through only immediate children. This will return null if no mesh exists with the given name.
  55405. function getImmediateChildByName(node, name) {
  55406. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  55407. }
  55408. };
  55409. WindowsMotionController.prototype.getForwardRay = function (length) {
  55410. if (length === void 0) { length = 100; }
  55411. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  55412. return _super.prototype.getForwardRay.call(this, length);
  55413. }
  55414. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  55415. var origin = m.getTranslation();
  55416. var forward = new BABYLON.Vector3(0, 0, -1);
  55417. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  55418. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  55419. return new BABYLON.Ray(origin, direction, length);
  55420. };
  55421. WindowsMotionController.prototype.dispose = function () {
  55422. _super.prototype.dispose.call(this);
  55423. this.onTrackpadChangedObservable.clear();
  55424. };
  55425. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  55426. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  55427. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  55428. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  55429. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  55430. return WindowsMotionController;
  55431. }(BABYLON.WebVRController));
  55432. BABYLON.WindowsMotionController = WindowsMotionController;
  55433. })(BABYLON || (BABYLON = {}));
  55434. //# sourceMappingURL=babylon.windowsMotionController.js.map
  55435. /// <reference path="babylon.targetCamera.ts" />
  55436. var BABYLON;
  55437. (function (BABYLON) {
  55438. var FollowCamera = /** @class */ (function (_super) {
  55439. __extends(FollowCamera, _super);
  55440. function FollowCamera(name, position, scene, lockedTarget) {
  55441. if (lockedTarget === void 0) { lockedTarget = null; }
  55442. var _this = _super.call(this, name, position, scene) || this;
  55443. _this.radius = 12;
  55444. _this.rotationOffset = 0;
  55445. _this.heightOffset = 4;
  55446. _this.cameraAcceleration = 0.05;
  55447. _this.maxCameraSpeed = 20;
  55448. _this.lockedTarget = lockedTarget;
  55449. return _this;
  55450. }
  55451. FollowCamera.prototype.getRadians = function (degrees) {
  55452. return degrees * Math.PI / 180;
  55453. };
  55454. FollowCamera.prototype.follow = function (cameraTarget) {
  55455. if (!cameraTarget)
  55456. return;
  55457. var yRotation;
  55458. if (cameraTarget.rotationQuaternion) {
  55459. var rotMatrix = new BABYLON.Matrix();
  55460. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  55461. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  55462. }
  55463. else {
  55464. yRotation = cameraTarget.rotation.y;
  55465. }
  55466. var radians = this.getRadians(this.rotationOffset) + yRotation;
  55467. var targetPosition = cameraTarget.getAbsolutePosition();
  55468. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  55469. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  55470. var dx = targetX - this.position.x;
  55471. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  55472. var dz = (targetZ) - this.position.z;
  55473. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  55474. var vy = dy * this.cameraAcceleration;
  55475. var vz = dz * this.cameraAcceleration * 2;
  55476. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  55477. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  55478. }
  55479. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  55480. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  55481. }
  55482. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  55483. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  55484. }
  55485. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  55486. this.setTarget(targetPosition);
  55487. };
  55488. FollowCamera.prototype._checkInputs = function () {
  55489. _super.prototype._checkInputs.call(this);
  55490. if (this.lockedTarget) {
  55491. this.follow(this.lockedTarget);
  55492. }
  55493. };
  55494. FollowCamera.prototype.getClassName = function () {
  55495. return "FollowCamera";
  55496. };
  55497. __decorate([
  55498. BABYLON.serialize()
  55499. ], FollowCamera.prototype, "radius", void 0);
  55500. __decorate([
  55501. BABYLON.serialize()
  55502. ], FollowCamera.prototype, "rotationOffset", void 0);
  55503. __decorate([
  55504. BABYLON.serialize()
  55505. ], FollowCamera.prototype, "heightOffset", void 0);
  55506. __decorate([
  55507. BABYLON.serialize()
  55508. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  55509. __decorate([
  55510. BABYLON.serialize()
  55511. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  55512. __decorate([
  55513. BABYLON.serializeAsMeshReference("lockedTargetId")
  55514. ], FollowCamera.prototype, "lockedTarget", void 0);
  55515. return FollowCamera;
  55516. }(BABYLON.TargetCamera));
  55517. BABYLON.FollowCamera = FollowCamera;
  55518. var ArcFollowCamera = /** @class */ (function (_super) {
  55519. __extends(ArcFollowCamera, _super);
  55520. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  55521. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  55522. _this.alpha = alpha;
  55523. _this.beta = beta;
  55524. _this.radius = radius;
  55525. _this.target = target;
  55526. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  55527. _this.follow();
  55528. return _this;
  55529. }
  55530. ArcFollowCamera.prototype.follow = function () {
  55531. if (!this.target) {
  55532. return;
  55533. }
  55534. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  55535. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  55536. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  55537. var targetPosition = this.target.getAbsolutePosition();
  55538. this.position = targetPosition.add(this._cartesianCoordinates);
  55539. this.setTarget(targetPosition);
  55540. };
  55541. ArcFollowCamera.prototype._checkInputs = function () {
  55542. _super.prototype._checkInputs.call(this);
  55543. this.follow();
  55544. };
  55545. ArcFollowCamera.prototype.getClassName = function () {
  55546. return "ArcFollowCamera";
  55547. };
  55548. return ArcFollowCamera;
  55549. }(BABYLON.TargetCamera));
  55550. BABYLON.ArcFollowCamera = ArcFollowCamera;
  55551. })(BABYLON || (BABYLON = {}));
  55552. //# sourceMappingURL=babylon.followCamera.js.map
  55553. /// <reference path="babylon.touchCamera.ts" />
  55554. var BABYLON;
  55555. (function (BABYLON) {
  55556. // We're mainly based on the logic defined into the FreeCamera code
  55557. var UniversalCamera = /** @class */ (function (_super) {
  55558. __extends(UniversalCamera, _super);
  55559. //-- end properties for backward compatibility for inputs
  55560. function UniversalCamera(name, position, scene) {
  55561. var _this = _super.call(this, name, position, scene) || this;
  55562. _this.inputs.addGamepad();
  55563. return _this;
  55564. }
  55565. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  55566. //-- Begin properties for backward compatibility for inputs
  55567. get: function () {
  55568. var gamepad = this.inputs.attached["gamepad"];
  55569. if (gamepad)
  55570. return gamepad.gamepadAngularSensibility;
  55571. return 0;
  55572. },
  55573. set: function (value) {
  55574. var gamepad = this.inputs.attached["gamepad"];
  55575. if (gamepad)
  55576. gamepad.gamepadAngularSensibility = value;
  55577. },
  55578. enumerable: true,
  55579. configurable: true
  55580. });
  55581. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  55582. get: function () {
  55583. var gamepad = this.inputs.attached["gamepad"];
  55584. if (gamepad)
  55585. return gamepad.gamepadMoveSensibility;
  55586. return 0;
  55587. },
  55588. set: function (value) {
  55589. var gamepad = this.inputs.attached["gamepad"];
  55590. if (gamepad)
  55591. gamepad.gamepadMoveSensibility = value;
  55592. },
  55593. enumerable: true,
  55594. configurable: true
  55595. });
  55596. UniversalCamera.prototype.getClassName = function () {
  55597. return "UniversalCamera";
  55598. };
  55599. return UniversalCamera;
  55600. }(BABYLON.TouchCamera));
  55601. BABYLON.UniversalCamera = UniversalCamera;
  55602. })(BABYLON || (BABYLON = {}));
  55603. //# sourceMappingURL=babylon.universalCamera.js.map
  55604. /// <reference path="babylon.universalCamera.ts" />
  55605. var BABYLON;
  55606. (function (BABYLON) {
  55607. // We're mainly based on the logic defined into the FreeCamera code
  55608. var GamepadCamera = /** @class */ (function (_super) {
  55609. __extends(GamepadCamera, _super);
  55610. //-- end properties for backward compatibility for inputs
  55611. function GamepadCamera(name, position, scene) {
  55612. return _super.call(this, name, position, scene) || this;
  55613. }
  55614. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  55615. //-- Begin properties for backward compatibility for inputs
  55616. get: function () {
  55617. var gamepad = this.inputs.attached["gamepad"];
  55618. if (gamepad)
  55619. return gamepad.gamepadAngularSensibility;
  55620. return 0;
  55621. },
  55622. set: function (value) {
  55623. var gamepad = this.inputs.attached["gamepad"];
  55624. if (gamepad)
  55625. gamepad.gamepadAngularSensibility = value;
  55626. },
  55627. enumerable: true,
  55628. configurable: true
  55629. });
  55630. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  55631. get: function () {
  55632. var gamepad = this.inputs.attached["gamepad"];
  55633. if (gamepad)
  55634. return gamepad.gamepadMoveSensibility;
  55635. return 0;
  55636. },
  55637. set: function (value) {
  55638. var gamepad = this.inputs.attached["gamepad"];
  55639. if (gamepad)
  55640. gamepad.gamepadMoveSensibility = value;
  55641. },
  55642. enumerable: true,
  55643. configurable: true
  55644. });
  55645. GamepadCamera.prototype.getClassName = function () {
  55646. return "GamepadCamera";
  55647. };
  55648. return GamepadCamera;
  55649. }(BABYLON.UniversalCamera));
  55650. BABYLON.GamepadCamera = GamepadCamera;
  55651. })(BABYLON || (BABYLON = {}));
  55652. //# sourceMappingURL=babylon.gamepadCamera.js.map
  55653. var BABYLON;
  55654. (function (BABYLON) {
  55655. var PostProcessRenderPipelineManager = /** @class */ (function () {
  55656. function PostProcessRenderPipelineManager() {
  55657. this._renderPipelines = {};
  55658. }
  55659. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  55660. this._renderPipelines[renderPipeline._name] = renderPipeline;
  55661. };
  55662. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  55663. var renderPipeline = this._renderPipelines[renderPipelineName];
  55664. if (!renderPipeline) {
  55665. return;
  55666. }
  55667. renderPipeline._attachCameras(cameras, unique);
  55668. };
  55669. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  55670. var renderPipeline = this._renderPipelines[renderPipelineName];
  55671. if (!renderPipeline) {
  55672. return;
  55673. }
  55674. renderPipeline._detachCameras(cameras);
  55675. };
  55676. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  55677. var renderPipeline = this._renderPipelines[renderPipelineName];
  55678. if (!renderPipeline) {
  55679. return;
  55680. }
  55681. renderPipeline._enableEffect(renderEffectName, cameras);
  55682. };
  55683. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  55684. var renderPipeline = this._renderPipelines[renderPipelineName];
  55685. if (!renderPipeline) {
  55686. return;
  55687. }
  55688. renderPipeline._disableEffect(renderEffectName, cameras);
  55689. };
  55690. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  55691. var renderPipeline = this._renderPipelines[renderPipelineName];
  55692. if (!renderPipeline) {
  55693. return;
  55694. }
  55695. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  55696. };
  55697. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  55698. var renderPipeline = this._renderPipelines[renderPipelineName];
  55699. if (!renderPipeline) {
  55700. return;
  55701. }
  55702. renderPipeline._disableDisplayOnlyPass(cameras);
  55703. };
  55704. PostProcessRenderPipelineManager.prototype.update = function () {
  55705. for (var renderPipelineName in this._renderPipelines) {
  55706. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  55707. var pipeline = this._renderPipelines[renderPipelineName];
  55708. if (!pipeline.isSupported) {
  55709. pipeline.dispose();
  55710. delete this._renderPipelines[renderPipelineName];
  55711. }
  55712. else {
  55713. pipeline._update();
  55714. }
  55715. }
  55716. }
  55717. };
  55718. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  55719. for (var renderPipelineName in this._renderPipelines) {
  55720. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  55721. var pipeline = this._renderPipelines[renderPipelineName];
  55722. pipeline._rebuild();
  55723. }
  55724. }
  55725. };
  55726. PostProcessRenderPipelineManager.prototype.dispose = function () {
  55727. for (var renderPipelineName in this._renderPipelines) {
  55728. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  55729. var pipeline = this._renderPipelines[renderPipelineName];
  55730. pipeline.dispose();
  55731. }
  55732. }
  55733. };
  55734. return PostProcessRenderPipelineManager;
  55735. }());
  55736. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  55737. })(BABYLON || (BABYLON = {}));
  55738. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  55739. var BABYLON;
  55740. (function (BABYLON) {
  55741. var PostProcessRenderPass = /** @class */ (function () {
  55742. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  55743. this._refCount = 0;
  55744. this._name = name;
  55745. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  55746. this.setRenderList(renderList);
  55747. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  55748. this._renderTexture.onAfterRenderObservable.add(afterRender);
  55749. this._scene = scene;
  55750. this._renderList = renderList;
  55751. }
  55752. // private
  55753. PostProcessRenderPass.prototype._incRefCount = function () {
  55754. if (this._refCount === 0) {
  55755. this._scene.customRenderTargets.push(this._renderTexture);
  55756. }
  55757. return ++this._refCount;
  55758. };
  55759. PostProcessRenderPass.prototype._decRefCount = function () {
  55760. this._refCount--;
  55761. if (this._refCount <= 0) {
  55762. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  55763. }
  55764. return this._refCount;
  55765. };
  55766. PostProcessRenderPass.prototype._update = function () {
  55767. this.setRenderList(this._renderList);
  55768. };
  55769. // public
  55770. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  55771. this._renderTexture.renderList = renderList;
  55772. };
  55773. PostProcessRenderPass.prototype.getRenderTexture = function () {
  55774. return this._renderTexture;
  55775. };
  55776. return PostProcessRenderPass;
  55777. }());
  55778. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  55779. })(BABYLON || (BABYLON = {}));
  55780. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  55781. var BABYLON;
  55782. (function (BABYLON) {
  55783. var PostProcessRenderEffect = /** @class */ (function () {
  55784. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  55785. this._engine = engine;
  55786. this._name = name;
  55787. this._singleInstance = singleInstance || true;
  55788. this._getPostProcess = getPostProcess;
  55789. this._cameras = [];
  55790. this._indicesForCamera = [];
  55791. this._postProcesses = {};
  55792. this._renderPasses = {};
  55793. this._renderEffectAsPasses = {};
  55794. }
  55795. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  55796. get: function () {
  55797. for (var index in this._postProcesses) {
  55798. if (!this._postProcesses[index].isSupported) {
  55799. return false;
  55800. }
  55801. }
  55802. return true;
  55803. },
  55804. enumerable: true,
  55805. configurable: true
  55806. });
  55807. PostProcessRenderEffect.prototype._update = function () {
  55808. for (var renderPassName in this._renderPasses) {
  55809. this._renderPasses[renderPassName]._update();
  55810. }
  55811. };
  55812. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  55813. this._renderPasses[renderPass._name] = renderPass;
  55814. this._linkParameters();
  55815. };
  55816. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  55817. delete this._renderPasses[renderPass._name];
  55818. this._linkParameters();
  55819. };
  55820. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  55821. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  55822. this._linkParameters();
  55823. };
  55824. PostProcessRenderEffect.prototype.getPass = function (passName) {
  55825. for (var renderPassName in this._renderPasses) {
  55826. if (renderPassName === passName) {
  55827. return this._renderPasses[passName];
  55828. }
  55829. }
  55830. return null;
  55831. };
  55832. PostProcessRenderEffect.prototype.emptyPasses = function () {
  55833. this._renderPasses = {};
  55834. this._linkParameters();
  55835. };
  55836. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  55837. var cameraKey;
  55838. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  55839. for (var i = 0; i < _cam.length; i++) {
  55840. var camera = _cam[i];
  55841. var cameraName = camera.name;
  55842. if (this._singleInstance) {
  55843. cameraKey = 0;
  55844. }
  55845. else {
  55846. cameraKey = cameraName;
  55847. }
  55848. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  55849. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  55850. if (!this._indicesForCamera[cameraName]) {
  55851. this._indicesForCamera[cameraName] = [];
  55852. }
  55853. this._indicesForCamera[cameraName].push(index);
  55854. if (this._cameras.indexOf(camera) === -1) {
  55855. this._cameras[cameraName] = camera;
  55856. }
  55857. for (var passName in this._renderPasses) {
  55858. this._renderPasses[passName]._incRefCount();
  55859. }
  55860. }
  55861. this._linkParameters();
  55862. };
  55863. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  55864. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  55865. for (var i = 0; i < _cam.length; i++) {
  55866. var camera = _cam[i];
  55867. var cameraName = camera.name;
  55868. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  55869. var index = this._cameras.indexOf(cameraName);
  55870. this._indicesForCamera.splice(index, 1);
  55871. this._cameras.splice(index, 1);
  55872. for (var passName in this._renderPasses) {
  55873. this._renderPasses[passName]._decRefCount();
  55874. }
  55875. }
  55876. };
  55877. PostProcessRenderEffect.prototype._enable = function (cameras) {
  55878. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  55879. for (var i = 0; i < _cam.length; i++) {
  55880. var camera = _cam[i];
  55881. var cameraName = camera.name;
  55882. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  55883. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  55884. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  55885. }
  55886. }
  55887. for (var passName in this._renderPasses) {
  55888. this._renderPasses[passName]._incRefCount();
  55889. }
  55890. }
  55891. };
  55892. PostProcessRenderEffect.prototype._disable = function (cameras) {
  55893. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  55894. for (var i = 0; i < _cam.length; i++) {
  55895. var camera = _cam[i];
  55896. var cameraName = camera.Name;
  55897. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  55898. for (var passName in this._renderPasses) {
  55899. this._renderPasses[passName]._decRefCount();
  55900. }
  55901. }
  55902. };
  55903. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  55904. if (this._singleInstance) {
  55905. return this._postProcesses[0];
  55906. }
  55907. else {
  55908. return this._postProcesses[camera.name];
  55909. }
  55910. };
  55911. PostProcessRenderEffect.prototype._linkParameters = function () {
  55912. var _this = this;
  55913. for (var index in this._postProcesses) {
  55914. if (this.applyParameters) {
  55915. this.applyParameters(this._postProcesses[index]);
  55916. }
  55917. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  55918. _this._linkTextures(effect);
  55919. });
  55920. }
  55921. };
  55922. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  55923. for (var renderPassName in this._renderPasses) {
  55924. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  55925. }
  55926. for (var renderEffectName in this._renderEffectAsPasses) {
  55927. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  55928. }
  55929. };
  55930. return PostProcessRenderEffect;
  55931. }());
  55932. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  55933. })(BABYLON || (BABYLON = {}));
  55934. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  55935. var BABYLON;
  55936. (function (BABYLON) {
  55937. var PostProcessRenderPipeline = /** @class */ (function () {
  55938. function PostProcessRenderPipeline(engine, name) {
  55939. this._engine = engine;
  55940. this._name = name;
  55941. this._renderEffects = new Array();
  55942. this._renderEffectsForIsolatedPass = new Array();
  55943. this._cameras = [];
  55944. }
  55945. PostProcessRenderPipeline.prototype.getClassName = function () {
  55946. return "PostProcessRenderPipeline";
  55947. };
  55948. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  55949. get: function () {
  55950. for (var renderEffectName in this._renderEffects) {
  55951. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  55952. if (!this._renderEffects[renderEffectName].isSupported) {
  55953. return false;
  55954. }
  55955. }
  55956. }
  55957. return true;
  55958. },
  55959. enumerable: true,
  55960. configurable: true
  55961. });
  55962. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  55963. this._renderEffects[renderEffect._name] = renderEffect;
  55964. };
  55965. // private
  55966. PostProcessRenderPipeline.prototype._rebuild = function () {
  55967. };
  55968. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  55969. var renderEffects = this._renderEffects[renderEffectName];
  55970. if (!renderEffects) {
  55971. return;
  55972. }
  55973. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  55974. };
  55975. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  55976. var renderEffects = this._renderEffects[renderEffectName];
  55977. if (!renderEffects) {
  55978. return;
  55979. }
  55980. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  55981. };
  55982. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  55983. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  55984. var indicesToDelete = [];
  55985. var i;
  55986. for (i = 0; i < _cam.length; i++) {
  55987. var camera = _cam[i];
  55988. var cameraName = camera.name;
  55989. if (this._cameras.indexOf(camera) === -1) {
  55990. this._cameras[cameraName] = camera;
  55991. }
  55992. else if (unique) {
  55993. indicesToDelete.push(i);
  55994. }
  55995. }
  55996. for (i = 0; i < indicesToDelete.length; i++) {
  55997. cameras.splice(indicesToDelete[i], 1);
  55998. }
  55999. for (var renderEffectName in this._renderEffects) {
  56000. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56001. this._renderEffects[renderEffectName]._attachCameras(_cam);
  56002. }
  56003. }
  56004. };
  56005. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  56006. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56007. for (var renderEffectName in this._renderEffects) {
  56008. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56009. this._renderEffects[renderEffectName]._detachCameras(_cam);
  56010. }
  56011. }
  56012. for (var i = 0; i < _cam.length; i++) {
  56013. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  56014. }
  56015. };
  56016. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  56017. var _this = this;
  56018. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56019. var pass = null;
  56020. var renderEffectName;
  56021. for (renderEffectName in this._renderEffects) {
  56022. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56023. pass = this._renderEffects[renderEffectName].getPass(passName);
  56024. if (pass != null) {
  56025. break;
  56026. }
  56027. }
  56028. }
  56029. if (pass === null) {
  56030. return;
  56031. }
  56032. for (renderEffectName in this._renderEffects) {
  56033. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56034. this._renderEffects[renderEffectName]._disable(_cam);
  56035. }
  56036. }
  56037. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  56038. for (var i = 0; i < _cam.length; i++) {
  56039. var camera = _cam[i];
  56040. var cameraName = camera.name;
  56041. 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, null, _this._engine, true); });
  56042. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  56043. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  56044. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  56045. }
  56046. };
  56047. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  56048. var _this = this;
  56049. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56050. for (var i = 0; i < _cam.length; i++) {
  56051. var camera = _cam[i];
  56052. var cameraName = camera.name;
  56053. 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, null, _this._engine, true); });
  56054. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  56055. }
  56056. for (var renderEffectName in this._renderEffects) {
  56057. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56058. this._renderEffects[renderEffectName]._enable(_cam);
  56059. }
  56060. }
  56061. };
  56062. PostProcessRenderPipeline.prototype._update = function () {
  56063. for (var renderEffectName in this._renderEffects) {
  56064. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56065. this._renderEffects[renderEffectName]._update();
  56066. }
  56067. }
  56068. for (var i = 0; i < this._cameras.length; i++) {
  56069. var cameraName = this._cameras[i].name;
  56070. if (this._renderEffectsForIsolatedPass[cameraName]) {
  56071. this._renderEffectsForIsolatedPass[cameraName]._update();
  56072. }
  56073. }
  56074. };
  56075. PostProcessRenderPipeline.prototype._reset = function () {
  56076. this._renderEffects = new Array();
  56077. this._renderEffectsForIsolatedPass = new Array();
  56078. };
  56079. PostProcessRenderPipeline.prototype.dispose = function () {
  56080. // Must be implemented by children
  56081. };
  56082. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  56083. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  56084. __decorate([
  56085. BABYLON.serialize()
  56086. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  56087. return PostProcessRenderPipeline;
  56088. }());
  56089. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  56090. })(BABYLON || (BABYLON = {}));
  56091. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  56092. var BABYLON;
  56093. (function (BABYLON) {
  56094. var DepthRenderer = /** @class */ (function () {
  56095. function DepthRenderer(scene, type) {
  56096. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  56097. var _this = this;
  56098. this._scene = scene;
  56099. var engine = scene.getEngine();
  56100. // Render target
  56101. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  56102. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56103. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56104. this._depthMap.refreshRate = 1;
  56105. this._depthMap.renderParticles = false;
  56106. this._depthMap.renderList = null;
  56107. // set default depth value to 1.0 (far away)
  56108. this._depthMap.onClearObservable.add(function (engine) {
  56109. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  56110. });
  56111. // Custom render function
  56112. var renderSubMesh = function (subMesh) {
  56113. var mesh = subMesh.getRenderingMesh();
  56114. var scene = _this._scene;
  56115. var engine = scene.getEngine();
  56116. // Culling
  56117. engine.setState(subMesh.getMaterial().backFaceCulling);
  56118. // Managing instances
  56119. var batch = mesh._getInstancesRenderList(subMesh._id);
  56120. if (batch.mustReturn) {
  56121. return;
  56122. }
  56123. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  56124. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  56125. engine.enableEffect(_this._effect);
  56126. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  56127. var material = subMesh.getMaterial();
  56128. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  56129. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  56130. // Alpha test
  56131. if (material && material.needAlphaTesting()) {
  56132. var alphaTexture = material.getAlphaTestTexture();
  56133. _this._effect.setTexture("diffuseSampler", alphaTexture);
  56134. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  56135. }
  56136. // Bones
  56137. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  56138. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  56139. }
  56140. // Draw
  56141. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  56142. }
  56143. };
  56144. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  56145. var index;
  56146. if (depthOnlySubMeshes.length) {
  56147. engine.setColorWrite(false);
  56148. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  56149. renderSubMesh(depthOnlySubMeshes.data[index]);
  56150. }
  56151. engine.setColorWrite(true);
  56152. }
  56153. for (index = 0; index < opaqueSubMeshes.length; index++) {
  56154. renderSubMesh(opaqueSubMeshes.data[index]);
  56155. }
  56156. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  56157. renderSubMesh(alphaTestSubMeshes.data[index]);
  56158. }
  56159. };
  56160. }
  56161. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  56162. var material = subMesh.getMaterial();
  56163. if (material.disableDepthWrite) {
  56164. return false;
  56165. }
  56166. var defines = [];
  56167. var attribs = [BABYLON.VertexBuffer.PositionKind];
  56168. var mesh = subMesh.getMesh();
  56169. // Alpha test
  56170. if (material && material.needAlphaTesting()) {
  56171. defines.push("#define ALPHATEST");
  56172. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  56173. attribs.push(BABYLON.VertexBuffer.UVKind);
  56174. defines.push("#define UV1");
  56175. }
  56176. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  56177. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  56178. defines.push("#define UV2");
  56179. }
  56180. }
  56181. // Bones
  56182. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  56183. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  56184. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  56185. if (mesh.numBoneInfluencers > 4) {
  56186. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  56187. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  56188. }
  56189. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  56190. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  56191. }
  56192. else {
  56193. defines.push("#define NUM_BONE_INFLUENCERS 0");
  56194. }
  56195. // Instances
  56196. if (useInstances) {
  56197. defines.push("#define INSTANCES");
  56198. attribs.push("world0");
  56199. attribs.push("world1");
  56200. attribs.push("world2");
  56201. attribs.push("world3");
  56202. }
  56203. // Get correct effect
  56204. var join = defines.join("\n");
  56205. if (this._cachedDefines !== join) {
  56206. this._cachedDefines = join;
  56207. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  56208. }
  56209. return this._effect.isReady();
  56210. };
  56211. DepthRenderer.prototype.getDepthMap = function () {
  56212. return this._depthMap;
  56213. };
  56214. // Methods
  56215. DepthRenderer.prototype.dispose = function () {
  56216. this._depthMap.dispose();
  56217. };
  56218. return DepthRenderer;
  56219. }());
  56220. BABYLON.DepthRenderer = DepthRenderer;
  56221. })(BABYLON || (BABYLON = {}));
  56222. //# sourceMappingURL=babylon.depthRenderer.js.map
  56223. var BABYLON;
  56224. (function (BABYLON) {
  56225. var SSAORenderingPipeline = /** @class */ (function (_super) {
  56226. __extends(SSAORenderingPipeline, _super);
  56227. /**
  56228. * @constructor
  56229. * @param {string} name - The rendering pipeline name
  56230. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  56231. * @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 }
  56232. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  56233. */
  56234. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  56235. var _this = _super.call(this, scene.getEngine(), name) || this;
  56236. // Members
  56237. /**
  56238. * The PassPostProcess id in the pipeline that contains the original scene color
  56239. * @type {string}
  56240. */
  56241. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  56242. /**
  56243. * The SSAO PostProcess id in the pipeline
  56244. * @type {string}
  56245. */
  56246. _this.SSAORenderEffect = "SSAORenderEffect";
  56247. /**
  56248. * The horizontal blur PostProcess id in the pipeline
  56249. * @type {string}
  56250. */
  56251. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  56252. /**
  56253. * The vertical blur PostProcess id in the pipeline
  56254. * @type {string}
  56255. */
  56256. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  56257. /**
  56258. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  56259. * @type {string}
  56260. */
  56261. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  56262. /**
  56263. * The output strength of the SSAO post-process. Default value is 1.0.
  56264. * @type {number}
  56265. */
  56266. _this.totalStrength = 1.0;
  56267. /**
  56268. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  56269. * @type {number}
  56270. */
  56271. _this.radius = 0.0001;
  56272. /**
  56273. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  56274. * Must not be equal to fallOff and superior to fallOff.
  56275. * Default value is 0.975
  56276. * @type {number}
  56277. */
  56278. _this.area = 0.0075;
  56279. /**
  56280. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  56281. * Must not be equal to area and inferior to area.
  56282. * Default value is 0.0
  56283. * @type {number}
  56284. */
  56285. _this.fallOff = 0.000001;
  56286. /**
  56287. * The base color of the SSAO post-process
  56288. * The final result is "base + ssao" between [0, 1]
  56289. * @type {number}
  56290. */
  56291. _this.base = 0.5;
  56292. _this._firstUpdate = true;
  56293. _this._scene = scene;
  56294. // Set up assets
  56295. _this._createRandomTexture();
  56296. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  56297. var ssaoRatio = ratio.ssaoRatio || ratio;
  56298. var combineRatio = ratio.combineRatio || ratio;
  56299. _this._ratio = {
  56300. ssaoRatio: ssaoRatio,
  56301. combineRatio: combineRatio
  56302. };
  56303. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  56304. _this._createSSAOPostProcess(ssaoRatio);
  56305. _this._createBlurPostProcess(ssaoRatio);
  56306. _this._createSSAOCombinePostProcess(combineRatio);
  56307. // Set up pipeline
  56308. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  56309. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  56310. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  56311. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  56312. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  56313. // Finish
  56314. scene.postProcessRenderPipelineManager.addPipeline(_this);
  56315. if (cameras)
  56316. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  56317. return _this;
  56318. }
  56319. // Public Methods
  56320. /**
  56321. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  56322. */
  56323. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  56324. if (disableDepthRender === void 0) { disableDepthRender = false; }
  56325. for (var i = 0; i < this._scene.cameras.length; i++) {
  56326. var camera = this._scene.cameras[i];
  56327. this._originalColorPostProcess.dispose(camera);
  56328. this._ssaoPostProcess.dispose(camera);
  56329. this._blurHPostProcess.dispose(camera);
  56330. this._blurVPostProcess.dispose(camera);
  56331. this._ssaoCombinePostProcess.dispose(camera);
  56332. }
  56333. this._randomTexture.dispose();
  56334. if (disableDepthRender)
  56335. this._scene.disableDepthRenderer();
  56336. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  56337. _super.prototype.dispose.call(this);
  56338. };
  56339. // Private Methods
  56340. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  56341. var _this = this;
  56342. /*
  56343. var samplerOffsets = [
  56344. -8.0, -6.0, -4.0, -2.0,
  56345. 0.0,
  56346. 2.0, 4.0, 6.0, 8.0
  56347. ];
  56348. */
  56349. var samplerOffsets = new Array();
  56350. for (var i = -8; i < 8; i++) {
  56351. samplerOffsets.push(i * 2);
  56352. }
  56353. 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");
  56354. this._blurHPostProcess.onApply = function (effect) {
  56355. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  56356. effect.setTexture("depthSampler", _this._depthTexture);
  56357. if (_this._firstUpdate) {
  56358. effect.setArray("samplerOffsets", samplerOffsets);
  56359. }
  56360. };
  56361. 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");
  56362. this._blurVPostProcess.onApply = function (effect) {
  56363. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  56364. effect.setTexture("depthSampler", _this._depthTexture);
  56365. if (_this._firstUpdate) {
  56366. effect.setArray("samplerOffsets", samplerOffsets);
  56367. _this._firstUpdate = false;
  56368. }
  56369. };
  56370. };
  56371. SSAORenderingPipeline.prototype._rebuild = function () {
  56372. this._firstUpdate = true;
  56373. _super.prototype._rebuild.call(this);
  56374. };
  56375. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  56376. var _this = this;
  56377. var numSamples = 16;
  56378. var sampleSphere = [
  56379. 0.5381, 0.1856, -0.4319,
  56380. 0.1379, 0.2486, 0.4430,
  56381. 0.3371, 0.5679, -0.0057,
  56382. -0.6999, -0.0451, -0.0019,
  56383. 0.0689, -0.1598, -0.8547,
  56384. 0.0560, 0.0069, -0.1843,
  56385. -0.0146, 0.1402, 0.0762,
  56386. 0.0100, -0.1924, -0.0344,
  56387. -0.3577, -0.5301, -0.4358,
  56388. -0.3169, 0.1063, 0.0158,
  56389. 0.0103, -0.5869, 0.0046,
  56390. -0.0897, -0.4940, 0.3287,
  56391. 0.7119, -0.0154, -0.0918,
  56392. -0.0533, 0.0596, -0.5411,
  56393. 0.0352, -0.0631, 0.5460,
  56394. -0.4776, 0.2847, -0.0271
  56395. ];
  56396. var samplesFactor = 1.0 / numSamples;
  56397. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  56398. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  56399. "area", "fallOff", "base", "range", "viewport"
  56400. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  56401. this._ssaoPostProcess.onApply = function (effect) {
  56402. if (_this._firstUpdate) {
  56403. effect.setArray3("sampleSphere", sampleSphere);
  56404. effect.setFloat("samplesFactor", samplesFactor);
  56405. effect.setFloat("randTextureTiles", 4.0);
  56406. }
  56407. effect.setFloat("totalStrength", _this.totalStrength);
  56408. effect.setFloat("radius", _this.radius);
  56409. effect.setFloat("area", _this.area);
  56410. effect.setFloat("fallOff", _this.fallOff);
  56411. effect.setFloat("base", _this.base);
  56412. effect.setTexture("textureSampler", _this._depthTexture);
  56413. effect.setTexture("randomSampler", _this._randomTexture);
  56414. };
  56415. };
  56416. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  56417. var _this = this;
  56418. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  56419. this._ssaoCombinePostProcess.onApply = function (effect) {
  56420. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  56421. };
  56422. };
  56423. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  56424. var size = 512;
  56425. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  56426. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56427. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56428. var context = this._randomTexture.getContext();
  56429. var rand = function (min, max) {
  56430. return Math.random() * (max - min) + min;
  56431. };
  56432. var randVector = BABYLON.Vector3.Zero();
  56433. for (var x = 0; x < size; x++) {
  56434. for (var y = 0; y < size; y++) {
  56435. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  56436. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  56437. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  56438. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  56439. context.fillRect(x, y, 1, 1);
  56440. }
  56441. }
  56442. this._randomTexture.update(false);
  56443. };
  56444. __decorate([
  56445. BABYLON.serialize()
  56446. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  56447. __decorate([
  56448. BABYLON.serialize()
  56449. ], SSAORenderingPipeline.prototype, "radius", void 0);
  56450. __decorate([
  56451. BABYLON.serialize()
  56452. ], SSAORenderingPipeline.prototype, "area", void 0);
  56453. __decorate([
  56454. BABYLON.serialize()
  56455. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  56456. __decorate([
  56457. BABYLON.serialize()
  56458. ], SSAORenderingPipeline.prototype, "base", void 0);
  56459. __decorate([
  56460. BABYLON.serialize()
  56461. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  56462. return SSAORenderingPipeline;
  56463. }(BABYLON.PostProcessRenderPipeline));
  56464. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  56465. })(BABYLON || (BABYLON = {}));
  56466. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  56467. var BABYLON;
  56468. (function (BABYLON) {
  56469. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  56470. __extends(SSAO2RenderingPipeline, _super);
  56471. /**
  56472. * @constructor
  56473. * @param {string} name - The rendering pipeline name
  56474. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  56475. * @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 }
  56476. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  56477. */
  56478. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  56479. var _this = _super.call(this, scene.getEngine(), name) || this;
  56480. // Members
  56481. /**
  56482. * The PassPostProcess id in the pipeline that contains the original scene color
  56483. * @type {string}
  56484. */
  56485. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  56486. /**
  56487. * The SSAO PostProcess id in the pipeline
  56488. * @type {string}
  56489. */
  56490. _this.SSAORenderEffect = "SSAORenderEffect";
  56491. /**
  56492. * The horizontal blur PostProcess id in the pipeline
  56493. * @type {string}
  56494. */
  56495. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  56496. /**
  56497. * The vertical blur PostProcess id in the pipeline
  56498. * @type {string}
  56499. */
  56500. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  56501. /**
  56502. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  56503. * @type {string}
  56504. */
  56505. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  56506. /**
  56507. * The output strength of the SSAO post-process. Default value is 1.0.
  56508. * @type {number}
  56509. */
  56510. _this.totalStrength = 1.0;
  56511. /**
  56512. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  56513. * @type {number}
  56514. */
  56515. _this.maxZ = 100.0;
  56516. /**
  56517. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  56518. * @type {number}
  56519. */
  56520. _this.minZAspect = 0.2;
  56521. /**
  56522. * Number of samples used for the SSAO calculations. Default value is 8
  56523. * @type {number}
  56524. */
  56525. _this._samples = 8;
  56526. /**
  56527. * Are we using bilateral blur ?
  56528. * @type {boolean}
  56529. */
  56530. _this._expensiveBlur = true;
  56531. /**
  56532. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  56533. * @type {number}
  56534. */
  56535. _this.radius = 2.0;
  56536. /**
  56537. * The base color of the SSAO post-process
  56538. * The final result is "base + ssao" between [0, 1]
  56539. * @type {number}
  56540. */
  56541. _this.base = 0.1;
  56542. _this._firstUpdate = true;
  56543. _this._scene = scene;
  56544. if (!_this.isSupported) {
  56545. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  56546. return _this;
  56547. }
  56548. var ssaoRatio = ratio.ssaoRatio || ratio;
  56549. var blurRatio = ratio.blurRatio || ratio;
  56550. _this._ratio = {
  56551. ssaoRatio: ssaoRatio,
  56552. blurRatio: blurRatio
  56553. };
  56554. // Set up assets
  56555. _this._createRandomTexture();
  56556. _this._depthTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[0];
  56557. _this._normalTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[1];
  56558. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  56559. _this._createSSAOPostProcess(1.0);
  56560. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  56561. _this._createSSAOCombinePostProcess(blurRatio);
  56562. // Set up pipeline
  56563. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  56564. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  56565. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  56566. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  56567. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  56568. // Finish
  56569. scene.postProcessRenderPipelineManager.addPipeline(_this);
  56570. if (cameras)
  56571. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  56572. return _this;
  56573. }
  56574. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  56575. get: function () {
  56576. return this._samples;
  56577. },
  56578. set: function (n) {
  56579. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  56580. this._samples = n;
  56581. this._sampleSphere = this._generateHemisphere();
  56582. this._firstUpdate = true;
  56583. },
  56584. enumerable: true,
  56585. configurable: true
  56586. });
  56587. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  56588. get: function () {
  56589. return this._expensiveBlur;
  56590. },
  56591. set: function (b) {
  56592. 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"]);
  56593. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  56594. this._expensiveBlur = b;
  56595. this._firstUpdate = true;
  56596. },
  56597. enumerable: true,
  56598. configurable: true
  56599. });
  56600. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  56601. /**
  56602. * Support test.
  56603. * @type {boolean}
  56604. */
  56605. get: function () {
  56606. var engine = BABYLON.Engine.LastCreatedEngine;
  56607. return engine.getCaps().drawBuffersExtension;
  56608. },
  56609. enumerable: true,
  56610. configurable: true
  56611. });
  56612. // Public Methods
  56613. /**
  56614. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  56615. */
  56616. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  56617. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  56618. for (var i = 0; i < this._scene.cameras.length; i++) {
  56619. var camera = this._scene.cameras[i];
  56620. this._originalColorPostProcess.dispose(camera);
  56621. this._ssaoPostProcess.dispose(camera);
  56622. this._blurHPostProcess.dispose(camera);
  56623. this._blurVPostProcess.dispose(camera);
  56624. this._ssaoCombinePostProcess.dispose(camera);
  56625. }
  56626. this._randomTexture.dispose();
  56627. if (disableGeometryBufferRenderer)
  56628. this._scene.disableGeometryBufferRenderer();
  56629. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  56630. _super.prototype.dispose.call(this);
  56631. };
  56632. // Private Methods
  56633. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  56634. var _this = this;
  56635. this._samplerOffsets = [];
  56636. var expensive = this.expensiveBlur;
  56637. for (var i = -8; i < 8; i++) {
  56638. this._samplerOffsets.push(i * 2 + 0.5);
  56639. }
  56640. 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");
  56641. this._blurHPostProcess.onApply = function (effect) {
  56642. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  56643. effect.setFloat("near", _this._scene.activeCamera.minZ);
  56644. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  56645. effect.setFloat("radius", _this.radius);
  56646. effect.setTexture("depthSampler", _this._depthTexture);
  56647. if (_this._firstUpdate) {
  56648. effect.setArray("samplerOffsets", _this._samplerOffsets);
  56649. }
  56650. };
  56651. 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");
  56652. this._blurVPostProcess.onApply = function (effect) {
  56653. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  56654. effect.setFloat("near", _this._scene.activeCamera.minZ);
  56655. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  56656. effect.setFloat("radius", _this.radius);
  56657. effect.setTexture("depthSampler", _this._depthTexture);
  56658. if (_this._firstUpdate) {
  56659. effect.setArray("samplerOffsets", _this._samplerOffsets);
  56660. _this._firstUpdate = false;
  56661. }
  56662. };
  56663. };
  56664. SSAO2RenderingPipeline.prototype._rebuild = function () {
  56665. this._firstUpdate = true;
  56666. _super.prototype._rebuild.call(this);
  56667. };
  56668. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  56669. var numSamples = this.samples;
  56670. var result = [];
  56671. var vector, scale;
  56672. var rand = function (min, max) {
  56673. return Math.random() * (max - min) + min;
  56674. };
  56675. var i = 0;
  56676. while (i < numSamples) {
  56677. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  56678. vector.normalize();
  56679. scale = i / numSamples;
  56680. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  56681. vector.scaleInPlace(scale);
  56682. result.push(vector.x, vector.y, vector.z);
  56683. i++;
  56684. }
  56685. return result;
  56686. };
  56687. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  56688. var _this = this;
  56689. var numSamples = this.samples;
  56690. this._sampleSphere = this._generateHemisphere();
  56691. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  56692. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  56693. "base", "range", "projection", "near", "far", "texelSize",
  56694. "xViewport", "yViewport", "maxZ", "minZAspect"
  56695. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  56696. this._ssaoPostProcess.onApply = function (effect) {
  56697. if (_this._firstUpdate) {
  56698. effect.setArray3("sampleSphere", _this._sampleSphere);
  56699. effect.setFloat("randTextureTiles", 4.0);
  56700. }
  56701. effect.setFloat("samplesFactor", 1 / _this.samples);
  56702. effect.setFloat("totalStrength", _this.totalStrength);
  56703. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  56704. effect.setFloat("radius", _this.radius);
  56705. effect.setFloat("maxZ", _this.maxZ);
  56706. effect.setFloat("minZAspect", _this.minZAspect);
  56707. effect.setFloat("base", _this.base);
  56708. effect.setFloat("near", _this._scene.activeCamera.minZ);
  56709. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  56710. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  56711. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  56712. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  56713. effect.setTexture("textureSampler", _this._depthTexture);
  56714. effect.setTexture("normalSampler", _this._normalTexture);
  56715. effect.setTexture("randomSampler", _this._randomTexture);
  56716. };
  56717. };
  56718. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  56719. var _this = this;
  56720. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  56721. this._ssaoCombinePostProcess.onApply = function (effect) {
  56722. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  56723. };
  56724. };
  56725. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  56726. var size = 512;
  56727. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  56728. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56729. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56730. var context = this._randomTexture.getContext();
  56731. var rand = function (min, max) {
  56732. return Math.random() * (max - min) + min;
  56733. };
  56734. var randVector = BABYLON.Vector3.Zero();
  56735. for (var x = 0; x < size; x++) {
  56736. for (var y = 0; y < size; y++) {
  56737. randVector.x = rand(0.0, 1.0);
  56738. randVector.y = rand(0.0, 1.0);
  56739. randVector.z = 0.0;
  56740. randVector.normalize();
  56741. randVector.scaleInPlace(255);
  56742. randVector.x = Math.floor(randVector.x);
  56743. randVector.y = Math.floor(randVector.y);
  56744. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  56745. context.fillRect(x, y, 1, 1);
  56746. }
  56747. }
  56748. this._randomTexture.update(false);
  56749. };
  56750. __decorate([
  56751. BABYLON.serialize()
  56752. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  56753. __decorate([
  56754. BABYLON.serialize()
  56755. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  56756. __decorate([
  56757. BABYLON.serialize()
  56758. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  56759. __decorate([
  56760. BABYLON.serialize("samples")
  56761. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  56762. __decorate([
  56763. BABYLON.serialize("expensiveBlur")
  56764. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  56765. __decorate([
  56766. BABYLON.serialize()
  56767. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  56768. __decorate([
  56769. BABYLON.serialize()
  56770. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  56771. __decorate([
  56772. BABYLON.serialize()
  56773. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  56774. return SSAO2RenderingPipeline;
  56775. }(BABYLON.PostProcessRenderPipeline));
  56776. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  56777. })(BABYLON || (BABYLON = {}));
  56778. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  56779. // BABYLON.JS Chromatic Aberration GLSL Shader
  56780. // Author: Olivier Guyot
  56781. // Separates very slightly R, G and B colors on the edges of the screen
  56782. // Inspired by Francois Tarlier & Martins Upitis
  56783. var BABYLON;
  56784. (function (BABYLON) {
  56785. var LensRenderingPipeline = /** @class */ (function (_super) {
  56786. __extends(LensRenderingPipeline, _super);
  56787. /**
  56788. * @constructor
  56789. *
  56790. * Effect parameters are as follow:
  56791. * {
  56792. * chromatic_aberration: number; // from 0 to x (1 for realism)
  56793. * edge_blur: number; // from 0 to x (1 for realism)
  56794. * distortion: number; // from 0 to x (1 for realism)
  56795. * grain_amount: number; // from 0 to 1
  56796. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  56797. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  56798. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  56799. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  56800. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  56801. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  56802. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  56803. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  56804. * }
  56805. * Note: if an effect parameter is unset, effect is disabled
  56806. *
  56807. * @param {string} name - The rendering pipeline name
  56808. * @param {object} parameters - An object containing all parameters (see above)
  56809. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  56810. * @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)
  56811. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  56812. */
  56813. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  56814. if (ratio === void 0) { ratio = 1.0; }
  56815. var _this = _super.call(this, scene.getEngine(), name) || this;
  56816. // Lens effects can be of the following:
  56817. // - chromatic aberration (slight shift of RGB colors)
  56818. // - blur on the edge of the lens
  56819. // - lens distortion
  56820. // - depth-of-field blur & highlights enhancing
  56821. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  56822. // - grain effect (noise or custom texture)
  56823. // Two additional texture samplers are needed:
  56824. // - depth map (for depth-of-field)
  56825. // - grain texture
  56826. /**
  56827. * The chromatic aberration PostProcess id in the pipeline
  56828. * @type {string}
  56829. */
  56830. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  56831. /**
  56832. * The highlights enhancing PostProcess id in the pipeline
  56833. * @type {string}
  56834. */
  56835. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  56836. /**
  56837. * The depth-of-field PostProcess id in the pipeline
  56838. * @type {string}
  56839. */
  56840. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  56841. _this._scene = scene;
  56842. // Fetch texture samplers
  56843. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  56844. if (parameters.grain_texture) {
  56845. _this._grainTexture = parameters.grain_texture;
  56846. }
  56847. else {
  56848. _this._createGrainTexture();
  56849. }
  56850. // save parameters
  56851. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  56852. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  56853. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  56854. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  56855. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  56856. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  56857. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  56858. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  56859. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  56860. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  56861. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  56862. // Create effects
  56863. _this._createChromaticAberrationPostProcess(ratio);
  56864. _this._createHighlightsPostProcess(ratio);
  56865. _this._createDepthOfFieldPostProcess(ratio / 4);
  56866. // Set up pipeline
  56867. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  56868. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  56869. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  56870. if (_this._highlightsGain === -1) {
  56871. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  56872. }
  56873. // Finish
  56874. scene.postProcessRenderPipelineManager.addPipeline(_this);
  56875. if (cameras) {
  56876. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  56877. }
  56878. return _this;
  56879. }
  56880. // public methods (self explanatory)
  56881. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  56882. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  56883. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  56884. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  56885. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  56886. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  56887. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  56888. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  56889. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  56890. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  56891. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  56892. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  56893. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  56894. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  56895. };
  56896. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  56897. this._highlightsPostProcess.updateEffect();
  56898. };
  56899. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  56900. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  56901. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  56902. this._highlightsGain = amount;
  56903. };
  56904. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  56905. if (this._highlightsGain === -1) {
  56906. this._highlightsGain = 1.0;
  56907. }
  56908. this._highlightsThreshold = amount;
  56909. };
  56910. LensRenderingPipeline.prototype.disableHighlights = function () {
  56911. this._highlightsGain = -1;
  56912. };
  56913. /**
  56914. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  56915. */
  56916. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  56917. if (disableDepthRender === void 0) { disableDepthRender = false; }
  56918. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  56919. this._chromaticAberrationPostProcess = undefined;
  56920. this._highlightsPostProcess = undefined;
  56921. this._depthOfFieldPostProcess = undefined;
  56922. this._grainTexture.dispose();
  56923. if (disableDepthRender)
  56924. this._scene.disableDepthRenderer();
  56925. };
  56926. // colors shifting and distortion
  56927. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  56928. var _this = this;
  56929. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  56930. [], // samplers
  56931. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  56932. this._chromaticAberrationPostProcess.onApply = function (effect) {
  56933. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  56934. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  56935. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  56936. };
  56937. };
  56938. // highlights enhancing
  56939. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  56940. var _this = this;
  56941. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  56942. [], // samplers
  56943. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  56944. this._highlightsPostProcess.onApply = function (effect) {
  56945. effect.setFloat('gain', _this._highlightsGain);
  56946. effect.setFloat('threshold', _this._highlightsThreshold);
  56947. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  56948. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  56949. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  56950. };
  56951. };
  56952. // colors shifting and distortion
  56953. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  56954. var _this = this;
  56955. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  56956. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  56957. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  56958. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  56959. this._depthOfFieldPostProcess.onApply = function (effect) {
  56960. effect.setTexture("depthSampler", _this._depthTexture);
  56961. effect.setTexture("grainSampler", _this._grainTexture);
  56962. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  56963. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  56964. effect.setFloat('grain_amount', _this._grainAmount);
  56965. effect.setBool('blur_noise', _this._blurNoise);
  56966. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  56967. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  56968. effect.setFloat('distortion', _this._distortion);
  56969. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  56970. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  56971. effect.setFloat('aperture', _this._dofAperture);
  56972. effect.setFloat('darken', _this._dofDarken);
  56973. effect.setFloat('edge_blur', _this._edgeBlur);
  56974. effect.setBool('highlights', (_this._highlightsGain !== -1));
  56975. effect.setFloat('near', _this._scene.activeCamera.minZ);
  56976. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  56977. };
  56978. };
  56979. // creates a black and white random noise texture, 512x512
  56980. LensRenderingPipeline.prototype._createGrainTexture = function () {
  56981. var size = 512;
  56982. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56983. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56984. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56985. var context = this._grainTexture.getContext();
  56986. var rand = function (min, max) {
  56987. return Math.random() * (max - min) + min;
  56988. };
  56989. var value;
  56990. for (var x = 0; x < size; x++) {
  56991. for (var y = 0; y < size; y++) {
  56992. value = Math.floor(rand(0.42, 0.58) * 255);
  56993. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  56994. context.fillRect(x, y, 1, 1);
  56995. }
  56996. }
  56997. this._grainTexture.update(false);
  56998. };
  56999. return LensRenderingPipeline;
  57000. }(BABYLON.PostProcessRenderPipeline));
  57001. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  57002. })(BABYLON || (BABYLON = {}));
  57003. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  57004. var BABYLON;
  57005. (function (BABYLON) {
  57006. var StandardRenderingPipeline = /** @class */ (function (_super) {
  57007. __extends(StandardRenderingPipeline, _super);
  57008. /**
  57009. * @constructor
  57010. * @param {string} name - The rendering pipeline name
  57011. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57012. * @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)
  57013. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  57014. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57015. */
  57016. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  57017. if (originalPostProcess === void 0) { originalPostProcess = null; }
  57018. var _this = _super.call(this, scene.getEngine(), name) || this;
  57019. _this.downSampleX4PostProcess = null;
  57020. _this.brightPassPostProcess = null;
  57021. _this.blurHPostProcesses = [];
  57022. _this.blurVPostProcesses = [];
  57023. _this.textureAdderPostProcess = null;
  57024. _this.volumetricLightPostProcess = null;
  57025. _this.volumetricLightSmoothXPostProcess = null;
  57026. _this.volumetricLightSmoothYPostProcess = null;
  57027. _this.volumetricLightMergePostProces = null;
  57028. _this.volumetricLightFinalPostProcess = null;
  57029. _this.luminancePostProcess = null;
  57030. _this.luminanceDownSamplePostProcesses = [];
  57031. _this.hdrPostProcess = null;
  57032. _this.textureAdderFinalPostProcess = null;
  57033. _this.lensFlareFinalPostProcess = null;
  57034. _this.hdrFinalPostProcess = null;
  57035. _this.lensFlarePostProcess = null;
  57036. _this.lensFlareComposePostProcess = null;
  57037. _this.motionBlurPostProcess = null;
  57038. _this.depthOfFieldPostProcess = null;
  57039. // Values
  57040. _this.brightThreshold = 1.0;
  57041. _this.blurWidth = 512.0;
  57042. _this.horizontalBlur = false;
  57043. _this.exposure = 1.0;
  57044. _this.lensTexture = null;
  57045. _this.volumetricLightCoefficient = 0.2;
  57046. _this.volumetricLightPower = 4.0;
  57047. _this.volumetricLightBlurScale = 64.0;
  57048. _this.sourceLight = null;
  57049. _this.hdrMinimumLuminance = 1.0;
  57050. _this.hdrDecreaseRate = 0.5;
  57051. _this.hdrIncreaseRate = 0.5;
  57052. _this.lensColorTexture = null;
  57053. _this.lensFlareStrength = 20.0;
  57054. _this.lensFlareGhostDispersal = 1.4;
  57055. _this.lensFlareHaloWidth = 0.7;
  57056. _this.lensFlareDistortionStrength = 16.0;
  57057. _this.lensStarTexture = null;
  57058. _this.lensFlareDirtTexture = null;
  57059. _this.depthOfFieldDistance = 10.0;
  57060. _this.depthOfFieldBlurWidth = 64.0;
  57061. _this.motionStrength = 1.0;
  57062. // IAnimatable
  57063. _this.animations = [];
  57064. _this._currentDepthOfFieldSource = null;
  57065. _this._hdrCurrentLuminance = 1.0;
  57066. // Getters and setters
  57067. _this._bloomEnabled = true;
  57068. _this._depthOfFieldEnabled = false;
  57069. _this._vlsEnabled = false;
  57070. _this._lensFlareEnabled = false;
  57071. _this._hdrEnabled = false;
  57072. _this._motionBlurEnabled = false;
  57073. _this._motionBlurSamples = 64.0;
  57074. _this._volumetricLightStepsCount = 50.0;
  57075. _this._cameras = cameras || [];
  57076. // Initialize
  57077. _this._scene = scene;
  57078. _this._basePostProcess = originalPostProcess;
  57079. _this._ratio = ratio;
  57080. // Misc
  57081. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  57082. // Finish
  57083. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57084. _this._buildPipeline();
  57085. return _this;
  57086. }
  57087. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  57088. get: function () {
  57089. return this._bloomEnabled;
  57090. },
  57091. set: function (enabled) {
  57092. if (this._bloomEnabled === enabled) {
  57093. return;
  57094. }
  57095. this._bloomEnabled = enabled;
  57096. this._buildPipeline();
  57097. },
  57098. enumerable: true,
  57099. configurable: true
  57100. });
  57101. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  57102. get: function () {
  57103. return this._depthOfFieldEnabled;
  57104. },
  57105. set: function (enabled) {
  57106. if (this._depthOfFieldEnabled === enabled) {
  57107. return;
  57108. }
  57109. this._depthOfFieldEnabled = enabled;
  57110. this._buildPipeline();
  57111. },
  57112. enumerable: true,
  57113. configurable: true
  57114. });
  57115. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  57116. get: function () {
  57117. return this._lensFlareEnabled;
  57118. },
  57119. set: function (enabled) {
  57120. if (this._lensFlareEnabled === enabled) {
  57121. return;
  57122. }
  57123. this._lensFlareEnabled = enabled;
  57124. this._buildPipeline();
  57125. },
  57126. enumerable: true,
  57127. configurable: true
  57128. });
  57129. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  57130. get: function () {
  57131. return this._hdrEnabled;
  57132. },
  57133. set: function (enabled) {
  57134. if (this._hdrEnabled === enabled) {
  57135. return;
  57136. }
  57137. this._hdrEnabled = enabled;
  57138. this._buildPipeline();
  57139. },
  57140. enumerable: true,
  57141. configurable: true
  57142. });
  57143. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  57144. get: function () {
  57145. return this._vlsEnabled;
  57146. },
  57147. set: function (enabled) {
  57148. if (this._vlsEnabled === enabled) {
  57149. return;
  57150. }
  57151. if (enabled) {
  57152. var geometry = this._scene.enableGeometryBufferRenderer();
  57153. if (!geometry) {
  57154. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  57155. return;
  57156. }
  57157. }
  57158. this._vlsEnabled = enabled;
  57159. this._buildPipeline();
  57160. },
  57161. enumerable: true,
  57162. configurable: true
  57163. });
  57164. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  57165. get: function () {
  57166. return this._motionBlurEnabled;
  57167. },
  57168. set: function (enabled) {
  57169. if (this._motionBlurEnabled === enabled) {
  57170. return;
  57171. }
  57172. this._motionBlurEnabled = enabled;
  57173. this._buildPipeline();
  57174. },
  57175. enumerable: true,
  57176. configurable: true
  57177. });
  57178. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  57179. get: function () {
  57180. return this._volumetricLightStepsCount;
  57181. },
  57182. set: function (count) {
  57183. if (this.volumetricLightPostProcess) {
  57184. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  57185. }
  57186. this._volumetricLightStepsCount = count;
  57187. },
  57188. enumerable: true,
  57189. configurable: true
  57190. });
  57191. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  57192. get: function () {
  57193. return this._motionBlurSamples;
  57194. },
  57195. set: function (samples) {
  57196. if (this.motionBlurPostProcess) {
  57197. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  57198. }
  57199. this._motionBlurSamples = samples;
  57200. },
  57201. enumerable: true,
  57202. configurable: true
  57203. });
  57204. StandardRenderingPipeline.prototype._buildPipeline = function () {
  57205. var _this = this;
  57206. var ratio = this._ratio;
  57207. var scene = this._scene;
  57208. this._disposePostProcesses();
  57209. this._reset();
  57210. // Create pass post-process
  57211. if (!this._basePostProcess) {
  57212. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  57213. this.originalPostProcess.onApply = function (effect) {
  57214. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  57215. };
  57216. }
  57217. else {
  57218. this.originalPostProcess = this._basePostProcess;
  57219. }
  57220. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  57221. this._currentDepthOfFieldSource = this.originalPostProcess;
  57222. if (this._vlsEnabled) {
  57223. // Create volumetric light
  57224. this._createVolumetricLightPostProcess(scene, ratio);
  57225. // Create volumetric light final post-process
  57226. 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);
  57227. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  57228. }
  57229. if (this._bloomEnabled) {
  57230. // Create down sample X4 post-process
  57231. this._createDownSampleX4PostProcess(scene, ratio / 2);
  57232. // Create bright pass post-process
  57233. this._createBrightPassPostProcess(scene, ratio / 2);
  57234. // Create gaussian blur post-processes (down sampling blurs)
  57235. this._createBlurPostProcesses(scene, ratio / 4, 1);
  57236. // Create texture adder post-process
  57237. this._createTextureAdderPostProcess(scene, ratio);
  57238. // Create depth-of-field source post-process
  57239. 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);
  57240. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  57241. }
  57242. if (this._lensFlareEnabled) {
  57243. // Create lens flare post-process
  57244. this._createLensFlarePostProcess(scene, ratio);
  57245. // Create depth-of-field source post-process post lens-flare and disable it now
  57246. 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);
  57247. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  57248. }
  57249. if (this._hdrEnabled) {
  57250. // Create luminance
  57251. this._createLuminancePostProcesses(scene, this._floatTextureType);
  57252. // Create HDR
  57253. this._createHdrPostProcess(scene, ratio);
  57254. // Create depth-of-field source post-process post hdr and disable it now
  57255. 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);
  57256. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  57257. }
  57258. if (this._depthOfFieldEnabled) {
  57259. // Create gaussian blur used by depth-of-field
  57260. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  57261. // Create depth-of-field post-process
  57262. this._createDepthOfFieldPostProcess(scene, ratio);
  57263. }
  57264. if (this._motionBlurEnabled) {
  57265. // Create motion blur post-process
  57266. this._createMotionBlurPostProcess(scene, ratio);
  57267. }
  57268. if (this._cameras !== null) {
  57269. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  57270. }
  57271. };
  57272. // Down Sample X4 Post-Processs
  57273. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  57274. var _this = this;
  57275. var downSampleX4Offsets = new Array(32);
  57276. 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);
  57277. this.downSampleX4PostProcess.onApply = function (effect) {
  57278. var id = 0;
  57279. for (var i = -2; i < 2; i++) {
  57280. for (var j = -2; j < 2; j++) {
  57281. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  57282. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  57283. id += 2;
  57284. }
  57285. }
  57286. effect.setArray2("dsOffsets", downSampleX4Offsets);
  57287. };
  57288. // Add to pipeline
  57289. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  57290. };
  57291. // Brightpass Post-Process
  57292. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  57293. var _this = this;
  57294. var brightOffsets = new Array(8);
  57295. 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);
  57296. this.brightPassPostProcess.onApply = function (effect) {
  57297. var sU = (1.0 / _this.brightPassPostProcess.width);
  57298. var sV = (1.0 / _this.brightPassPostProcess.height);
  57299. brightOffsets[0] = -0.5 * sU;
  57300. brightOffsets[1] = 0.5 * sV;
  57301. brightOffsets[2] = 0.5 * sU;
  57302. brightOffsets[3] = 0.5 * sV;
  57303. brightOffsets[4] = -0.5 * sU;
  57304. brightOffsets[5] = -0.5 * sV;
  57305. brightOffsets[6] = 0.5 * sU;
  57306. brightOffsets[7] = -0.5 * sV;
  57307. effect.setArray2("dsOffsets", brightOffsets);
  57308. effect.setFloat("brightThreshold", _this.brightThreshold);
  57309. };
  57310. // Add to pipeline
  57311. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  57312. };
  57313. // Create blur H&V post-processes
  57314. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  57315. var _this = this;
  57316. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  57317. var engine = scene.getEngine();
  57318. 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);
  57319. 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);
  57320. blurX.onActivateObservable.add(function () {
  57321. var dw = blurX.width / engine.getRenderingCanvas().width;
  57322. blurX.kernel = _this[blurWidthKey] * dw;
  57323. });
  57324. blurY.onActivateObservable.add(function () {
  57325. var dw = blurY.height / engine.getRenderingCanvas().height;
  57326. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  57327. });
  57328. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  57329. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  57330. this.blurHPostProcesses.push(blurX);
  57331. this.blurVPostProcesses.push(blurY);
  57332. };
  57333. // Create texture adder post-process
  57334. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  57335. var _this = this;
  57336. 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);
  57337. this.textureAdderPostProcess.onApply = function (effect) {
  57338. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  57339. effect.setTexture("lensSampler", _this.lensTexture);
  57340. effect.setFloat("exposure", _this.exposure);
  57341. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  57342. };
  57343. // Add to pipeline
  57344. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  57345. };
  57346. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  57347. var _this = this;
  57348. var geometryRenderer = scene.enableGeometryBufferRenderer();
  57349. geometryRenderer.enablePosition = true;
  57350. var geometry = geometryRenderer.getGBuffer();
  57351. // Base post-process
  57352. 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));
  57353. var depthValues = BABYLON.Vector2.Zero();
  57354. this.volumetricLightPostProcess.onApply = function (effect) {
  57355. if (_this.sourceLight && _this.sourceLight.getShadowGenerator()) {
  57356. var generator = _this.sourceLight.getShadowGenerator();
  57357. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  57358. effect.setTexture("positionSampler", geometry.textures[2]);
  57359. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  57360. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  57361. effect.setVector3("cameraPosition", scene.activeCamera.globalPosition);
  57362. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  57363. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  57364. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  57365. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  57366. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  57367. effect.setVector2("depthValues", depthValues);
  57368. }
  57369. };
  57370. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  57371. // Smooth
  57372. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  57373. // Merge
  57374. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  57375. this.volumetricLightMergePostProces.onApply = function (effect) {
  57376. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  57377. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  57378. };
  57379. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  57380. };
  57381. // Create luminance
  57382. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  57383. var _this = this;
  57384. // Create luminance
  57385. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  57386. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  57387. var offsets = [];
  57388. this.luminancePostProcess.onApply = function (effect) {
  57389. var sU = (1.0 / _this.luminancePostProcess.width);
  57390. var sV = (1.0 / _this.luminancePostProcess.height);
  57391. offsets[0] = -0.5 * sU;
  57392. offsets[1] = 0.5 * sV;
  57393. offsets[2] = 0.5 * sU;
  57394. offsets[3] = 0.5 * sV;
  57395. offsets[4] = -0.5 * sU;
  57396. offsets[5] = -0.5 * sV;
  57397. offsets[6] = 0.5 * sU;
  57398. offsets[7] = -0.5 * sV;
  57399. effect.setArray2("lumOffsets", offsets);
  57400. };
  57401. // Add to pipeline
  57402. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  57403. // Create down sample luminance
  57404. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  57405. var size = Math.pow(3, i);
  57406. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  57407. if (i === 0) {
  57408. defines += "#define FINAL_DOWN_SAMPLER";
  57409. }
  57410. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  57411. this.luminanceDownSamplePostProcesses.push(postProcess);
  57412. }
  57413. // Create callbacks and add effects
  57414. var lastLuminance = this.luminancePostProcess;
  57415. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  57416. var downSampleOffsets = new Array(18);
  57417. pp.onApply = function (effect) {
  57418. var id = 0;
  57419. for (var x = -1; x < 2; x++) {
  57420. for (var y = -1; y < 2; y++) {
  57421. downSampleOffsets[id] = x / lastLuminance.width;
  57422. downSampleOffsets[id + 1] = y / lastLuminance.height;
  57423. id += 2;
  57424. }
  57425. }
  57426. effect.setArray2("dsOffsets", downSampleOffsets);
  57427. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  57428. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  57429. lastLuminance = _this.luminancePostProcess;
  57430. }
  57431. else {
  57432. lastLuminance = pp;
  57433. }
  57434. };
  57435. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  57436. pp.onAfterRender = function (effect) {
  57437. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  57438. 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);
  57439. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  57440. };
  57441. }
  57442. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  57443. });
  57444. };
  57445. // Create HDR post-process
  57446. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  57447. var _this = this;
  57448. 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);
  57449. var outputLiminance = 1;
  57450. var time = 0;
  57451. var lastTime = 0;
  57452. this.hdrPostProcess.onApply = function (effect) {
  57453. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  57454. time += scene.getEngine().getDeltaTime();
  57455. if (outputLiminance < 0) {
  57456. outputLiminance = _this._hdrCurrentLuminance;
  57457. }
  57458. else {
  57459. var dt = (lastTime - time) / 1000.0;
  57460. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  57461. outputLiminance += _this.hdrDecreaseRate * dt;
  57462. }
  57463. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  57464. outputLiminance -= _this.hdrIncreaseRate * dt;
  57465. }
  57466. else {
  57467. outputLiminance = _this._hdrCurrentLuminance;
  57468. }
  57469. }
  57470. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  57471. effect.setFloat("averageLuminance", outputLiminance);
  57472. lastTime = time;
  57473. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  57474. };
  57475. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  57476. };
  57477. // Create lens flare post-process
  57478. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  57479. var _this = this;
  57480. 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);
  57481. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  57482. this._createBlurPostProcesses(scene, ratio / 4, 2);
  57483. 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);
  57484. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  57485. var resolution = new BABYLON.Vector2(0, 0);
  57486. // Lens flare
  57487. this.lensFlarePostProcess.onApply = function (effect) {
  57488. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  57489. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  57490. effect.setFloat("strength", _this.lensFlareStrength);
  57491. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  57492. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  57493. // Shift
  57494. resolution.x = _this.lensFlarePostProcess.width;
  57495. resolution.y = _this.lensFlarePostProcess.height;
  57496. effect.setVector2("resolution", resolution);
  57497. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  57498. };
  57499. // Compose
  57500. 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);
  57501. 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);
  57502. this.lensFlareComposePostProcess.onApply = function (effect) {
  57503. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  57504. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  57505. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  57506. // Lens start rotation matrix
  57507. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  57508. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  57509. 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));
  57510. camRot *= 4.0;
  57511. 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);
  57512. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  57513. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  57514. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  57515. };
  57516. };
  57517. // Create depth-of-field post-process
  57518. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  57519. var _this = this;
  57520. 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);
  57521. this.depthOfFieldPostProcess.onApply = function (effect) {
  57522. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  57523. effect.setTexture("depthSampler", _this._getDepthTexture());
  57524. effect.setFloat("distance", _this.depthOfFieldDistance);
  57525. };
  57526. // Add to pipeline
  57527. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  57528. };
  57529. // Create motion blur post-process
  57530. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  57531. var _this = this;
  57532. 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);
  57533. var motionScale = 0;
  57534. var prevViewProjection = BABYLON.Matrix.Identity();
  57535. var invViewProjection = BABYLON.Matrix.Identity();
  57536. var viewProjection = BABYLON.Matrix.Identity();
  57537. var screenSize = BABYLON.Vector2.Zero();
  57538. this.motionBlurPostProcess.onApply = function (effect) {
  57539. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  57540. viewProjection.invertToRef(invViewProjection);
  57541. effect.setMatrix("inverseViewProjection", invViewProjection);
  57542. effect.setMatrix("prevViewProjection", prevViewProjection);
  57543. prevViewProjection = viewProjection;
  57544. screenSize.x = _this.motionBlurPostProcess.width;
  57545. screenSize.y = _this.motionBlurPostProcess.height;
  57546. effect.setVector2("screenSize", screenSize);
  57547. motionScale = scene.getEngine().getFps() / 60.0;
  57548. effect.setFloat("motionScale", motionScale);
  57549. effect.setFloat("motionStrength", _this.motionStrength);
  57550. effect.setTexture("depthSampler", _this._getDepthTexture());
  57551. };
  57552. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  57553. };
  57554. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  57555. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  57556. return this._scene.enableGeometryBufferRenderer().getGBuffer().textures[0];
  57557. }
  57558. return this._scene.enableDepthRenderer().getDepthMap();
  57559. };
  57560. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  57561. for (var i = 0; i < this._cameras.length; i++) {
  57562. var camera = this._cameras[i];
  57563. if (this.originalPostProcess) {
  57564. this.originalPostProcess.dispose(camera);
  57565. }
  57566. if (this.downSampleX4PostProcess) {
  57567. this.downSampleX4PostProcess.dispose(camera);
  57568. }
  57569. if (this.brightPassPostProcess) {
  57570. this.brightPassPostProcess.dispose(camera);
  57571. }
  57572. if (this.textureAdderPostProcess) {
  57573. this.textureAdderPostProcess.dispose(camera);
  57574. }
  57575. if (this.textureAdderFinalPostProcess) {
  57576. this.textureAdderFinalPostProcess.dispose(camera);
  57577. }
  57578. if (this.volumetricLightPostProcess) {
  57579. this.volumetricLightPostProcess.dispose(camera);
  57580. }
  57581. if (this.volumetricLightSmoothXPostProcess) {
  57582. this.volumetricLightSmoothXPostProcess.dispose(camera);
  57583. }
  57584. if (this.volumetricLightSmoothYPostProcess) {
  57585. this.volumetricLightSmoothYPostProcess.dispose(camera);
  57586. }
  57587. if (this.volumetricLightMergePostProces) {
  57588. this.volumetricLightMergePostProces.dispose(camera);
  57589. }
  57590. if (this.volumetricLightFinalPostProcess) {
  57591. this.volumetricLightFinalPostProcess.dispose(camera);
  57592. }
  57593. if (this.lensFlarePostProcess) {
  57594. this.lensFlarePostProcess.dispose(camera);
  57595. }
  57596. if (this.lensFlareComposePostProcess) {
  57597. this.lensFlareComposePostProcess.dispose(camera);
  57598. }
  57599. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  57600. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  57601. }
  57602. if (this.luminancePostProcess) {
  57603. this.luminancePostProcess.dispose(camera);
  57604. }
  57605. if (this.hdrPostProcess) {
  57606. this.hdrPostProcess.dispose(camera);
  57607. }
  57608. if (this.hdrFinalPostProcess) {
  57609. this.hdrFinalPostProcess.dispose(camera);
  57610. }
  57611. if (this.depthOfFieldPostProcess) {
  57612. this.depthOfFieldPostProcess.dispose(camera);
  57613. }
  57614. if (this.motionBlurPostProcess) {
  57615. this.motionBlurPostProcess.dispose(camera);
  57616. }
  57617. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  57618. this.blurHPostProcesses[j].dispose(camera);
  57619. }
  57620. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  57621. this.blurVPostProcesses[j].dispose(camera);
  57622. }
  57623. }
  57624. this.originalPostProcess = null;
  57625. this.downSampleX4PostProcess = null;
  57626. this.brightPassPostProcess = null;
  57627. this.textureAdderPostProcess = null;
  57628. this.textureAdderFinalPostProcess = null;
  57629. this.volumetricLightPostProcess = null;
  57630. this.volumetricLightSmoothXPostProcess = null;
  57631. this.volumetricLightSmoothYPostProcess = null;
  57632. this.volumetricLightMergePostProces = null;
  57633. this.volumetricLightFinalPostProcess = null;
  57634. this.lensFlarePostProcess = null;
  57635. this.lensFlareComposePostProcess = null;
  57636. this.luminancePostProcess = null;
  57637. this.hdrPostProcess = null;
  57638. this.hdrFinalPostProcess = null;
  57639. this.depthOfFieldPostProcess = null;
  57640. this.motionBlurPostProcess = null;
  57641. this.luminanceDownSamplePostProcesses = [];
  57642. this.blurHPostProcesses = [];
  57643. this.blurVPostProcesses = [];
  57644. };
  57645. // Dispose
  57646. StandardRenderingPipeline.prototype.dispose = function () {
  57647. this._disposePostProcesses();
  57648. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  57649. _super.prototype.dispose.call(this);
  57650. };
  57651. // Serialize rendering pipeline
  57652. StandardRenderingPipeline.prototype.serialize = function () {
  57653. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  57654. serializationObject.customType = "StandardRenderingPipeline";
  57655. return serializationObject;
  57656. };
  57657. /**
  57658. * Static members
  57659. */
  57660. // Parse serialized pipeline
  57661. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  57662. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  57663. };
  57664. // Luminance steps
  57665. StandardRenderingPipeline.LuminanceSteps = 6;
  57666. __decorate([
  57667. BABYLON.serialize()
  57668. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  57669. __decorate([
  57670. BABYLON.serialize()
  57671. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  57672. __decorate([
  57673. BABYLON.serialize()
  57674. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  57675. __decorate([
  57676. BABYLON.serialize()
  57677. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  57678. __decorate([
  57679. BABYLON.serializeAsTexture("lensTexture")
  57680. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  57681. __decorate([
  57682. BABYLON.serialize()
  57683. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  57684. __decorate([
  57685. BABYLON.serialize()
  57686. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  57687. __decorate([
  57688. BABYLON.serialize()
  57689. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  57690. __decorate([
  57691. BABYLON.serialize()
  57692. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  57693. __decorate([
  57694. BABYLON.serialize()
  57695. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  57696. __decorate([
  57697. BABYLON.serialize()
  57698. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  57699. __decorate([
  57700. BABYLON.serializeAsTexture("lensColorTexture")
  57701. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  57702. __decorate([
  57703. BABYLON.serialize()
  57704. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  57705. __decorate([
  57706. BABYLON.serialize()
  57707. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  57708. __decorate([
  57709. BABYLON.serialize()
  57710. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  57711. __decorate([
  57712. BABYLON.serialize()
  57713. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  57714. __decorate([
  57715. BABYLON.serializeAsTexture("lensStarTexture")
  57716. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  57717. __decorate([
  57718. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  57719. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  57720. __decorate([
  57721. BABYLON.serialize()
  57722. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  57723. __decorate([
  57724. BABYLON.serialize()
  57725. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  57726. __decorate([
  57727. BABYLON.serialize()
  57728. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  57729. __decorate([
  57730. BABYLON.serialize()
  57731. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  57732. __decorate([
  57733. BABYLON.serialize()
  57734. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  57735. __decorate([
  57736. BABYLON.serialize()
  57737. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  57738. __decorate([
  57739. BABYLON.serialize()
  57740. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  57741. __decorate([
  57742. BABYLON.serialize()
  57743. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  57744. __decorate([
  57745. BABYLON.serialize()
  57746. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  57747. __decorate([
  57748. BABYLON.serialize()
  57749. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  57750. __decorate([
  57751. BABYLON.serialize()
  57752. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  57753. return StandardRenderingPipeline;
  57754. }(BABYLON.PostProcessRenderPipeline));
  57755. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  57756. })(BABYLON || (BABYLON = {}));
  57757. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  57758. var BABYLON;
  57759. (function (BABYLON) {
  57760. var FxaaPostProcess = /** @class */ (function (_super) {
  57761. __extends(FxaaPostProcess, _super);
  57762. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  57763. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57764. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  57765. _this.onApplyObservable.add(function (effect) {
  57766. var texelSize = _this.texelSize;
  57767. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  57768. });
  57769. return _this;
  57770. }
  57771. return FxaaPostProcess;
  57772. }(BABYLON.PostProcess));
  57773. BABYLON.FxaaPostProcess = FxaaPostProcess;
  57774. })(BABYLON || (BABYLON = {}));
  57775. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  57776. var BABYLON;
  57777. (function (BABYLON) {
  57778. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  57779. __extends(DefaultRenderingPipeline, _super);
  57780. /**
  57781. * @constructor
  57782. * @param {string} name - The rendering pipeline name
  57783. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57784. * @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)
  57785. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57786. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  57787. */
  57788. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  57789. if (automaticBuild === void 0) { automaticBuild = true; }
  57790. var _this = _super.call(this, scene.getEngine(), name) || this;
  57791. _this.PassPostProcessId = "PassPostProcessEffect";
  57792. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  57793. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  57794. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  57795. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  57796. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  57797. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  57798. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  57799. // IAnimatable
  57800. _this.animations = [];
  57801. // Values
  57802. _this._bloomEnabled = false;
  57803. _this._fxaaEnabled = false;
  57804. _this._imageProcessingEnabled = true;
  57805. _this._bloomScale = 0.6;
  57806. _this._buildAllowed = true;
  57807. /**
  57808. * Specifies the size of the bloom blur kernel, relative to the final output size
  57809. */
  57810. _this.bloomKernel = 64;
  57811. /**
  57812. * Specifies the weight of the bloom in the final rendering
  57813. */
  57814. _this._bloomWeight = 0.15;
  57815. _this._cameras = cameras || [];
  57816. _this._buildAllowed = automaticBuild;
  57817. // Initialize
  57818. _this._scene = scene;
  57819. var caps = _this._scene.getEngine().getCaps();
  57820. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  57821. // Misc
  57822. if (_this._hdr) {
  57823. if (caps.textureHalfFloatRender) {
  57824. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  57825. }
  57826. else if (caps.textureFloatRender) {
  57827. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  57828. }
  57829. }
  57830. else {
  57831. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  57832. }
  57833. // Attach
  57834. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57835. _this._buildPipeline();
  57836. return _this;
  57837. }
  57838. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  57839. get: function () {
  57840. return this._bloomWeight;
  57841. },
  57842. set: function (value) {
  57843. if (this._bloomWeight === value) {
  57844. return;
  57845. }
  57846. this._bloomWeight = value;
  57847. if (this._hdr && this.copyBack) {
  57848. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  57849. }
  57850. },
  57851. enumerable: true,
  57852. configurable: true
  57853. });
  57854. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  57855. get: function () {
  57856. return this._bloomScale;
  57857. },
  57858. set: function (value) {
  57859. if (this._bloomScale === value) {
  57860. return;
  57861. }
  57862. this._bloomScale = value;
  57863. this._buildPipeline();
  57864. },
  57865. enumerable: true,
  57866. configurable: true
  57867. });
  57868. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  57869. get: function () {
  57870. return this._bloomEnabled;
  57871. },
  57872. set: function (enabled) {
  57873. if (this._bloomEnabled === enabled) {
  57874. return;
  57875. }
  57876. this._bloomEnabled = enabled;
  57877. this._buildPipeline();
  57878. },
  57879. enumerable: true,
  57880. configurable: true
  57881. });
  57882. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  57883. get: function () {
  57884. return this._fxaaEnabled;
  57885. },
  57886. set: function (enabled) {
  57887. if (this._fxaaEnabled === enabled) {
  57888. return;
  57889. }
  57890. this._fxaaEnabled = enabled;
  57891. this._buildPipeline();
  57892. },
  57893. enumerable: true,
  57894. configurable: true
  57895. });
  57896. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  57897. get: function () {
  57898. return this._imageProcessingEnabled;
  57899. },
  57900. set: function (enabled) {
  57901. if (this._imageProcessingEnabled === enabled) {
  57902. return;
  57903. }
  57904. this._imageProcessingEnabled = enabled;
  57905. this._buildPipeline();
  57906. },
  57907. enumerable: true,
  57908. configurable: true
  57909. });
  57910. /**
  57911. * Force the compilation of the entire pipeline.
  57912. */
  57913. DefaultRenderingPipeline.prototype.prepare = function () {
  57914. var previousState = this._buildAllowed;
  57915. this._buildAllowed = true;
  57916. this._buildPipeline();
  57917. this._buildAllowed = previousState;
  57918. };
  57919. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  57920. var _this = this;
  57921. if (!this._buildAllowed) {
  57922. return;
  57923. }
  57924. var engine = this._scene.getEngine();
  57925. this._disposePostProcesses();
  57926. this._reset();
  57927. if (this.bloomEnabled) {
  57928. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  57929. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  57930. if (!this._hdr) {
  57931. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  57932. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  57933. this.highlights.autoClear = false;
  57934. this.highlights.alwaysForcePOT = true;
  57935. }
  57936. 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);
  57937. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  57938. this.blurX.alwaysForcePOT = true;
  57939. this.blurX.autoClear = false;
  57940. this.blurX.onActivateObservable.add(function () {
  57941. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  57942. _this.blurX.kernel = _this.bloomKernel * dw;
  57943. });
  57944. 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);
  57945. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  57946. this.blurY.alwaysForcePOT = true;
  57947. this.blurY.autoClear = false;
  57948. this.blurY.onActivateObservable.add(function () {
  57949. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  57950. _this.blurY.kernel = _this.bloomKernel * dh;
  57951. });
  57952. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  57953. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  57954. this.copyBack.alwaysForcePOT = true;
  57955. if (this._hdr) {
  57956. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  57957. var w = this.bloomWeight;
  57958. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  57959. }
  57960. else {
  57961. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  57962. }
  57963. this.copyBack.autoClear = false;
  57964. }
  57965. if (this._imageProcessingEnabled) {
  57966. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  57967. if (this._hdr) {
  57968. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  57969. }
  57970. else {
  57971. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  57972. }
  57973. }
  57974. if (this.fxaaEnabled) {
  57975. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  57976. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  57977. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  57978. }
  57979. else {
  57980. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  57981. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  57982. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  57983. }
  57984. if (this.bloomEnabled) {
  57985. if (this._hdr) {
  57986. this.copyBack.shareOutputWith(this.blurX);
  57987. if (this.imageProcessing) {
  57988. this.imageProcessing.shareOutputWith(this.pass);
  57989. this.imageProcessing.autoClear = false;
  57990. }
  57991. else if (this.fxaa) {
  57992. this.fxaa.shareOutputWith(this.pass);
  57993. }
  57994. else {
  57995. this.finalMerge.shareOutputWith(this.pass);
  57996. }
  57997. }
  57998. else {
  57999. if (this.fxaa) {
  58000. this.fxaa.shareOutputWith(this.pass);
  58001. }
  58002. else {
  58003. this.finalMerge.shareOutputWith(this.pass);
  58004. }
  58005. }
  58006. }
  58007. if (this._cameras !== null) {
  58008. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  58009. }
  58010. };
  58011. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  58012. for (var i = 0; i < this._cameras.length; i++) {
  58013. var camera = this._cameras[i];
  58014. if (this.pass) {
  58015. this.pass.dispose(camera);
  58016. }
  58017. if (this.highlights) {
  58018. this.highlights.dispose(camera);
  58019. }
  58020. if (this.blurX) {
  58021. this.blurX.dispose(camera);
  58022. }
  58023. if (this.blurY) {
  58024. this.blurY.dispose(camera);
  58025. }
  58026. if (this.copyBack) {
  58027. this.copyBack.dispose(camera);
  58028. }
  58029. if (this.imageProcessing) {
  58030. this.imageProcessing.dispose(camera);
  58031. }
  58032. if (this.fxaa) {
  58033. this.fxaa.dispose(camera);
  58034. }
  58035. if (this.finalMerge) {
  58036. this.finalMerge.dispose(camera);
  58037. }
  58038. }
  58039. this.pass = null;
  58040. this.highlights = null;
  58041. this.blurX = null;
  58042. this.blurY = null;
  58043. this.copyBack = null;
  58044. this.imageProcessing = null;
  58045. this.fxaa = null;
  58046. this.finalMerge = null;
  58047. };
  58048. // Dispose
  58049. DefaultRenderingPipeline.prototype.dispose = function () {
  58050. this._disposePostProcesses();
  58051. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  58052. _super.prototype.dispose.call(this);
  58053. };
  58054. // Serialize rendering pipeline
  58055. DefaultRenderingPipeline.prototype.serialize = function () {
  58056. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58057. serializationObject.customType = "DefaultRenderingPipeline";
  58058. return serializationObject;
  58059. };
  58060. // Parse serialized pipeline
  58061. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  58062. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  58063. };
  58064. __decorate([
  58065. BABYLON.serialize()
  58066. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  58067. __decorate([
  58068. BABYLON.serialize()
  58069. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  58070. __decorate([
  58071. BABYLON.serialize()
  58072. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  58073. __decorate([
  58074. BABYLON.serialize()
  58075. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  58076. __decorate([
  58077. BABYLON.serialize()
  58078. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  58079. __decorate([
  58080. BABYLON.serialize()
  58081. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  58082. __decorate([
  58083. BABYLON.serialize()
  58084. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  58085. __decorate([
  58086. BABYLON.serialize()
  58087. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  58088. return DefaultRenderingPipeline;
  58089. }(BABYLON.PostProcessRenderPipeline));
  58090. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  58091. })(BABYLON || (BABYLON = {}));
  58092. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  58093. var BABYLON;
  58094. (function (BABYLON) {
  58095. var GeometryBufferRenderer = /** @class */ (function () {
  58096. function GeometryBufferRenderer(scene, ratio) {
  58097. if (ratio === void 0) { ratio = 1; }
  58098. this._enablePosition = false;
  58099. this._scene = scene;
  58100. this._ratio = ratio;
  58101. // Render target
  58102. this._createRenderTargets();
  58103. }
  58104. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  58105. set: function (meshes) {
  58106. this._multiRenderTarget.renderList = meshes;
  58107. },
  58108. enumerable: true,
  58109. configurable: true
  58110. });
  58111. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  58112. get: function () {
  58113. return this._multiRenderTarget.isSupported;
  58114. },
  58115. enumerable: true,
  58116. configurable: true
  58117. });
  58118. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  58119. get: function () {
  58120. return this._enablePosition;
  58121. },
  58122. set: function (enable) {
  58123. this._enablePosition = enable;
  58124. this.dispose();
  58125. this._createRenderTargets();
  58126. },
  58127. enumerable: true,
  58128. configurable: true
  58129. });
  58130. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  58131. var material = subMesh.getMaterial();
  58132. if (material && material.disableDepthWrite) {
  58133. return false;
  58134. }
  58135. var defines = [];
  58136. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  58137. var mesh = subMesh.getMesh();
  58138. // Alpha test
  58139. if (material && material.needAlphaTesting()) {
  58140. defines.push("#define ALPHATEST");
  58141. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58142. attribs.push(BABYLON.VertexBuffer.UVKind);
  58143. defines.push("#define UV1");
  58144. }
  58145. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  58146. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  58147. defines.push("#define UV2");
  58148. }
  58149. }
  58150. // Buffers
  58151. if (this._enablePosition) {
  58152. defines.push("#define POSITION");
  58153. }
  58154. // Bones
  58155. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58156. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58157. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58158. if (mesh.numBoneInfluencers > 4) {
  58159. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58160. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58161. }
  58162. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58163. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  58164. }
  58165. else {
  58166. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58167. }
  58168. // Instances
  58169. if (useInstances) {
  58170. defines.push("#define INSTANCES");
  58171. attribs.push("world0");
  58172. attribs.push("world1");
  58173. attribs.push("world2");
  58174. attribs.push("world3");
  58175. }
  58176. // Get correct effect
  58177. var join = defines.join("\n");
  58178. if (this._cachedDefines !== join) {
  58179. this._cachedDefines = join;
  58180. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, null, null, null, { buffersCount: this._enablePosition ? 3 : 2 });
  58181. }
  58182. return this._effect.isReady();
  58183. };
  58184. GeometryBufferRenderer.prototype.getGBuffer = function () {
  58185. return this._multiRenderTarget;
  58186. };
  58187. // Methods
  58188. GeometryBufferRenderer.prototype.dispose = function () {
  58189. this.getGBuffer().dispose();
  58190. };
  58191. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  58192. var _this = this;
  58193. var engine = this._scene.getEngine();
  58194. var count = this._enablePosition ? 3 : 2;
  58195. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  58196. if (!this.isSupported) {
  58197. return null;
  58198. }
  58199. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58200. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58201. this._multiRenderTarget.refreshRate = 1;
  58202. this._multiRenderTarget.renderParticles = false;
  58203. this._multiRenderTarget.renderList = null;
  58204. // set default depth value to 1.0 (far away)
  58205. this._multiRenderTarget.onClearObservable.add(function (engine) {
  58206. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  58207. });
  58208. // Custom render function
  58209. var renderSubMesh = function (subMesh) {
  58210. var mesh = subMesh.getRenderingMesh();
  58211. var scene = _this._scene;
  58212. var engine = scene.getEngine();
  58213. // Culling
  58214. engine.setState(subMesh.getMaterial().backFaceCulling);
  58215. // Managing instances
  58216. var batch = mesh._getInstancesRenderList(subMesh._id);
  58217. if (batch.mustReturn) {
  58218. return;
  58219. }
  58220. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  58221. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  58222. engine.enableEffect(_this._effect);
  58223. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  58224. var material = subMesh.getMaterial();
  58225. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  58226. _this._effect.setMatrix("view", scene.getViewMatrix());
  58227. // Alpha test
  58228. if (material && material.needAlphaTesting()) {
  58229. var alphaTexture = material.getAlphaTestTexture();
  58230. _this._effect.setTexture("diffuseSampler", alphaTexture);
  58231. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  58232. }
  58233. // Bones
  58234. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58235. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  58236. }
  58237. // Draw
  58238. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  58239. }
  58240. };
  58241. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  58242. var index;
  58243. if (depthOnlySubMeshes.length) {
  58244. engine.setColorWrite(false);
  58245. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  58246. renderSubMesh(depthOnlySubMeshes.data[index]);
  58247. }
  58248. engine.setColorWrite(true);
  58249. }
  58250. for (index = 0; index < opaqueSubMeshes.length; index++) {
  58251. renderSubMesh(opaqueSubMeshes.data[index]);
  58252. }
  58253. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  58254. renderSubMesh(alphaTestSubMeshes.data[index]);
  58255. }
  58256. };
  58257. };
  58258. return GeometryBufferRenderer;
  58259. }());
  58260. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  58261. })(BABYLON || (BABYLON = {}));
  58262. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  58263. var BABYLON;
  58264. (function (BABYLON) {
  58265. var RefractionPostProcess = /** @class */ (function (_super) {
  58266. __extends(RefractionPostProcess, _super);
  58267. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  58268. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  58269. _this.color = color;
  58270. _this.depth = depth;
  58271. _this.colorLevel = colorLevel;
  58272. _this.onActivateObservable.add(function (cam) {
  58273. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  58274. });
  58275. _this.onApplyObservable.add(function (effect) {
  58276. effect.setColor3("baseColor", _this.color);
  58277. effect.setFloat("depth", _this.depth);
  58278. effect.setFloat("colorLevel", _this.colorLevel);
  58279. effect.setTexture("refractionSampler", _this._refRexture);
  58280. });
  58281. return _this;
  58282. }
  58283. // Methods
  58284. RefractionPostProcess.prototype.dispose = function (camera) {
  58285. if (this._refRexture) {
  58286. this._refRexture.dispose();
  58287. }
  58288. _super.prototype.dispose.call(this, camera);
  58289. };
  58290. return RefractionPostProcess;
  58291. }(BABYLON.PostProcess));
  58292. BABYLON.RefractionPostProcess = RefractionPostProcess;
  58293. })(BABYLON || (BABYLON = {}));
  58294. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  58295. var BABYLON;
  58296. (function (BABYLON) {
  58297. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  58298. __extends(BlackAndWhitePostProcess, _super);
  58299. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  58300. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  58301. _this.degree = 1;
  58302. _this.onApplyObservable.add(function (effect) {
  58303. effect.setFloat("degree", _this.degree);
  58304. });
  58305. return _this;
  58306. }
  58307. return BlackAndWhitePostProcess;
  58308. }(BABYLON.PostProcess));
  58309. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  58310. })(BABYLON || (BABYLON = {}));
  58311. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  58312. var BABYLON;
  58313. (function (BABYLON) {
  58314. var ConvolutionPostProcess = /** @class */ (function (_super) {
  58315. __extends(ConvolutionPostProcess, _super);
  58316. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  58317. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  58318. _this.kernel = kernel;
  58319. _this.onApply = function (effect) {
  58320. effect.setFloat2("screenSize", _this.width, _this.height);
  58321. effect.setArray("kernel", _this.kernel);
  58322. };
  58323. return _this;
  58324. }
  58325. // Statics
  58326. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  58327. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  58328. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  58329. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  58330. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  58331. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  58332. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  58333. return ConvolutionPostProcess;
  58334. }(BABYLON.PostProcess));
  58335. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  58336. })(BABYLON || (BABYLON = {}));
  58337. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  58338. var BABYLON;
  58339. (function (BABYLON) {
  58340. var FilterPostProcess = /** @class */ (function (_super) {
  58341. __extends(FilterPostProcess, _super);
  58342. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  58343. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  58344. _this.kernelMatrix = kernelMatrix;
  58345. _this.onApply = function (effect) {
  58346. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  58347. };
  58348. return _this;
  58349. }
  58350. return FilterPostProcess;
  58351. }(BABYLON.PostProcess));
  58352. BABYLON.FilterPostProcess = FilterPostProcess;
  58353. })(BABYLON || (BABYLON = {}));
  58354. //# sourceMappingURL=babylon.filterPostProcess.js.map
  58355. var BABYLON;
  58356. (function (BABYLON) {
  58357. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  58358. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  58359. __extends(VolumetricLightScatteringPostProcess, _super);
  58360. /**
  58361. * @constructor
  58362. * @param {string} name - The post-process name
  58363. * @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)
  58364. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  58365. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  58366. * @param {number} samples - The post-process quality, default 100
  58367. * @param {number} samplingMode - The post-process filtering mode
  58368. * @param {BABYLON.Engine} engine - The babylon engine
  58369. * @param {boolean} reusable - If the post-process is reusable
  58370. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  58371. */
  58372. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  58373. if (samples === void 0) { samples = 100; }
  58374. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  58375. 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;
  58376. _this._screenCoordinates = BABYLON.Vector2.Zero();
  58377. /**
  58378. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  58379. * @type {Vector3}
  58380. */
  58381. _this.customMeshPosition = BABYLON.Vector3.Zero();
  58382. /**
  58383. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  58384. * @type {boolean}
  58385. */
  58386. _this.useCustomMeshPosition = false;
  58387. /**
  58388. * If the post-process should inverse the light scattering direction
  58389. * @type {boolean}
  58390. */
  58391. _this.invert = true;
  58392. /**
  58393. * Array containing the excluded meshes not rendered in the internal pass
  58394. */
  58395. _this.excludedMeshes = new Array();
  58396. /**
  58397. * Controls the overall intensity of the post-process
  58398. * @type {number}
  58399. */
  58400. _this.exposure = 0.3;
  58401. /**
  58402. * Dissipates each sample's contribution in range [0, 1]
  58403. * @type {number}
  58404. */
  58405. _this.decay = 0.96815;
  58406. /**
  58407. * Controls the overall intensity of each sample
  58408. * @type {number}
  58409. */
  58410. _this.weight = 0.58767;
  58411. /**
  58412. * Controls the density of each sample
  58413. * @type {number}
  58414. */
  58415. _this.density = 0.926;
  58416. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  58417. var engine = scene.getEngine();
  58418. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  58419. // Configure mesh
  58420. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  58421. // Configure
  58422. _this._createPass(scene, ratio.passRatio || ratio);
  58423. _this.onActivate = function (camera) {
  58424. if (!_this.isSupported) {
  58425. _this.dispose(camera);
  58426. }
  58427. _this.onActivate = null;
  58428. };
  58429. _this.onApplyObservable.add(function (effect) {
  58430. _this._updateMeshScreenCoordinates(scene);
  58431. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  58432. effect.setFloat("exposure", _this.exposure);
  58433. effect.setFloat("decay", _this.decay);
  58434. effect.setFloat("weight", _this.weight);
  58435. effect.setFloat("density", _this.density);
  58436. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  58437. });
  58438. return _this;
  58439. }
  58440. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  58441. get: function () {
  58442. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  58443. return false;
  58444. },
  58445. set: function (useDiffuseColor) {
  58446. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  58447. },
  58448. enumerable: true,
  58449. configurable: true
  58450. });
  58451. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  58452. return "VolumetricLightScatteringPostProcess";
  58453. };
  58454. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  58455. var mesh = subMesh.getMesh();
  58456. // Render this.mesh as default
  58457. if (mesh === this.mesh) {
  58458. return mesh.material.isReady(mesh);
  58459. }
  58460. var defines = [];
  58461. var attribs = [BABYLON.VertexBuffer.PositionKind];
  58462. var material = subMesh.getMaterial();
  58463. // Alpha test
  58464. if (material) {
  58465. if (material.needAlphaTesting()) {
  58466. defines.push("#define ALPHATEST");
  58467. }
  58468. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58469. attribs.push(BABYLON.VertexBuffer.UVKind);
  58470. defines.push("#define UV1");
  58471. }
  58472. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  58473. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  58474. defines.push("#define UV2");
  58475. }
  58476. }
  58477. // Bones
  58478. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58479. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58480. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58481. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58482. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  58483. }
  58484. else {
  58485. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58486. }
  58487. // Instances
  58488. if (useInstances) {
  58489. defines.push("#define INSTANCES");
  58490. attribs.push("world0");
  58491. attribs.push("world1");
  58492. attribs.push("world2");
  58493. attribs.push("world3");
  58494. }
  58495. // Get correct effect
  58496. var join = defines.join("\n");
  58497. if (this._cachedDefines !== join) {
  58498. this._cachedDefines = join;
  58499. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  58500. }
  58501. return this._volumetricLightScatteringPass.isReady();
  58502. };
  58503. /**
  58504. * Sets the new light position for light scattering effect
  58505. * @param {BABYLON.Vector3} The new custom light position
  58506. */
  58507. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  58508. this.customMeshPosition = position;
  58509. };
  58510. /**
  58511. * Returns the light position for light scattering effect
  58512. * @return {BABYLON.Vector3} The custom light position
  58513. */
  58514. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  58515. return this.customMeshPosition;
  58516. };
  58517. /**
  58518. * Disposes the internal assets and detaches the post-process from the camera
  58519. */
  58520. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  58521. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  58522. if (rttIndex !== -1) {
  58523. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  58524. }
  58525. this._volumetricLightScatteringRTT.dispose();
  58526. _super.prototype.dispose.call(this, camera);
  58527. };
  58528. /**
  58529. * Returns the render target texture used by the post-process
  58530. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  58531. */
  58532. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  58533. return this._volumetricLightScatteringRTT;
  58534. };
  58535. // Private methods
  58536. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  58537. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  58538. return true;
  58539. }
  58540. return false;
  58541. };
  58542. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  58543. var _this = this;
  58544. var engine = scene.getEngine();
  58545. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  58546. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58547. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58548. this._volumetricLightScatteringRTT.renderList = null;
  58549. this._volumetricLightScatteringRTT.renderParticles = false;
  58550. var camera = this.getCamera();
  58551. if (camera) {
  58552. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  58553. }
  58554. else {
  58555. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  58556. }
  58557. // Custom render function for submeshes
  58558. var renderSubMesh = function (subMesh) {
  58559. var mesh = subMesh.getRenderingMesh();
  58560. if (_this._meshExcluded(mesh)) {
  58561. return;
  58562. }
  58563. var scene = mesh.getScene();
  58564. var engine = scene.getEngine();
  58565. // Culling
  58566. engine.setState(subMesh.getMaterial().backFaceCulling);
  58567. // Managing instances
  58568. var batch = mesh._getInstancesRenderList(subMesh._id);
  58569. if (batch.mustReturn) {
  58570. return;
  58571. }
  58572. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  58573. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  58574. var effect = _this._volumetricLightScatteringPass;
  58575. if (mesh === _this.mesh) {
  58576. if (subMesh.effect) {
  58577. effect = subMesh.effect;
  58578. }
  58579. else {
  58580. effect = subMesh.getMaterial().getEffect();
  58581. }
  58582. }
  58583. engine.enableEffect(effect);
  58584. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  58585. if (mesh === _this.mesh) {
  58586. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  58587. }
  58588. else {
  58589. var material = subMesh.getMaterial();
  58590. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  58591. // Alpha test
  58592. if (material && material.needAlphaTesting()) {
  58593. var alphaTexture = material.getAlphaTestTexture();
  58594. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  58595. if (alphaTexture) {
  58596. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  58597. }
  58598. }
  58599. // Bones
  58600. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58601. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  58602. }
  58603. }
  58604. // Draw
  58605. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  58606. }
  58607. };
  58608. // Render target texture callbacks
  58609. var savedSceneClearColor;
  58610. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  58611. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  58612. savedSceneClearColor = scene.clearColor;
  58613. scene.clearColor = sceneClearColor;
  58614. });
  58615. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  58616. scene.clearColor = savedSceneClearColor;
  58617. });
  58618. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  58619. var engine = scene.getEngine();
  58620. var index;
  58621. if (depthOnlySubMeshes.length) {
  58622. engine.setColorWrite(false);
  58623. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  58624. renderSubMesh(depthOnlySubMeshes.data[index]);
  58625. }
  58626. engine.setColorWrite(true);
  58627. }
  58628. for (index = 0; index < opaqueSubMeshes.length; index++) {
  58629. renderSubMesh(opaqueSubMeshes.data[index]);
  58630. }
  58631. engine.setAlphaTesting(true);
  58632. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  58633. renderSubMesh(alphaTestSubMeshes.data[index]);
  58634. }
  58635. engine.setAlphaTesting(false);
  58636. if (transparentSubMeshes.length) {
  58637. // Sort sub meshes
  58638. for (index = 0; index < transparentSubMeshes.length; index++) {
  58639. var submesh = transparentSubMeshes.data[index];
  58640. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  58641. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  58642. }
  58643. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  58644. sortedArray.sort(function (a, b) {
  58645. // Alpha index first
  58646. if (a._alphaIndex > b._alphaIndex) {
  58647. return 1;
  58648. }
  58649. if (a._alphaIndex < b._alphaIndex) {
  58650. return -1;
  58651. }
  58652. // Then distance to camera
  58653. if (a._distanceToCamera < b._distanceToCamera) {
  58654. return 1;
  58655. }
  58656. if (a._distanceToCamera > b._distanceToCamera) {
  58657. return -1;
  58658. }
  58659. return 0;
  58660. });
  58661. // Render sub meshes
  58662. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  58663. for (index = 0; index < sortedArray.length; index++) {
  58664. renderSubMesh(sortedArray[index]);
  58665. }
  58666. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58667. }
  58668. };
  58669. };
  58670. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  58671. var transform = scene.getTransformMatrix();
  58672. var meshPosition;
  58673. if (this.useCustomMeshPosition) {
  58674. meshPosition = this.customMeshPosition;
  58675. }
  58676. else if (this.attachedNode) {
  58677. meshPosition = this.attachedNode.position;
  58678. }
  58679. else {
  58680. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  58681. }
  58682. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  58683. this._screenCoordinates.x = pos.x / this._viewPort.width;
  58684. this._screenCoordinates.y = pos.y / this._viewPort.height;
  58685. if (this.invert)
  58686. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  58687. };
  58688. // Static methods
  58689. /**
  58690. * Creates a default mesh for the Volumeric Light Scattering post-process
  58691. * @param {string} The mesh name
  58692. * @param {BABYLON.Scene} The scene where to create the mesh
  58693. * @return {BABYLON.Mesh} the default mesh
  58694. */
  58695. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  58696. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  58697. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  58698. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  58699. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  58700. mesh.material = material;
  58701. return mesh;
  58702. };
  58703. __decorate([
  58704. BABYLON.serializeAsVector3()
  58705. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  58706. __decorate([
  58707. BABYLON.serialize()
  58708. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  58709. __decorate([
  58710. BABYLON.serialize()
  58711. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  58712. __decorate([
  58713. BABYLON.serializeAsMeshReference()
  58714. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  58715. __decorate([
  58716. BABYLON.serialize()
  58717. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  58718. __decorate([
  58719. BABYLON.serialize()
  58720. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  58721. __decorate([
  58722. BABYLON.serialize()
  58723. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  58724. __decorate([
  58725. BABYLON.serialize()
  58726. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  58727. __decorate([
  58728. BABYLON.serialize()
  58729. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  58730. return VolumetricLightScatteringPostProcess;
  58731. }(BABYLON.PostProcess));
  58732. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  58733. })(BABYLON || (BABYLON = {}));
  58734. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  58735. //
  58736. // This post-process allows the modification of rendered colors by using
  58737. // a 'look-up table' (LUT). This effect is also called Color Grading.
  58738. //
  58739. // The object needs to be provided an url to a texture containing the color
  58740. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  58741. // Use an image editing software to tweak the LUT to match your needs.
  58742. //
  58743. // For an example of a color LUT, see here:
  58744. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  58745. // For explanations on color grading, see here:
  58746. // http://udn.epicgames.com/Three/ColorGrading.html
  58747. //
  58748. var BABYLON;
  58749. (function (BABYLON) {
  58750. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  58751. __extends(ColorCorrectionPostProcess, _super);
  58752. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  58753. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  58754. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  58755. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  58756. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58757. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58758. _this.onApply = function (effect) {
  58759. effect.setTexture("colorTable", _this._colorTableTexture);
  58760. };
  58761. return _this;
  58762. }
  58763. return ColorCorrectionPostProcess;
  58764. }(BABYLON.PostProcess));
  58765. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  58766. })(BABYLON || (BABYLON = {}));
  58767. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  58768. var BABYLON;
  58769. (function (BABYLON) {
  58770. var TonemappingOperator;
  58771. (function (TonemappingOperator) {
  58772. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  58773. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  58774. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  58775. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  58776. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  58777. ;
  58778. var TonemapPostProcess = /** @class */ (function (_super) {
  58779. __extends(TonemapPostProcess, _super);
  58780. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  58781. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  58782. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58783. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  58784. _this._operator = _operator;
  58785. _this.exposureAdjustment = exposureAdjustment;
  58786. var defines = "#define ";
  58787. if (_this._operator === TonemappingOperator.Hable)
  58788. defines += "HABLE_TONEMAPPING";
  58789. else if (_this._operator === TonemappingOperator.Reinhard)
  58790. defines += "REINHARD_TONEMAPPING";
  58791. else if (_this._operator === TonemappingOperator.HejiDawson)
  58792. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  58793. else if (_this._operator === TonemappingOperator.Photographic)
  58794. defines += "PHOTOGRAPHIC_TONEMAPPING";
  58795. //sadly a second call to create the effect.
  58796. _this.updateEffect(defines);
  58797. _this.onApply = function (effect) {
  58798. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  58799. };
  58800. return _this;
  58801. }
  58802. return TonemapPostProcess;
  58803. }(BABYLON.PostProcess));
  58804. BABYLON.TonemapPostProcess = TonemapPostProcess;
  58805. })(BABYLON || (BABYLON = {}));
  58806. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  58807. var BABYLON;
  58808. (function (BABYLON) {
  58809. var DisplayPassPostProcess = /** @class */ (function (_super) {
  58810. __extends(DisplayPassPostProcess, _super);
  58811. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  58812. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  58813. }
  58814. return DisplayPassPostProcess;
  58815. }(BABYLON.PostProcess));
  58816. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  58817. })(BABYLON || (BABYLON = {}));
  58818. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  58819. var BABYLON;
  58820. (function (BABYLON) {
  58821. var HighlightsPostProcess = /** @class */ (function (_super) {
  58822. __extends(HighlightsPostProcess, _super);
  58823. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  58824. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58825. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  58826. }
  58827. return HighlightsPostProcess;
  58828. }(BABYLON.PostProcess));
  58829. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  58830. })(BABYLON || (BABYLON = {}));
  58831. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  58832. var BABYLON;
  58833. (function (BABYLON) {
  58834. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  58835. __extends(ImageProcessingPostProcess, _super);
  58836. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  58837. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58838. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  58839. _this._fromLinearSpace = true;
  58840. /**
  58841. * Defines cache preventing GC.
  58842. */
  58843. _this._defines = {
  58844. IMAGEPROCESSING: false,
  58845. VIGNETTE: false,
  58846. VIGNETTEBLENDMODEMULTIPLY: false,
  58847. VIGNETTEBLENDMODEOPAQUE: false,
  58848. TONEMAPPING: false,
  58849. CONTRAST: false,
  58850. COLORCURVES: false,
  58851. COLORGRADING: false,
  58852. FROMLINEARSPACE: false,
  58853. SAMPLER3DGREENDEPTH: false,
  58854. SAMPLER3DBGRMAP: false,
  58855. IMAGEPROCESSINGPOSTPROCESS: false,
  58856. EXPOSURE: false,
  58857. };
  58858. // Setup the default processing configuration to the scene.
  58859. _this._attachImageProcessingConfiguration(null, true);
  58860. _this.imageProcessingConfiguration.applyByPostProcess = true;
  58861. _this.onApply = function (effect) {
  58862. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  58863. };
  58864. return _this;
  58865. }
  58866. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  58867. /**
  58868. * Gets the image processing configuration used either in this material.
  58869. */
  58870. get: function () {
  58871. return this._imageProcessingConfiguration;
  58872. },
  58873. /**
  58874. * Sets the Default image processing configuration used either in the this material.
  58875. *
  58876. * If sets to null, the scene one is in use.
  58877. */
  58878. set: function (value) {
  58879. this._attachImageProcessingConfiguration(value);
  58880. },
  58881. enumerable: true,
  58882. configurable: true
  58883. });
  58884. /**
  58885. * Attaches a new image processing configuration to the PBR Material.
  58886. * @param configuration
  58887. */
  58888. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  58889. var _this = this;
  58890. if (doNotBuild === void 0) { doNotBuild = false; }
  58891. if (configuration === this._imageProcessingConfiguration) {
  58892. return;
  58893. }
  58894. // Detaches observer.
  58895. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  58896. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  58897. }
  58898. // Pick the scene configuration if needed.
  58899. if (!configuration) {
  58900. var scene = null;
  58901. var engine = this.getEngine();
  58902. var camera = this.getCamera();
  58903. if (camera) {
  58904. scene = camera.getScene();
  58905. }
  58906. else if (engine && engine.scenes) {
  58907. var scenes = engine.scenes;
  58908. scene = scenes[scenes.length - 1];
  58909. }
  58910. else {
  58911. scene = BABYLON.Engine.LastCreatedScene;
  58912. }
  58913. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  58914. }
  58915. else {
  58916. this._imageProcessingConfiguration = configuration;
  58917. }
  58918. // Attaches observer.
  58919. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  58920. _this._updateParameters();
  58921. });
  58922. // Ensure the effect will be rebuilt.
  58923. if (!doNotBuild) {
  58924. this._updateParameters();
  58925. }
  58926. };
  58927. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  58928. /**
  58929. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  58930. */
  58931. get: function () {
  58932. return this.imageProcessingConfiguration.colorCurves;
  58933. },
  58934. /**
  58935. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  58936. */
  58937. set: function (value) {
  58938. this.imageProcessingConfiguration.colorCurves = value;
  58939. },
  58940. enumerable: true,
  58941. configurable: true
  58942. });
  58943. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  58944. /**
  58945. * Gets wether the color curves effect is enabled.
  58946. */
  58947. get: function () {
  58948. return this.imageProcessingConfiguration.colorCurvesEnabled;
  58949. },
  58950. /**
  58951. * Sets wether the color curves effect is enabled.
  58952. */
  58953. set: function (value) {
  58954. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  58955. },
  58956. enumerable: true,
  58957. configurable: true
  58958. });
  58959. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  58960. /**
  58961. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  58962. */
  58963. get: function () {
  58964. return this.imageProcessingConfiguration.colorGradingTexture;
  58965. },
  58966. /**
  58967. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  58968. */
  58969. set: function (value) {
  58970. this.imageProcessingConfiguration.colorGradingTexture = value;
  58971. },
  58972. enumerable: true,
  58973. configurable: true
  58974. });
  58975. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  58976. /**
  58977. * Gets wether the color grading effect is enabled.
  58978. */
  58979. get: function () {
  58980. return this.imageProcessingConfiguration.colorGradingEnabled;
  58981. },
  58982. /**
  58983. * Gets wether the color grading effect is enabled.
  58984. */
  58985. set: function (value) {
  58986. this.imageProcessingConfiguration.colorGradingEnabled = value;
  58987. },
  58988. enumerable: true,
  58989. configurable: true
  58990. });
  58991. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  58992. /**
  58993. * Gets exposure used in the effect.
  58994. */
  58995. get: function () {
  58996. return this.imageProcessingConfiguration.exposure;
  58997. },
  58998. /**
  58999. * Sets exposure used in the effect.
  59000. */
  59001. set: function (value) {
  59002. this.imageProcessingConfiguration.exposure = value;
  59003. },
  59004. enumerable: true,
  59005. configurable: true
  59006. });
  59007. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  59008. /**
  59009. * Gets wether tonemapping is enabled or not.
  59010. */
  59011. get: function () {
  59012. return this._imageProcessingConfiguration.toneMappingEnabled;
  59013. },
  59014. /**
  59015. * Sets wether tonemapping is enabled or not
  59016. */
  59017. set: function (value) {
  59018. this._imageProcessingConfiguration.toneMappingEnabled = value;
  59019. },
  59020. enumerable: true,
  59021. configurable: true
  59022. });
  59023. ;
  59024. ;
  59025. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  59026. /**
  59027. * Gets contrast used in the effect.
  59028. */
  59029. get: function () {
  59030. return this.imageProcessingConfiguration.contrast;
  59031. },
  59032. /**
  59033. * Sets contrast used in the effect.
  59034. */
  59035. set: function (value) {
  59036. this.imageProcessingConfiguration.contrast = value;
  59037. },
  59038. enumerable: true,
  59039. configurable: true
  59040. });
  59041. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  59042. /**
  59043. * Gets Vignette stretch size.
  59044. */
  59045. get: function () {
  59046. return this.imageProcessingConfiguration.vignetteStretch;
  59047. },
  59048. /**
  59049. * Sets Vignette stretch size.
  59050. */
  59051. set: function (value) {
  59052. this.imageProcessingConfiguration.vignetteStretch = value;
  59053. },
  59054. enumerable: true,
  59055. configurable: true
  59056. });
  59057. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  59058. /**
  59059. * Gets Vignette centre X Offset.
  59060. */
  59061. get: function () {
  59062. return this.imageProcessingConfiguration.vignetteCentreX;
  59063. },
  59064. /**
  59065. * Sets Vignette centre X Offset.
  59066. */
  59067. set: function (value) {
  59068. this.imageProcessingConfiguration.vignetteCentreX = value;
  59069. },
  59070. enumerable: true,
  59071. configurable: true
  59072. });
  59073. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  59074. /**
  59075. * Gets Vignette centre Y Offset.
  59076. */
  59077. get: function () {
  59078. return this.imageProcessingConfiguration.vignetteCentreY;
  59079. },
  59080. /**
  59081. * Sets Vignette centre Y Offset.
  59082. */
  59083. set: function (value) {
  59084. this.imageProcessingConfiguration.vignetteCentreY = value;
  59085. },
  59086. enumerable: true,
  59087. configurable: true
  59088. });
  59089. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  59090. /**
  59091. * Gets Vignette weight or intensity of the vignette effect.
  59092. */
  59093. get: function () {
  59094. return this.imageProcessingConfiguration.vignetteWeight;
  59095. },
  59096. /**
  59097. * Sets Vignette weight or intensity of the vignette effect.
  59098. */
  59099. set: function (value) {
  59100. this.imageProcessingConfiguration.vignetteWeight = value;
  59101. },
  59102. enumerable: true,
  59103. configurable: true
  59104. });
  59105. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  59106. /**
  59107. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  59108. * if vignetteEnabled is set to true.
  59109. */
  59110. get: function () {
  59111. return this.imageProcessingConfiguration.vignetteColor;
  59112. },
  59113. /**
  59114. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  59115. * if vignetteEnabled is set to true.
  59116. */
  59117. set: function (value) {
  59118. this.imageProcessingConfiguration.vignetteColor = value;
  59119. },
  59120. enumerable: true,
  59121. configurable: true
  59122. });
  59123. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  59124. /**
  59125. * Gets Camera field of view used by the Vignette effect.
  59126. */
  59127. get: function () {
  59128. return this.imageProcessingConfiguration.vignetteCameraFov;
  59129. },
  59130. /**
  59131. * Sets Camera field of view used by the Vignette effect.
  59132. */
  59133. set: function (value) {
  59134. this.imageProcessingConfiguration.vignetteCameraFov = value;
  59135. },
  59136. enumerable: true,
  59137. configurable: true
  59138. });
  59139. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  59140. /**
  59141. * Gets the vignette blend mode allowing different kind of effect.
  59142. */
  59143. get: function () {
  59144. return this.imageProcessingConfiguration.vignetteBlendMode;
  59145. },
  59146. /**
  59147. * Sets the vignette blend mode allowing different kind of effect.
  59148. */
  59149. set: function (value) {
  59150. this.imageProcessingConfiguration.vignetteBlendMode = value;
  59151. },
  59152. enumerable: true,
  59153. configurable: true
  59154. });
  59155. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  59156. /**
  59157. * Gets wether the vignette effect is enabled.
  59158. */
  59159. get: function () {
  59160. return this.imageProcessingConfiguration.vignetteEnabled;
  59161. },
  59162. /**
  59163. * Sets wether the vignette effect is enabled.
  59164. */
  59165. set: function (value) {
  59166. this.imageProcessingConfiguration.vignetteEnabled = value;
  59167. },
  59168. enumerable: true,
  59169. configurable: true
  59170. });
  59171. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  59172. /**
  59173. * Gets wether the input of the processing is in Gamma or Linear Space.
  59174. */
  59175. get: function () {
  59176. return this._fromLinearSpace;
  59177. },
  59178. /**
  59179. * Sets wether the input of the processing is in Gamma or Linear Space.
  59180. */
  59181. set: function (value) {
  59182. if (this._fromLinearSpace === value) {
  59183. return;
  59184. }
  59185. this._fromLinearSpace = value;
  59186. this._updateParameters();
  59187. },
  59188. enumerable: true,
  59189. configurable: true
  59190. });
  59191. ImageProcessingPostProcess.prototype.getClassName = function () {
  59192. return "ImageProcessingPostProcess";
  59193. };
  59194. ImageProcessingPostProcess.prototype._updateParameters = function () {
  59195. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  59196. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  59197. var defines = "";
  59198. for (var define in this._defines) {
  59199. if (this._defines[define]) {
  59200. defines += "#define " + define + ";\r\n";
  59201. }
  59202. }
  59203. var samplers = ["textureSampler"];
  59204. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  59205. var uniforms = ["scale"];
  59206. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  59207. this.updateEffect(defines, uniforms, samplers);
  59208. };
  59209. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  59210. _super.prototype.dispose.call(this, camera);
  59211. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  59212. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  59213. }
  59214. this.imageProcessingConfiguration.applyByPostProcess = false;
  59215. };
  59216. __decorate([
  59217. BABYLON.serialize()
  59218. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  59219. return ImageProcessingPostProcess;
  59220. }(BABYLON.PostProcess));
  59221. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  59222. })(BABYLON || (BABYLON = {}));
  59223. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  59224. var BABYLON;
  59225. (function (BABYLON) {
  59226. var BlurPostProcess = /** @class */ (function (_super) {
  59227. __extends(BlurPostProcess, _super);
  59228. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  59229. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59230. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59231. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  59232. _this.direction = direction;
  59233. _this._packedFloat = false;
  59234. _this.onApplyObservable.add(function (effect) {
  59235. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  59236. });
  59237. _this.kernel = kernel;
  59238. return _this;
  59239. }
  59240. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  59241. /**
  59242. * Gets the length in pixels of the blur sample region
  59243. */
  59244. get: function () {
  59245. return this._idealKernel;
  59246. },
  59247. /**
  59248. * Sets the length in pixels of the blur sample region
  59249. */
  59250. set: function (v) {
  59251. if (this._idealKernel === v) {
  59252. return;
  59253. }
  59254. v = Math.max(v, 1);
  59255. this._idealKernel = v;
  59256. this._kernel = this._nearestBestKernel(v);
  59257. this._updateParameters();
  59258. },
  59259. enumerable: true,
  59260. configurable: true
  59261. });
  59262. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  59263. /**
  59264. * Gets wether or not the blur is unpacking/repacking floats
  59265. */
  59266. get: function () {
  59267. return this._packedFloat;
  59268. },
  59269. /**
  59270. * Sets wether or not the blur needs to unpack/repack floats
  59271. */
  59272. set: function (v) {
  59273. if (this._packedFloat === v) {
  59274. return;
  59275. }
  59276. this._packedFloat = v;
  59277. this._updateParameters();
  59278. },
  59279. enumerable: true,
  59280. configurable: true
  59281. });
  59282. BlurPostProcess.prototype._updateParameters = function () {
  59283. // Generate sampling offsets and weights
  59284. var N = this._kernel;
  59285. var centerIndex = (N - 1) / 2;
  59286. // Generate Gaussian sampling weights over kernel
  59287. var offsets = [];
  59288. var weights = [];
  59289. var totalWeight = 0;
  59290. for (var i = 0; i < N; i++) {
  59291. var u = i / (N - 1);
  59292. var w = this._gaussianWeight(u * 2.0 - 1);
  59293. offsets[i] = (i - centerIndex);
  59294. weights[i] = w;
  59295. totalWeight += w;
  59296. }
  59297. // Normalize weights
  59298. for (var i = 0; i < weights.length; i++) {
  59299. weights[i] /= totalWeight;
  59300. }
  59301. // Optimize: combine samples to take advantage of hardware linear sampling
  59302. // Walk from left to center, combining pairs (symmetrically)
  59303. var linearSamplingWeights = [];
  59304. var linearSamplingOffsets = [];
  59305. var linearSamplingMap = [];
  59306. for (var i = 0; i <= centerIndex; i += 2) {
  59307. var j = Math.min(i + 1, Math.floor(centerIndex));
  59308. var singleCenterSample = i === j;
  59309. if (singleCenterSample) {
  59310. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  59311. }
  59312. else {
  59313. var sharedCell = j === centerIndex;
  59314. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  59315. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  59316. if (offsetLinear === 0) {
  59317. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  59318. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  59319. }
  59320. else {
  59321. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  59322. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  59323. }
  59324. }
  59325. }
  59326. for (var i = 0; i < linearSamplingMap.length; i++) {
  59327. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  59328. linearSamplingWeights[i] = linearSamplingMap[i].w;
  59329. }
  59330. // Replace with optimized
  59331. offsets = linearSamplingOffsets;
  59332. weights = linearSamplingWeights;
  59333. // Generate shaders
  59334. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  59335. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  59336. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  59337. var defines = "";
  59338. for (var i = 0; i < varyingCount; i++) {
  59339. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  59340. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  59341. }
  59342. var depCount = 0;
  59343. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  59344. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  59345. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  59346. depCount++;
  59347. }
  59348. if (this.packedFloat) {
  59349. defines += "#define PACKEDFLOAT 1";
  59350. }
  59351. this.updateEffect(defines, null, null, {
  59352. varyingCount: varyingCount,
  59353. depCount: depCount
  59354. });
  59355. };
  59356. /**
  59357. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  59358. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  59359. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  59360. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  59361. * The gaps between physical kernels are compensated for in the weighting of the samples
  59362. * @param idealKernel Ideal blur kernel.
  59363. * @return Nearest best kernel.
  59364. */
  59365. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  59366. var v = Math.round(idealKernel);
  59367. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  59368. var k = _a[_i];
  59369. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  59370. return Math.max(k, 3);
  59371. }
  59372. }
  59373. return Math.max(v, 3);
  59374. };
  59375. /**
  59376. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  59377. * @param x The point on the Gaussian distribution to sample.
  59378. * @return the value of the Gaussian function at x.
  59379. */
  59380. BlurPostProcess.prototype._gaussianWeight = function (x) {
  59381. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  59382. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  59383. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  59384. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  59385. // truncated at around 1.3% of peak strength.
  59386. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  59387. var sigma = (1 / 3);
  59388. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  59389. var exponent = -((x * x) / (2.0 * sigma * sigma));
  59390. var weight = (1.0 / denominator) * Math.exp(exponent);
  59391. return weight;
  59392. };
  59393. /**
  59394. * Generates a string that can be used as a floating point number in GLSL.
  59395. * @param x Value to print.
  59396. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  59397. * @return GLSL float string.
  59398. */
  59399. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  59400. if (decimalFigures === void 0) { decimalFigures = 8; }
  59401. return x.toFixed(decimalFigures).replace(/0+$/, '');
  59402. };
  59403. return BlurPostProcess;
  59404. }(BABYLON.PostProcess));
  59405. BABYLON.BlurPostProcess = BlurPostProcess;
  59406. })(BABYLON || (BABYLON = {}));
  59407. //# sourceMappingURL=babylon.blurPostProcess.js.map
  59408. /// <reference path="..\babylon.node.ts" />
  59409. var BABYLON;
  59410. (function (BABYLON) {
  59411. var Bone = /** @class */ (function (_super) {
  59412. __extends(Bone, _super);
  59413. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  59414. if (parentBone === void 0) { parentBone = null; }
  59415. if (localMatrix === void 0) { localMatrix = null; }
  59416. if (restPose === void 0) { restPose = null; }
  59417. if (baseMatrix === void 0) { baseMatrix = null; }
  59418. if (index === void 0) { index = null; }
  59419. var _this = _super.call(this, name, skeleton.getScene()) || this;
  59420. _this.name = name;
  59421. _this.children = new Array();
  59422. _this.animations = new Array();
  59423. // Set this value to map this bone to a different index in the transform matrices.
  59424. // Set this value to -1 to exclude the bone from the transform matrices.
  59425. _this._index = null;
  59426. _this._worldTransform = new BABYLON.Matrix();
  59427. _this._absoluteTransform = new BABYLON.Matrix();
  59428. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  59429. _this._scaleMatrix = BABYLON.Matrix.Identity();
  59430. _this._scaleVector = BABYLON.Vector3.One();
  59431. _this._negateScaleChildren = BABYLON.Vector3.One();
  59432. _this._scalingDeterminant = 1;
  59433. _this._skeleton = skeleton;
  59434. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  59435. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  59436. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  59437. _this._index = index;
  59438. skeleton.bones.push(_this);
  59439. _this.setParent(parentBone, false);
  59440. _this._updateDifferenceMatrix();
  59441. return _this;
  59442. }
  59443. Object.defineProperty(Bone.prototype, "_matrix", {
  59444. get: function () {
  59445. return this._localMatrix;
  59446. },
  59447. set: function (val) {
  59448. if (this._localMatrix) {
  59449. this._localMatrix.copyFrom(val);
  59450. }
  59451. else {
  59452. this._localMatrix = val;
  59453. }
  59454. },
  59455. enumerable: true,
  59456. configurable: true
  59457. });
  59458. // Members
  59459. Bone.prototype.getSkeleton = function () {
  59460. return this._skeleton;
  59461. };
  59462. Bone.prototype.getParent = function () {
  59463. return this._parent;
  59464. };
  59465. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  59466. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  59467. if (this._parent === parent) {
  59468. return;
  59469. }
  59470. if (this._parent) {
  59471. var index = this._parent.children.indexOf(this);
  59472. if (index !== -1) {
  59473. this._parent.children.splice(index);
  59474. }
  59475. }
  59476. this._parent = parent;
  59477. if (this._parent) {
  59478. this._parent.children.push(this);
  59479. }
  59480. if (updateDifferenceMatrix) {
  59481. this._updateDifferenceMatrix();
  59482. }
  59483. };
  59484. Bone.prototype.getLocalMatrix = function () {
  59485. return this._localMatrix;
  59486. };
  59487. Bone.prototype.getBaseMatrix = function () {
  59488. return this._baseMatrix;
  59489. };
  59490. Bone.prototype.getRestPose = function () {
  59491. return this._restPose;
  59492. };
  59493. Bone.prototype.returnToRest = function () {
  59494. this.updateMatrix(this._restPose.clone());
  59495. };
  59496. Bone.prototype.getWorldMatrix = function () {
  59497. return this._worldTransform;
  59498. };
  59499. Bone.prototype.getInvertedAbsoluteTransform = function () {
  59500. return this._invertedAbsoluteTransform;
  59501. };
  59502. Bone.prototype.getAbsoluteTransform = function () {
  59503. return this._absoluteTransform;
  59504. };
  59505. Object.defineProperty(Bone.prototype, "position", {
  59506. // Properties (matches AbstractMesh properties)
  59507. get: function () {
  59508. return this.getPosition();
  59509. },
  59510. set: function (newPosition) {
  59511. this.setPosition(newPosition);
  59512. },
  59513. enumerable: true,
  59514. configurable: true
  59515. });
  59516. Object.defineProperty(Bone.prototype, "rotation", {
  59517. get: function () {
  59518. return this.getRotation();
  59519. },
  59520. set: function (newRotation) {
  59521. this.setRotation(newRotation);
  59522. },
  59523. enumerable: true,
  59524. configurable: true
  59525. });
  59526. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  59527. get: function () {
  59528. return this.getRotationQuaternion();
  59529. },
  59530. set: function (newRotation) {
  59531. this.setRotationQuaternion(newRotation);
  59532. },
  59533. enumerable: true,
  59534. configurable: true
  59535. });
  59536. Object.defineProperty(Bone.prototype, "scaling", {
  59537. get: function () {
  59538. return this.getScale();
  59539. },
  59540. set: function (newScaling) {
  59541. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  59542. },
  59543. enumerable: true,
  59544. configurable: true
  59545. });
  59546. // Methods
  59547. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  59548. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  59549. this._baseMatrix = matrix.clone();
  59550. this._localMatrix = matrix.clone();
  59551. this._skeleton._markAsDirty();
  59552. if (updateDifferenceMatrix) {
  59553. this._updateDifferenceMatrix();
  59554. }
  59555. };
  59556. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  59557. if (!rootMatrix) {
  59558. rootMatrix = this._baseMatrix;
  59559. }
  59560. if (this._parent) {
  59561. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  59562. }
  59563. else {
  59564. this._absoluteTransform.copyFrom(rootMatrix);
  59565. }
  59566. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  59567. for (var index = 0; index < this.children.length; index++) {
  59568. this.children[index]._updateDifferenceMatrix();
  59569. }
  59570. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  59571. };
  59572. Bone.prototype.markAsDirty = function () {
  59573. this._currentRenderId++;
  59574. this._skeleton._markAsDirty();
  59575. };
  59576. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  59577. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  59578. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  59579. // all animation may be coming from a library skeleton, so may need to create animation
  59580. if (this.animations.length === 0) {
  59581. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  59582. this.animations[0].setKeys([]);
  59583. }
  59584. // get animation info / verify there is such a range from the source bone
  59585. var sourceRange = source.animations[0].getRange(rangeName);
  59586. if (!sourceRange) {
  59587. return false;
  59588. }
  59589. var from = sourceRange.from;
  59590. var to = sourceRange.to;
  59591. var sourceKeys = source.animations[0].getKeys();
  59592. // rescaling prep
  59593. var sourceBoneLength = source.length;
  59594. var sourceParent = source.getParent();
  59595. var parent = this.getParent();
  59596. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  59597. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  59598. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  59599. var destKeys = this.animations[0].getKeys();
  59600. // loop vars declaration
  59601. var orig;
  59602. var origTranslation;
  59603. var mat;
  59604. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  59605. orig = sourceKeys[key];
  59606. if (orig.frame >= from && orig.frame <= to) {
  59607. if (rescaleAsRequired) {
  59608. mat = orig.value.clone();
  59609. // scale based on parent ratio, when bone has parent
  59610. if (parentScalingReqd) {
  59611. origTranslation = mat.getTranslation();
  59612. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  59613. // scale based on skeleton dimension ratio when root bone, and value is passed
  59614. }
  59615. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  59616. origTranslation = mat.getTranslation();
  59617. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  59618. // use original when root bone, and no data for skelDimensionsRatio
  59619. }
  59620. else {
  59621. mat = orig.value;
  59622. }
  59623. }
  59624. else {
  59625. mat = orig.value;
  59626. }
  59627. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  59628. }
  59629. }
  59630. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  59631. return true;
  59632. };
  59633. /**
  59634. * Translate the bone in local or world space.
  59635. * @param vec The amount to translate the bone.
  59636. * @param space The space that the translation is in.
  59637. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59638. */
  59639. Bone.prototype.translate = function (vec, space, mesh) {
  59640. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59641. var lm = this.getLocalMatrix();
  59642. if (space == BABYLON.Space.LOCAL) {
  59643. lm.m[12] += vec.x;
  59644. lm.m[13] += vec.y;
  59645. lm.m[14] += vec.z;
  59646. }
  59647. else {
  59648. var wm = null;
  59649. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  59650. if (mesh) {
  59651. wm = mesh.getWorldMatrix();
  59652. }
  59653. this._skeleton.computeAbsoluteTransforms();
  59654. var tmat = Bone._tmpMats[0];
  59655. var tvec = Bone._tmpVecs[0];
  59656. if (this._parent) {
  59657. if (mesh && wm) {
  59658. tmat.copyFrom(this._parent.getAbsoluteTransform());
  59659. tmat.multiplyToRef(wm, tmat);
  59660. }
  59661. else {
  59662. tmat.copyFrom(this._parent.getAbsoluteTransform());
  59663. }
  59664. }
  59665. tmat.m[12] = 0;
  59666. tmat.m[13] = 0;
  59667. tmat.m[14] = 0;
  59668. tmat.invert();
  59669. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  59670. lm.m[12] += tvec.x;
  59671. lm.m[13] += tvec.y;
  59672. lm.m[14] += tvec.z;
  59673. }
  59674. this.markAsDirty();
  59675. };
  59676. /**
  59677. * Set the postion of the bone in local or world space.
  59678. * @param position The position to set the bone.
  59679. * @param space The space that the position is in.
  59680. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59681. */
  59682. Bone.prototype.setPosition = function (position, space, mesh) {
  59683. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59684. var lm = this.getLocalMatrix();
  59685. if (space == BABYLON.Space.LOCAL) {
  59686. lm.m[12] = position.x;
  59687. lm.m[13] = position.y;
  59688. lm.m[14] = position.z;
  59689. }
  59690. else {
  59691. var wm = null;
  59692. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  59693. if (mesh) {
  59694. wm = mesh.getWorldMatrix();
  59695. }
  59696. this._skeleton.computeAbsoluteTransforms();
  59697. var tmat = Bone._tmpMats[0];
  59698. var vec = Bone._tmpVecs[0];
  59699. if (this._parent) {
  59700. if (mesh && wm) {
  59701. tmat.copyFrom(this._parent.getAbsoluteTransform());
  59702. tmat.multiplyToRef(wm, tmat);
  59703. }
  59704. else {
  59705. tmat.copyFrom(this._parent.getAbsoluteTransform());
  59706. }
  59707. }
  59708. tmat.invert();
  59709. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  59710. lm.m[12] = vec.x;
  59711. lm.m[13] = vec.y;
  59712. lm.m[14] = vec.z;
  59713. }
  59714. this.markAsDirty();
  59715. };
  59716. /**
  59717. * Set the absolute postion of the bone (world space).
  59718. * @param position The position to set the bone.
  59719. * @param mesh The mesh that this bone is attached to.
  59720. */
  59721. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  59722. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  59723. };
  59724. /**
  59725. * Set the scale of the bone on the x, y and z axes.
  59726. * @param x The scale of the bone on the x axis.
  59727. * @param x The scale of the bone on the y axis.
  59728. * @param z The scale of the bone on the z axis.
  59729. * @param scaleChildren Set this to true if children of the bone should be scaled.
  59730. */
  59731. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  59732. if (scaleChildren === void 0) { scaleChildren = false; }
  59733. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  59734. if (!scaleChildren) {
  59735. this._negateScaleChildren.x = 1 / x;
  59736. this._negateScaleChildren.y = 1 / y;
  59737. this._negateScaleChildren.z = 1 / z;
  59738. }
  59739. this._syncScaleVector();
  59740. }
  59741. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  59742. };
  59743. /**
  59744. * Scale the bone on the x, y and z axes.
  59745. * @param x The amount to scale the bone on the x axis.
  59746. * @param x The amount to scale the bone on the y axis.
  59747. * @param z The amount to scale the bone on the z axis.
  59748. * @param scaleChildren Set this to true if children of the bone should be scaled.
  59749. */
  59750. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  59751. if (scaleChildren === void 0) { scaleChildren = false; }
  59752. var locMat = this.getLocalMatrix();
  59753. var origLocMat = Bone._tmpMats[0];
  59754. origLocMat.copyFrom(locMat);
  59755. var origLocMatInv = Bone._tmpMats[1];
  59756. origLocMatInv.copyFrom(origLocMat);
  59757. origLocMatInv.invert();
  59758. var scaleMat = Bone._tmpMats[2];
  59759. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  59760. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  59761. this._scaleVector.x *= x;
  59762. this._scaleVector.y *= y;
  59763. this._scaleVector.z *= z;
  59764. locMat.multiplyToRef(origLocMatInv, locMat);
  59765. locMat.multiplyToRef(scaleMat, locMat);
  59766. locMat.multiplyToRef(origLocMat, locMat);
  59767. var parent = this.getParent();
  59768. if (parent) {
  59769. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  59770. }
  59771. else {
  59772. this.getAbsoluteTransform().copyFrom(locMat);
  59773. }
  59774. var len = this.children.length;
  59775. scaleMat.invert();
  59776. for (var i = 0; i < len; i++) {
  59777. var child = this.children[i];
  59778. var cm = child.getLocalMatrix();
  59779. cm.multiplyToRef(scaleMat, cm);
  59780. var lm = child.getLocalMatrix();
  59781. lm.m[12] *= x;
  59782. lm.m[13] *= y;
  59783. lm.m[14] *= z;
  59784. }
  59785. this.computeAbsoluteTransforms();
  59786. if (scaleChildren) {
  59787. for (var i = 0; i < len; i++) {
  59788. this.children[i].scale(x, y, z, scaleChildren);
  59789. }
  59790. }
  59791. this.markAsDirty();
  59792. };
  59793. /**
  59794. * Set the yaw, pitch, and roll of the bone in local or world space.
  59795. * @param yaw The rotation of the bone on the y axis.
  59796. * @param pitch The rotation of the bone on the x axis.
  59797. * @param roll The rotation of the bone on the z axis.
  59798. * @param space The space that the axes of rotation are in.
  59799. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59800. */
  59801. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  59802. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59803. var rotMat = Bone._tmpMats[0];
  59804. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  59805. var rotMatInv = Bone._tmpMats[1];
  59806. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  59807. rotMatInv.multiplyToRef(rotMat, rotMat);
  59808. this._rotateWithMatrix(rotMat, space, mesh);
  59809. };
  59810. /**
  59811. * Rotate the bone on an axis in local or world space.
  59812. * @param axis The axis to rotate the bone on.
  59813. * @param amount The amount to rotate the bone.
  59814. * @param space The space that the axis is in.
  59815. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59816. */
  59817. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  59818. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59819. var rmat = Bone._tmpMats[0];
  59820. rmat.m[12] = 0;
  59821. rmat.m[13] = 0;
  59822. rmat.m[14] = 0;
  59823. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  59824. this._rotateWithMatrix(rmat, space, mesh);
  59825. };
  59826. /**
  59827. * Set the rotation of the bone to a particular axis angle in local or world space.
  59828. * @param axis The axis to rotate the bone on.
  59829. * @param angle The angle that the bone should be rotated to.
  59830. * @param space The space that the axis is in.
  59831. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59832. */
  59833. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  59834. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59835. var rotMat = Bone._tmpMats[0];
  59836. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  59837. var rotMatInv = Bone._tmpMats[1];
  59838. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  59839. rotMatInv.multiplyToRef(rotMat, rotMat);
  59840. this._rotateWithMatrix(rotMat, space, mesh);
  59841. };
  59842. /**
  59843. * Set the euler rotation of the bone in local of world space.
  59844. * @param rotation The euler rotation that the bone should be set to.
  59845. * @param space The space that the rotation is in.
  59846. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59847. */
  59848. Bone.prototype.setRotation = function (rotation, space, mesh) {
  59849. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59850. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  59851. };
  59852. /**
  59853. * Set the quaternion rotation of the bone in local of world space.
  59854. * @param quat The quaternion rotation that the bone should be set to.
  59855. * @param space The space that the rotation is in.
  59856. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59857. */
  59858. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  59859. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59860. var rotMatInv = Bone._tmpMats[0];
  59861. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  59862. var rotMat = Bone._tmpMats[1];
  59863. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  59864. rotMatInv.multiplyToRef(rotMat, rotMat);
  59865. this._rotateWithMatrix(rotMat, space, mesh);
  59866. };
  59867. /**
  59868. * Set the rotation matrix of the bone in local of world space.
  59869. * @param rotMat The rotation matrix that the bone should be set to.
  59870. * @param space The space that the rotation is in.
  59871. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59872. */
  59873. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  59874. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59875. var rotMatInv = Bone._tmpMats[0];
  59876. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  59877. var rotMat2 = Bone._tmpMats[1];
  59878. rotMat2.copyFrom(rotMat);
  59879. rotMatInv.multiplyToRef(rotMat, rotMat2);
  59880. this._rotateWithMatrix(rotMat2, space, mesh);
  59881. };
  59882. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  59883. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59884. var lmat = this.getLocalMatrix();
  59885. var lx = lmat.m[12];
  59886. var ly = lmat.m[13];
  59887. var lz = lmat.m[14];
  59888. var parent = this.getParent();
  59889. var parentScale = Bone._tmpMats[3];
  59890. var parentScaleInv = Bone._tmpMats[4];
  59891. if (parent) {
  59892. if (space == BABYLON.Space.WORLD) {
  59893. if (mesh) {
  59894. parentScale.copyFrom(mesh.getWorldMatrix());
  59895. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  59896. }
  59897. else {
  59898. parentScale.copyFrom(parent.getAbsoluteTransform());
  59899. }
  59900. }
  59901. else {
  59902. parentScale = parent._scaleMatrix;
  59903. }
  59904. parentScaleInv.copyFrom(parentScale);
  59905. parentScaleInv.invert();
  59906. lmat.multiplyToRef(parentScale, lmat);
  59907. lmat.multiplyToRef(rmat, lmat);
  59908. lmat.multiplyToRef(parentScaleInv, lmat);
  59909. }
  59910. else {
  59911. if (space == BABYLON.Space.WORLD && mesh) {
  59912. parentScale.copyFrom(mesh.getWorldMatrix());
  59913. parentScaleInv.copyFrom(parentScale);
  59914. parentScaleInv.invert();
  59915. lmat.multiplyToRef(parentScale, lmat);
  59916. lmat.multiplyToRef(rmat, lmat);
  59917. lmat.multiplyToRef(parentScaleInv, lmat);
  59918. }
  59919. else {
  59920. lmat.multiplyToRef(rmat, lmat);
  59921. }
  59922. }
  59923. lmat.m[12] = lx;
  59924. lmat.m[13] = ly;
  59925. lmat.m[14] = lz;
  59926. this.computeAbsoluteTransforms();
  59927. this.markAsDirty();
  59928. };
  59929. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  59930. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59931. if (space == BABYLON.Space.WORLD) {
  59932. var scaleMatrix = Bone._tmpMats[2];
  59933. scaleMatrix.copyFrom(this._scaleMatrix);
  59934. rotMatInv.copyFrom(this.getAbsoluteTransform());
  59935. if (mesh) {
  59936. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  59937. var meshScale = Bone._tmpMats[3];
  59938. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  59939. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  59940. }
  59941. rotMatInv.invert();
  59942. scaleMatrix.m[0] *= this._scalingDeterminant;
  59943. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  59944. }
  59945. else {
  59946. rotMatInv.copyFrom(this.getLocalMatrix());
  59947. rotMatInv.invert();
  59948. var scaleMatrix = Bone._tmpMats[2];
  59949. scaleMatrix.copyFrom(this._scaleMatrix);
  59950. if (this._parent) {
  59951. var pscaleMatrix = Bone._tmpMats[3];
  59952. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  59953. pscaleMatrix.invert();
  59954. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  59955. }
  59956. else {
  59957. scaleMatrix.m[0] *= this._scalingDeterminant;
  59958. }
  59959. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  59960. }
  59961. };
  59962. /**
  59963. * Get the scale of the bone
  59964. * @returns the scale of the bone
  59965. */
  59966. Bone.prototype.getScale = function () {
  59967. return this._scaleVector.clone();
  59968. };
  59969. /**
  59970. * Copy the scale of the bone to a vector3.
  59971. * @param result The vector3 to copy the scale to
  59972. */
  59973. Bone.prototype.getScaleToRef = function (result) {
  59974. result.copyFrom(this._scaleVector);
  59975. };
  59976. /**
  59977. * Get the position of the bone in local or world space.
  59978. * @param space The space that the returned position is in.
  59979. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59980. * @returns The position of the bone
  59981. */
  59982. Bone.prototype.getPosition = function (space, mesh) {
  59983. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59984. if (mesh === void 0) { mesh = null; }
  59985. var pos = BABYLON.Vector3.Zero();
  59986. this.getPositionToRef(space, mesh, pos);
  59987. return pos;
  59988. };
  59989. /**
  59990. * Copy the position of the bone to a vector3 in local or world space.
  59991. * @param space The space that the returned position is in.
  59992. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59993. * @param result The vector3 to copy the position to.
  59994. */
  59995. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  59996. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59997. if (space == BABYLON.Space.LOCAL) {
  59998. var lm = this.getLocalMatrix();
  59999. result.x = lm.m[12];
  60000. result.y = lm.m[13];
  60001. result.z = lm.m[14];
  60002. }
  60003. else {
  60004. var wm = null;
  60005. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60006. if (mesh) {
  60007. wm = mesh.getWorldMatrix();
  60008. }
  60009. this._skeleton.computeAbsoluteTransforms();
  60010. var tmat = Bone._tmpMats[0];
  60011. if (mesh && wm) {
  60012. tmat.copyFrom(this.getAbsoluteTransform());
  60013. tmat.multiplyToRef(wm, tmat);
  60014. }
  60015. else {
  60016. tmat = this.getAbsoluteTransform();
  60017. }
  60018. result.x = tmat.m[12];
  60019. result.y = tmat.m[13];
  60020. result.z = tmat.m[14];
  60021. }
  60022. };
  60023. /**
  60024. * Get the absolute position of the bone (world space).
  60025. * @param mesh The mesh that this bone is attached to.
  60026. * @returns The absolute position of the bone
  60027. */
  60028. Bone.prototype.getAbsolutePosition = function (mesh) {
  60029. if (mesh === void 0) { mesh = null; }
  60030. var pos = BABYLON.Vector3.Zero();
  60031. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  60032. return pos;
  60033. };
  60034. /**
  60035. * Copy the absolute position of the bone (world space) to the result param.
  60036. * @param mesh The mesh that this bone is attached to.
  60037. * @param result The vector3 to copy the absolute position to.
  60038. */
  60039. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  60040. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  60041. };
  60042. /**
  60043. * Compute the absolute transforms of this bone and its children.
  60044. */
  60045. Bone.prototype.computeAbsoluteTransforms = function () {
  60046. if (this._parent) {
  60047. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  60048. }
  60049. else {
  60050. this._absoluteTransform.copyFrom(this._localMatrix);
  60051. var poseMatrix = this._skeleton.getPoseMatrix();
  60052. if (poseMatrix) {
  60053. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  60054. }
  60055. }
  60056. var children = this.children;
  60057. var len = children.length;
  60058. for (var i = 0; i < len; i++) {
  60059. children[i].computeAbsoluteTransforms();
  60060. }
  60061. };
  60062. Bone.prototype._syncScaleVector = function () {
  60063. var lm = this.getLocalMatrix();
  60064. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  60065. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  60066. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  60067. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  60068. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  60069. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  60070. this._scaleVector.x = xs * Math.sqrt(xsq);
  60071. this._scaleVector.y = ys * Math.sqrt(ysq);
  60072. this._scaleVector.z = zs * Math.sqrt(zsq);
  60073. if (this._parent) {
  60074. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  60075. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  60076. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  60077. }
  60078. 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);
  60079. };
  60080. /**
  60081. * Get the world direction from an axis that is in the local space of the bone.
  60082. * @param localAxis The local direction that is used to compute the world direction.
  60083. * @param mesh The mesh that this bone is attached to.
  60084. * @returns The world direction
  60085. */
  60086. Bone.prototype.getDirection = function (localAxis, mesh) {
  60087. if (mesh === void 0) { mesh = null; }
  60088. var result = BABYLON.Vector3.Zero();
  60089. this.getDirectionToRef(localAxis, mesh, result);
  60090. return result;
  60091. };
  60092. /**
  60093. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  60094. * @param localAxis The local direction that is used to compute the world direction.
  60095. * @param mesh The mesh that this bone is attached to.
  60096. * @param result The vector3 that the world direction will be copied to.
  60097. */
  60098. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  60099. if (mesh === void 0) { mesh = null; }
  60100. var wm = null;
  60101. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60102. if (mesh) {
  60103. wm = mesh.getWorldMatrix();
  60104. }
  60105. this._skeleton.computeAbsoluteTransforms();
  60106. var mat = Bone._tmpMats[0];
  60107. mat.copyFrom(this.getAbsoluteTransform());
  60108. if (mesh && wm) {
  60109. mat.multiplyToRef(wm, mat);
  60110. }
  60111. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  60112. result.normalize();
  60113. };
  60114. /**
  60115. * Get the euler rotation of the bone in local or world space.
  60116. * @param space The space that the rotation should be in.
  60117. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60118. * @returns The euler rotation
  60119. */
  60120. Bone.prototype.getRotation = function (space, mesh) {
  60121. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60122. if (mesh === void 0) { mesh = null; }
  60123. var result = BABYLON.Vector3.Zero();
  60124. this.getRotationToRef(space, mesh, result);
  60125. return result;
  60126. };
  60127. /**
  60128. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  60129. * @param space The space that the rotation should be in.
  60130. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60131. * @param result The vector3 that the rotation should be copied to.
  60132. */
  60133. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  60134. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60135. if (mesh === void 0) { mesh = null; }
  60136. var quat = Bone._tmpQuat;
  60137. this.getRotationQuaternionToRef(space, mesh, quat);
  60138. quat.toEulerAnglesToRef(result);
  60139. };
  60140. /**
  60141. * Get the quaternion rotation of the bone in either local or world space.
  60142. * @param space The space that the rotation should be in.
  60143. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60144. * @returns The quaternion rotation
  60145. */
  60146. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  60147. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60148. if (mesh === void 0) { mesh = null; }
  60149. var result = BABYLON.Quaternion.Identity();
  60150. this.getRotationQuaternionToRef(space, mesh, result);
  60151. return result;
  60152. };
  60153. /**
  60154. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  60155. * @param space The space that the rotation should be in.
  60156. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60157. * @param result The quaternion that the rotation should be copied to.
  60158. */
  60159. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  60160. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60161. if (mesh === void 0) { mesh = null; }
  60162. if (space == BABYLON.Space.LOCAL) {
  60163. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  60164. }
  60165. else {
  60166. var mat = Bone._tmpMats[0];
  60167. var amat = this.getAbsoluteTransform();
  60168. if (mesh) {
  60169. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  60170. }
  60171. else {
  60172. mat.copyFrom(amat);
  60173. }
  60174. mat.m[0] *= this._scalingDeterminant;
  60175. mat.m[1] *= this._scalingDeterminant;
  60176. mat.m[2] *= this._scalingDeterminant;
  60177. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  60178. }
  60179. };
  60180. /**
  60181. * Get the rotation matrix of the bone in local or world space.
  60182. * @param space The space that the rotation should be in.
  60183. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60184. * @returns The rotation matrix
  60185. */
  60186. Bone.prototype.getRotationMatrix = function (space, mesh) {
  60187. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60188. var result = BABYLON.Matrix.Identity();
  60189. this.getRotationMatrixToRef(space, mesh, result);
  60190. return result;
  60191. };
  60192. /**
  60193. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  60194. * @param space The space that the rotation should be in.
  60195. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60196. * @param result The quaternion that the rotation should be copied to.
  60197. */
  60198. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  60199. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60200. if (space == BABYLON.Space.LOCAL) {
  60201. this.getLocalMatrix().getRotationMatrixToRef(result);
  60202. }
  60203. else {
  60204. var mat = Bone._tmpMats[0];
  60205. var amat = this.getAbsoluteTransform();
  60206. if (mesh) {
  60207. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  60208. }
  60209. else {
  60210. mat.copyFrom(amat);
  60211. }
  60212. mat.m[0] *= this._scalingDeterminant;
  60213. mat.m[1] *= this._scalingDeterminant;
  60214. mat.m[2] *= this._scalingDeterminant;
  60215. mat.getRotationMatrixToRef(result);
  60216. }
  60217. };
  60218. /**
  60219. * Get the world position of a point that is in the local space of the bone.
  60220. * @param position The local position
  60221. * @param mesh The mesh that this bone is attached to.
  60222. * @returns The world position
  60223. */
  60224. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  60225. if (mesh === void 0) { mesh = null; }
  60226. var result = BABYLON.Vector3.Zero();
  60227. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  60228. return result;
  60229. };
  60230. /**
  60231. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  60232. * @param position The local position
  60233. * @param mesh The mesh that this bone is attached to.
  60234. * @param result The vector3 that the world position should be copied to.
  60235. */
  60236. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  60237. if (mesh === void 0) { mesh = null; }
  60238. var wm = null;
  60239. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60240. if (mesh) {
  60241. wm = mesh.getWorldMatrix();
  60242. }
  60243. this._skeleton.computeAbsoluteTransforms();
  60244. var tmat = Bone._tmpMats[0];
  60245. if (mesh && wm) {
  60246. tmat.copyFrom(this.getAbsoluteTransform());
  60247. tmat.multiplyToRef(wm, tmat);
  60248. }
  60249. else {
  60250. tmat = this.getAbsoluteTransform();
  60251. }
  60252. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  60253. };
  60254. /**
  60255. * Get the local position of a point that is in world space.
  60256. * @param position The world position
  60257. * @param mesh The mesh that this bone is attached to.
  60258. * @returns The local position
  60259. */
  60260. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  60261. if (mesh === void 0) { mesh = null; }
  60262. var result = BABYLON.Vector3.Zero();
  60263. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  60264. return result;
  60265. };
  60266. /**
  60267. * Get the local position of a point that is in world space and copy it to the result param.
  60268. * @param position The world position
  60269. * @param mesh The mesh that this bone is attached to.
  60270. * @param result The vector3 that the local position should be copied to.
  60271. */
  60272. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  60273. if (mesh === void 0) { mesh = null; }
  60274. var wm = null;
  60275. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60276. if (mesh) {
  60277. wm = mesh.getWorldMatrix();
  60278. }
  60279. this._skeleton.computeAbsoluteTransforms();
  60280. var tmat = Bone._tmpMats[0];
  60281. tmat.copyFrom(this.getAbsoluteTransform());
  60282. if (mesh && wm) {
  60283. tmat.multiplyToRef(wm, tmat);
  60284. }
  60285. tmat.invert();
  60286. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  60287. };
  60288. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60289. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  60290. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  60291. return Bone;
  60292. }(BABYLON.Node));
  60293. BABYLON.Bone = Bone;
  60294. })(BABYLON || (BABYLON = {}));
  60295. //# sourceMappingURL=babylon.bone.js.map
  60296. var BABYLON;
  60297. (function (BABYLON) {
  60298. var BoneIKController = /** @class */ (function () {
  60299. function BoneIKController(mesh, bone, options) {
  60300. this.targetPosition = BABYLON.Vector3.Zero();
  60301. this.poleTargetPosition = BABYLON.Vector3.Zero();
  60302. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  60303. this.poleAngle = 0;
  60304. this.slerpAmount = 1;
  60305. this._bone1Quat = BABYLON.Quaternion.Identity();
  60306. this._bone1Mat = BABYLON.Matrix.Identity();
  60307. this._bone2Ang = Math.PI;
  60308. this._maxAngle = Math.PI;
  60309. this._rightHandedSystem = false;
  60310. this._bendAxis = BABYLON.Vector3.Right();
  60311. this._slerping = false;
  60312. this._adjustRoll = 0;
  60313. this._bone2 = bone;
  60314. this._bone1 = bone.getParent();
  60315. if (!this._bone1) {
  60316. return;
  60317. }
  60318. this.mesh = mesh;
  60319. var bonePos = bone.getPosition();
  60320. if (bone.getAbsoluteTransform().determinant() > 0) {
  60321. this._rightHandedSystem = true;
  60322. this._bendAxis.x = 0;
  60323. this._bendAxis.y = 0;
  60324. this._bendAxis.z = -1;
  60325. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  60326. this._adjustRoll = Math.PI * .5;
  60327. this._bendAxis.z = 1;
  60328. }
  60329. }
  60330. if (this._bone1.length) {
  60331. var boneScale1 = this._bone1.getScale();
  60332. var boneScale2 = this._bone2.getScale();
  60333. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  60334. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  60335. }
  60336. else if (this._bone1.children[0]) {
  60337. mesh.computeWorldMatrix(true);
  60338. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  60339. var pos2 = this._bone2.getAbsolutePosition(mesh);
  60340. var pos3 = this._bone1.getAbsolutePosition(mesh);
  60341. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  60342. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  60343. }
  60344. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  60345. this.maxAngle = Math.PI;
  60346. if (options) {
  60347. if (options.targetMesh) {
  60348. this.targetMesh = options.targetMesh;
  60349. this.targetMesh.computeWorldMatrix(true);
  60350. }
  60351. if (options.poleTargetMesh) {
  60352. this.poleTargetMesh = options.poleTargetMesh;
  60353. this.poleTargetMesh.computeWorldMatrix(true);
  60354. }
  60355. else if (options.poleTargetBone) {
  60356. this.poleTargetBone = options.poleTargetBone;
  60357. }
  60358. else if (this._bone1.getParent()) {
  60359. this.poleTargetBone = this._bone1.getParent();
  60360. }
  60361. if (options.poleTargetLocalOffset) {
  60362. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  60363. }
  60364. if (options.poleAngle) {
  60365. this.poleAngle = options.poleAngle;
  60366. }
  60367. if (options.bendAxis) {
  60368. this._bendAxis.copyFrom(options.bendAxis);
  60369. }
  60370. if (options.maxAngle) {
  60371. this.maxAngle = options.maxAngle;
  60372. }
  60373. if (options.slerpAmount) {
  60374. this.slerpAmount = options.slerpAmount;
  60375. }
  60376. }
  60377. }
  60378. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  60379. get: function () {
  60380. return this._maxAngle;
  60381. },
  60382. set: function (value) {
  60383. this._setMaxAngle(value);
  60384. },
  60385. enumerable: true,
  60386. configurable: true
  60387. });
  60388. BoneIKController.prototype._setMaxAngle = function (ang) {
  60389. if (ang < 0) {
  60390. ang = 0;
  60391. }
  60392. if (ang > Math.PI || ang == undefined) {
  60393. ang = Math.PI;
  60394. }
  60395. this._maxAngle = ang;
  60396. var a = this._bone1Length;
  60397. var b = this._bone2Length;
  60398. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  60399. };
  60400. BoneIKController.prototype.update = function () {
  60401. var bone1 = this._bone1;
  60402. if (!bone1) {
  60403. return;
  60404. }
  60405. var target = this.targetPosition;
  60406. var poleTarget = this.poleTargetPosition;
  60407. var mat1 = BoneIKController._tmpMats[0];
  60408. var mat2 = BoneIKController._tmpMats[1];
  60409. if (this.targetMesh) {
  60410. target.copyFrom(this.targetMesh.getAbsolutePosition());
  60411. }
  60412. if (this.poleTargetBone) {
  60413. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  60414. }
  60415. else if (this.poleTargetMesh) {
  60416. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  60417. }
  60418. var bonePos = BoneIKController._tmpVecs[0];
  60419. var zaxis = BoneIKController._tmpVecs[1];
  60420. var xaxis = BoneIKController._tmpVecs[2];
  60421. var yaxis = BoneIKController._tmpVecs[3];
  60422. var upAxis = BoneIKController._tmpVecs[4];
  60423. var _tmpQuat = BoneIKController._tmpQuat;
  60424. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  60425. poleTarget.subtractToRef(bonePos, upAxis);
  60426. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  60427. upAxis.y = 1;
  60428. }
  60429. else {
  60430. upAxis.normalize();
  60431. }
  60432. target.subtractToRef(bonePos, yaxis);
  60433. yaxis.normalize();
  60434. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  60435. zaxis.normalize();
  60436. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  60437. xaxis.normalize();
  60438. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  60439. var a = this._bone1Length;
  60440. var b = this._bone2Length;
  60441. var c = BABYLON.Vector3.Distance(bonePos, target);
  60442. if (this._maxReach > 0) {
  60443. c = Math.min(this._maxReach, c);
  60444. }
  60445. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  60446. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  60447. if (acosa > 1) {
  60448. acosa = 1;
  60449. }
  60450. if (acosb > 1) {
  60451. acosb = 1;
  60452. }
  60453. if (acosa < -1) {
  60454. acosa = -1;
  60455. }
  60456. if (acosb < -1) {
  60457. acosb = -1;
  60458. }
  60459. var angA = Math.acos(acosa);
  60460. var angB = Math.acos(acosb);
  60461. var angC = -angA - angB;
  60462. if (this._rightHandedSystem) {
  60463. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  60464. mat2.multiplyToRef(mat1, mat1);
  60465. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  60466. mat2.multiplyToRef(mat1, mat1);
  60467. }
  60468. else {
  60469. var _tmpVec = BoneIKController._tmpVecs[5];
  60470. _tmpVec.copyFrom(this._bendAxis);
  60471. _tmpVec.x *= -1;
  60472. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  60473. mat2.multiplyToRef(mat1, mat1);
  60474. }
  60475. if (this.poleAngle) {
  60476. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  60477. mat1.multiplyToRef(mat2, mat1);
  60478. }
  60479. if (this._bone1) {
  60480. if (this.slerpAmount < 1) {
  60481. if (!this._slerping) {
  60482. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  60483. }
  60484. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  60485. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  60486. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  60487. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  60488. this._slerping = true;
  60489. }
  60490. else {
  60491. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  60492. this._bone1Mat.copyFrom(mat1);
  60493. this._slerping = false;
  60494. }
  60495. }
  60496. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  60497. this._bone2Ang = angC;
  60498. };
  60499. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60500. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  60501. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  60502. return BoneIKController;
  60503. }());
  60504. BABYLON.BoneIKController = BoneIKController;
  60505. })(BABYLON || (BABYLON = {}));
  60506. //# sourceMappingURL=babylon.boneIKController.js.map
  60507. var BABYLON;
  60508. (function (BABYLON) {
  60509. var BoneLookController = /** @class */ (function () {
  60510. /**
  60511. * Create a BoneLookController
  60512. * @param mesh the mesh that the bone belongs to
  60513. * @param bone the bone that will be looking to the target
  60514. * @param target the target Vector3 to look at
  60515. * @param settings optional settings:
  60516. * - maxYaw: the maximum angle the bone will yaw to
  60517. * - minYaw: the minimum angle the bone will yaw to
  60518. * - maxPitch: the maximum angle the bone will pitch to
  60519. * - minPitch: the minimum angle the bone will yaw to
  60520. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  60521. * - upAxis: the up axis of the coordinate system
  60522. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  60523. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  60524. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  60525. * - adjustYaw: used to make an adjustment to the yaw of the bone
  60526. * - adjustPitch: used to make an adjustment to the pitch of the bone
  60527. * - adjustRoll: used to make an adjustment to the roll of the bone
  60528. **/
  60529. function BoneLookController(mesh, bone, target, options) {
  60530. /**
  60531. * The up axis of the coordinate system that is used when the bone is rotated.
  60532. */
  60533. this.upAxis = BABYLON.Vector3.Up();
  60534. /**
  60535. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  60536. */
  60537. this.upAxisSpace = BABYLON.Space.LOCAL;
  60538. /**
  60539. * Used to make an adjustment to the yaw of the bone.
  60540. */
  60541. this.adjustYaw = 0;
  60542. /**
  60543. * Used to make an adjustment to the pitch of the bone.
  60544. */
  60545. this.adjustPitch = 0;
  60546. /**
  60547. * Used to make an adjustment to the roll of the bone.
  60548. */
  60549. this.adjustRoll = 0;
  60550. /**
  60551. * 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).
  60552. */
  60553. this.slerpAmount = 1;
  60554. this._boneQuat = BABYLON.Quaternion.Identity();
  60555. this._slerping = false;
  60556. this._firstFrameSkipped = false;
  60557. this._fowardAxis = BABYLON.Vector3.Forward();
  60558. this.mesh = mesh;
  60559. this.bone = bone;
  60560. this.target = target;
  60561. if (options) {
  60562. if (options.adjustYaw) {
  60563. this.adjustYaw = options.adjustYaw;
  60564. }
  60565. if (options.adjustPitch) {
  60566. this.adjustPitch = options.adjustPitch;
  60567. }
  60568. if (options.adjustRoll) {
  60569. this.adjustRoll = options.adjustRoll;
  60570. }
  60571. if (options.maxYaw != null) {
  60572. this.maxYaw = options.maxYaw;
  60573. }
  60574. else {
  60575. this.maxYaw = Math.PI;
  60576. }
  60577. if (options.minYaw != null) {
  60578. this.minYaw = options.minYaw;
  60579. }
  60580. else {
  60581. this.minYaw = -Math.PI;
  60582. }
  60583. if (options.maxPitch != null) {
  60584. this.maxPitch = options.maxPitch;
  60585. }
  60586. else {
  60587. this.maxPitch = Math.PI;
  60588. }
  60589. if (options.minPitch != null) {
  60590. this.minPitch = options.minPitch;
  60591. }
  60592. else {
  60593. this.minPitch = -Math.PI;
  60594. }
  60595. if (options.slerpAmount != null) {
  60596. this.slerpAmount = options.slerpAmount;
  60597. }
  60598. if (options.upAxis != null) {
  60599. this.upAxis = options.upAxis;
  60600. }
  60601. if (options.upAxisSpace != null) {
  60602. this.upAxisSpace = options.upAxisSpace;
  60603. }
  60604. if (options.yawAxis != null || options.pitchAxis != null) {
  60605. var newYawAxis = BABYLON.Axis.Y;
  60606. var newPitchAxis = BABYLON.Axis.X;
  60607. if (options.yawAxis != null) {
  60608. newYawAxis = options.yawAxis.clone();
  60609. newYawAxis.normalize();
  60610. }
  60611. if (options.pitchAxis != null) {
  60612. newPitchAxis = options.pitchAxis.clone();
  60613. newPitchAxis.normalize();
  60614. }
  60615. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  60616. this._transformYawPitch = BABYLON.Matrix.Identity();
  60617. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  60618. this._transformYawPitchInv = this._transformYawPitch.clone();
  60619. this._transformYawPitch.invert();
  60620. }
  60621. }
  60622. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  60623. this.upAxisSpace = BABYLON.Space.LOCAL;
  60624. }
  60625. }
  60626. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  60627. /**
  60628. * Get/set the minimum yaw angle that the bone can look to.
  60629. */
  60630. get: function () {
  60631. return this._minYaw;
  60632. },
  60633. set: function (value) {
  60634. this._minYaw = value;
  60635. this._minYawSin = Math.sin(value);
  60636. this._minYawCos = Math.cos(value);
  60637. if (this._maxYaw != null) {
  60638. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  60639. this._yawRange = this._maxYaw - this._minYaw;
  60640. }
  60641. },
  60642. enumerable: true,
  60643. configurable: true
  60644. });
  60645. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  60646. /**
  60647. * Get/set the maximum yaw angle that the bone can look to.
  60648. */
  60649. get: function () {
  60650. return this._maxYaw;
  60651. },
  60652. set: function (value) {
  60653. this._maxYaw = value;
  60654. this._maxYawSin = Math.sin(value);
  60655. this._maxYawCos = Math.cos(value);
  60656. if (this._minYaw != null) {
  60657. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  60658. this._yawRange = this._maxYaw - this._minYaw;
  60659. }
  60660. },
  60661. enumerable: true,
  60662. configurable: true
  60663. });
  60664. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  60665. /**
  60666. * Get/set the minimum pitch angle that the bone can look to.
  60667. */
  60668. get: function () {
  60669. return this._minPitch;
  60670. },
  60671. set: function (value) {
  60672. this._minPitch = value;
  60673. this._minPitchTan = Math.tan(value);
  60674. },
  60675. enumerable: true,
  60676. configurable: true
  60677. });
  60678. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  60679. /**
  60680. * Get/set the maximum pitch angle that the bone can look to.
  60681. */
  60682. get: function () {
  60683. return this._maxPitch;
  60684. },
  60685. set: function (value) {
  60686. this._maxPitch = value;
  60687. this._maxPitchTan = Math.tan(value);
  60688. },
  60689. enumerable: true,
  60690. configurable: true
  60691. });
  60692. /**
  60693. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  60694. */
  60695. BoneLookController.prototype.update = function () {
  60696. //skip the first frame when slerping so that the mesh rotation is correct
  60697. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  60698. this._firstFrameSkipped = true;
  60699. return;
  60700. }
  60701. var bone = this.bone;
  60702. var bonePos = BoneLookController._tmpVecs[0];
  60703. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  60704. var target = this.target;
  60705. var _tmpMat1 = BoneLookController._tmpMats[0];
  60706. var _tmpMat2 = BoneLookController._tmpMats[1];
  60707. var mesh = this.mesh;
  60708. var parentBone = bone.getParent();
  60709. var upAxis = BoneLookController._tmpVecs[1];
  60710. upAxis.copyFrom(this.upAxis);
  60711. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  60712. if (this._transformYawPitch) {
  60713. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  60714. }
  60715. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  60716. }
  60717. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  60718. mesh.getDirectionToRef(upAxis, upAxis);
  60719. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  60720. upAxis.normalize();
  60721. }
  60722. }
  60723. var checkYaw = false;
  60724. var checkPitch = false;
  60725. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  60726. checkYaw = true;
  60727. }
  60728. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  60729. checkPitch = true;
  60730. }
  60731. if (checkYaw || checkPitch) {
  60732. var spaceMat = BoneLookController._tmpMats[2];
  60733. var spaceMatInv = BoneLookController._tmpMats[3];
  60734. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  60735. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  60736. }
  60737. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  60738. spaceMat.copyFrom(mesh.getWorldMatrix());
  60739. }
  60740. else {
  60741. var forwardAxis = BoneLookController._tmpVecs[2];
  60742. forwardAxis.copyFrom(this._fowardAxis);
  60743. if (this._transformYawPitch) {
  60744. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  60745. }
  60746. if (parentBone) {
  60747. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  60748. }
  60749. else {
  60750. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  60751. }
  60752. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  60753. rightAxis.normalize();
  60754. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  60755. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  60756. }
  60757. spaceMat.invertToRef(spaceMatInv);
  60758. var xzlen = null;
  60759. if (checkPitch) {
  60760. var localTarget = BoneLookController._tmpVecs[3];
  60761. target.subtractToRef(bonePos, localTarget);
  60762. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  60763. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  60764. var pitch = Math.atan2(localTarget.y, xzlen);
  60765. var newPitch = pitch;
  60766. if (pitch > this._maxPitch) {
  60767. localTarget.y = this._maxPitchTan * xzlen;
  60768. newPitch = this._maxPitch;
  60769. }
  60770. else if (pitch < this._minPitch) {
  60771. localTarget.y = this._minPitchTan * xzlen;
  60772. newPitch = this._minPitch;
  60773. }
  60774. if (pitch != newPitch) {
  60775. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  60776. localTarget.addInPlace(bonePos);
  60777. target = localTarget;
  60778. }
  60779. }
  60780. if (checkYaw) {
  60781. var localTarget = BoneLookController._tmpVecs[4];
  60782. target.subtractToRef(bonePos, localTarget);
  60783. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  60784. var yaw = Math.atan2(localTarget.x, localTarget.z);
  60785. var newYaw = yaw;
  60786. if (yaw > this._maxYaw || yaw < this._minYaw) {
  60787. if (xzlen == null) {
  60788. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  60789. }
  60790. if (this._yawRange > Math.PI) {
  60791. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  60792. localTarget.z = this._maxYawCos * xzlen;
  60793. localTarget.x = this._maxYawSin * xzlen;
  60794. newYaw = this._maxYaw;
  60795. }
  60796. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  60797. localTarget.z = this._minYawCos * xzlen;
  60798. localTarget.x = this._minYawSin * xzlen;
  60799. newYaw = this._minYaw;
  60800. }
  60801. }
  60802. else {
  60803. if (yaw > this._maxYaw) {
  60804. localTarget.z = this._maxYawCos * xzlen;
  60805. localTarget.x = this._maxYawSin * xzlen;
  60806. newYaw = this._maxYaw;
  60807. }
  60808. else if (yaw < this._minYaw) {
  60809. localTarget.z = this._minYawCos * xzlen;
  60810. localTarget.x = this._minYawSin * xzlen;
  60811. newYaw = this._minYaw;
  60812. }
  60813. }
  60814. }
  60815. if (this._slerping && this._yawRange > Math.PI) {
  60816. //are we going to be crossing into the min/max region?
  60817. var boneFwd = BoneLookController._tmpVecs[8];
  60818. boneFwd.copyFrom(BABYLON.Axis.Z);
  60819. if (this._transformYawPitch) {
  60820. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  60821. }
  60822. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  60823. this._boneQuat.toRotationMatrix(boneRotMat);
  60824. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  60825. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  60826. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  60827. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  60828. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  60829. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  60830. if (angBtwTar > angBtwMidYaw) {
  60831. if (xzlen == null) {
  60832. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  60833. }
  60834. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  60835. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  60836. if (angBtwMin < angBtwMax) {
  60837. newYaw = boneYaw + Math.PI * .75;
  60838. localTarget.z = Math.cos(newYaw) * xzlen;
  60839. localTarget.x = Math.sin(newYaw) * xzlen;
  60840. }
  60841. else {
  60842. newYaw = boneYaw - Math.PI * .75;
  60843. localTarget.z = Math.cos(newYaw) * xzlen;
  60844. localTarget.x = Math.sin(newYaw) * xzlen;
  60845. }
  60846. }
  60847. }
  60848. if (yaw != newYaw) {
  60849. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  60850. localTarget.addInPlace(bonePos);
  60851. target = localTarget;
  60852. }
  60853. }
  60854. }
  60855. var zaxis = BoneLookController._tmpVecs[5];
  60856. var xaxis = BoneLookController._tmpVecs[6];
  60857. var yaxis = BoneLookController._tmpVecs[7];
  60858. var _tmpQuat = BoneLookController._tmpQuat;
  60859. target.subtractToRef(bonePos, zaxis);
  60860. zaxis.normalize();
  60861. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  60862. xaxis.normalize();
  60863. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  60864. yaxis.normalize();
  60865. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  60866. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  60867. return;
  60868. }
  60869. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  60870. return;
  60871. }
  60872. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  60873. return;
  60874. }
  60875. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  60876. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  60877. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  60878. }
  60879. if (this.slerpAmount < 1) {
  60880. if (!this._slerping) {
  60881. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  60882. }
  60883. if (this._transformYawPitch) {
  60884. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  60885. }
  60886. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  60887. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  60888. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  60889. this._slerping = true;
  60890. }
  60891. else {
  60892. if (this._transformYawPitch) {
  60893. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  60894. }
  60895. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  60896. this._slerping = false;
  60897. }
  60898. };
  60899. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  60900. var angDiff = ang2 - ang1;
  60901. angDiff %= Math.PI * 2;
  60902. if (angDiff > Math.PI) {
  60903. angDiff -= Math.PI * 2;
  60904. }
  60905. else if (angDiff < -Math.PI) {
  60906. angDiff += Math.PI * 2;
  60907. }
  60908. return angDiff;
  60909. };
  60910. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  60911. ang1 %= (2 * Math.PI);
  60912. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  60913. ang2 %= (2 * Math.PI);
  60914. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  60915. var ab = 0;
  60916. if (ang1 < ang2) {
  60917. ab = ang2 - ang1;
  60918. }
  60919. else {
  60920. ab = ang1 - ang2;
  60921. }
  60922. if (ab > Math.PI) {
  60923. ab = Math.PI * 2 - ab;
  60924. }
  60925. return ab;
  60926. };
  60927. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  60928. ang %= (2 * Math.PI);
  60929. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  60930. ang1 %= (2 * Math.PI);
  60931. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  60932. ang2 %= (2 * Math.PI);
  60933. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  60934. if (ang1 < ang2) {
  60935. if (ang > ang1 && ang < ang2) {
  60936. return true;
  60937. }
  60938. }
  60939. else {
  60940. if (ang > ang2 && ang < ang1) {
  60941. return true;
  60942. }
  60943. }
  60944. return false;
  60945. };
  60946. 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()];
  60947. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  60948. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  60949. return BoneLookController;
  60950. }());
  60951. BABYLON.BoneLookController = BoneLookController;
  60952. })(BABYLON || (BABYLON = {}));
  60953. //# sourceMappingURL=babylon.boneLookController.js.map
  60954. var BABYLON;
  60955. (function (BABYLON) {
  60956. var Skeleton = /** @class */ (function () {
  60957. function Skeleton(name, id, scene) {
  60958. this.name = name;
  60959. this.id = id;
  60960. this.bones = new Array();
  60961. this.needInitialSkinMatrix = false;
  60962. this._isDirty = true;
  60963. this._meshesWithPoseMatrix = new Array();
  60964. this._identity = BABYLON.Matrix.Identity();
  60965. this._ranges = {};
  60966. this._lastAbsoluteTransformsUpdateId = -1;
  60967. // Events
  60968. /**
  60969. * An event triggered before computing the skeleton's matrices
  60970. * @type {BABYLON.Observable}
  60971. */
  60972. this.onBeforeComputeObservable = new BABYLON.Observable();
  60973. this.bones = [];
  60974. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60975. scene.skeletons.push(this);
  60976. //make sure it will recalculate the matrix next time prepare is called.
  60977. this._isDirty = true;
  60978. }
  60979. // Members
  60980. Skeleton.prototype.getTransformMatrices = function (mesh) {
  60981. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  60982. return mesh._bonesTransformMatrices;
  60983. }
  60984. if (!this._transformMatrices) {
  60985. this.prepare();
  60986. }
  60987. return this._transformMatrices;
  60988. };
  60989. Skeleton.prototype.getScene = function () {
  60990. return this._scene;
  60991. };
  60992. // Methods
  60993. /**
  60994. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  60995. */
  60996. Skeleton.prototype.toString = function (fullDetails) {
  60997. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  60998. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  60999. if (fullDetails) {
  61000. ret += ", Ranges: {";
  61001. var first = true;
  61002. for (var name_1 in this._ranges) {
  61003. if (first) {
  61004. ret += ", ";
  61005. first = false;
  61006. }
  61007. ret += name_1;
  61008. }
  61009. ret += "}";
  61010. }
  61011. return ret;
  61012. };
  61013. /**
  61014. * Get bone's index searching by name
  61015. * @param {string} name is bone's name to search for
  61016. * @return {number} Indice of the bone. Returns -1 if not found
  61017. */
  61018. Skeleton.prototype.getBoneIndexByName = function (name) {
  61019. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  61020. if (this.bones[boneIndex].name === name) {
  61021. return boneIndex;
  61022. }
  61023. }
  61024. return -1;
  61025. };
  61026. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  61027. // check name not already in use
  61028. if (!this._ranges[name]) {
  61029. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  61030. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  61031. if (this.bones[i].animations[0]) {
  61032. this.bones[i].animations[0].createRange(name, from, to);
  61033. }
  61034. }
  61035. }
  61036. };
  61037. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  61038. if (deleteFrames === void 0) { deleteFrames = true; }
  61039. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  61040. if (this.bones[i].animations[0]) {
  61041. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  61042. }
  61043. }
  61044. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  61045. };
  61046. Skeleton.prototype.getAnimationRange = function (name) {
  61047. return this._ranges[name];
  61048. };
  61049. /**
  61050. * Returns as an Array, all AnimationRanges defined on this skeleton
  61051. */
  61052. Skeleton.prototype.getAnimationRanges = function () {
  61053. var animationRanges = [];
  61054. var name;
  61055. var i = 0;
  61056. for (name in this._ranges) {
  61057. animationRanges[i] = this._ranges[name];
  61058. i++;
  61059. }
  61060. return animationRanges;
  61061. };
  61062. /**
  61063. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  61064. */
  61065. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  61066. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  61067. if (this._ranges[name] || !source.getAnimationRange(name)) {
  61068. return false;
  61069. }
  61070. var ret = true;
  61071. var frameOffset = this._getHighestAnimationFrame() + 1;
  61072. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  61073. var boneDict = {};
  61074. var sourceBones = source.bones;
  61075. var nBones;
  61076. var i;
  61077. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  61078. boneDict[sourceBones[i].name] = sourceBones[i];
  61079. }
  61080. if (this.bones.length !== sourceBones.length) {
  61081. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  61082. ret = false;
  61083. }
  61084. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  61085. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  61086. var boneName = this.bones[i].name;
  61087. var sourceBone = boneDict[boneName];
  61088. if (sourceBone) {
  61089. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  61090. }
  61091. else {
  61092. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  61093. ret = false;
  61094. }
  61095. }
  61096. // do not call createAnimationRange(), since it also is done to bones, which was already done
  61097. var range = source.getAnimationRange(name);
  61098. if (range) {
  61099. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  61100. }
  61101. return ret;
  61102. };
  61103. Skeleton.prototype.returnToRest = function () {
  61104. for (var index = 0; index < this.bones.length; index++) {
  61105. this.bones[index].returnToRest();
  61106. }
  61107. };
  61108. Skeleton.prototype._getHighestAnimationFrame = function () {
  61109. var ret = 0;
  61110. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  61111. if (this.bones[i].animations[0]) {
  61112. var highest = this.bones[i].animations[0].getHighestFrame();
  61113. if (ret < highest) {
  61114. ret = highest;
  61115. }
  61116. }
  61117. }
  61118. return ret;
  61119. };
  61120. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  61121. var range = this.getAnimationRange(name);
  61122. if (!range) {
  61123. return null;
  61124. }
  61125. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  61126. };
  61127. Skeleton.prototype._markAsDirty = function () {
  61128. this._isDirty = true;
  61129. };
  61130. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  61131. this._meshesWithPoseMatrix.push(mesh);
  61132. };
  61133. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  61134. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  61135. if (index > -1) {
  61136. this._meshesWithPoseMatrix.splice(index, 1);
  61137. }
  61138. };
  61139. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  61140. this.onBeforeComputeObservable.notifyObservers(this);
  61141. for (var index = 0; index < this.bones.length; index++) {
  61142. var bone = this.bones[index];
  61143. var parentBone = bone.getParent();
  61144. if (parentBone) {
  61145. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  61146. }
  61147. else {
  61148. if (initialSkinMatrix) {
  61149. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  61150. }
  61151. else {
  61152. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  61153. }
  61154. }
  61155. if (bone._index !== -1) {
  61156. var mappedIndex = bone._index === null ? index : bone._index;
  61157. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  61158. }
  61159. }
  61160. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  61161. };
  61162. Skeleton.prototype.prepare = function () {
  61163. if (!this._isDirty) {
  61164. return;
  61165. }
  61166. if (this.needInitialSkinMatrix) {
  61167. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  61168. var mesh = this._meshesWithPoseMatrix[index];
  61169. var poseMatrix = mesh.getPoseMatrix();
  61170. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  61171. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  61172. }
  61173. if (this._synchronizedWithMesh !== mesh) {
  61174. this._synchronizedWithMesh = mesh;
  61175. // Prepare bones
  61176. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  61177. var bone = this.bones[boneIndex];
  61178. if (!bone.getParent()) {
  61179. var matrix = bone.getBaseMatrix();
  61180. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  61181. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  61182. }
  61183. }
  61184. }
  61185. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  61186. }
  61187. }
  61188. else {
  61189. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  61190. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  61191. }
  61192. this._computeTransformMatrices(this._transformMatrices, null);
  61193. }
  61194. this._isDirty = false;
  61195. this._scene._activeBones.addCount(this.bones.length, false);
  61196. };
  61197. Skeleton.prototype.getAnimatables = function () {
  61198. if (!this._animatables || this._animatables.length !== this.bones.length) {
  61199. this._animatables = [];
  61200. for (var index = 0; index < this.bones.length; index++) {
  61201. this._animatables.push(this.bones[index]);
  61202. }
  61203. }
  61204. return this._animatables;
  61205. };
  61206. Skeleton.prototype.clone = function (name, id) {
  61207. var result = new Skeleton(name, id || name, this._scene);
  61208. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  61209. for (var index = 0; index < this.bones.length; index++) {
  61210. var source = this.bones[index];
  61211. var parentBone = null;
  61212. var parent_1 = source.getParent();
  61213. if (parent_1) {
  61214. var parentIndex = this.bones.indexOf(parent_1);
  61215. parentBone = result.bones[parentIndex];
  61216. }
  61217. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  61218. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  61219. }
  61220. if (this._ranges) {
  61221. result._ranges = {};
  61222. for (var rangeName in this._ranges) {
  61223. var range = this._ranges[rangeName];
  61224. if (range) {
  61225. result._ranges[rangeName] = range.clone();
  61226. }
  61227. }
  61228. }
  61229. this._isDirty = true;
  61230. return result;
  61231. };
  61232. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  61233. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  61234. this.bones.forEach(function (bone) {
  61235. bone.animations.forEach(function (animation) {
  61236. animation.enableBlending = true;
  61237. animation.blendingSpeed = blendingSpeed;
  61238. });
  61239. });
  61240. };
  61241. Skeleton.prototype.dispose = function () {
  61242. this._meshesWithPoseMatrix = [];
  61243. // Animations
  61244. this.getScene().stopAnimation(this);
  61245. // Remove from scene
  61246. this.getScene().removeSkeleton(this);
  61247. };
  61248. Skeleton.prototype.serialize = function () {
  61249. var serializationObject = {};
  61250. serializationObject.name = this.name;
  61251. serializationObject.id = this.id;
  61252. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  61253. serializationObject.bones = [];
  61254. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  61255. for (var index = 0; index < this.bones.length; index++) {
  61256. var bone = this.bones[index];
  61257. var parent_2 = bone.getParent();
  61258. var serializedBone = {
  61259. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  61260. name: bone.name,
  61261. matrix: bone.getBaseMatrix().toArray(),
  61262. rest: bone.getRestPose().toArray()
  61263. };
  61264. serializationObject.bones.push(serializedBone);
  61265. if (bone.length) {
  61266. serializedBone.length = bone.length;
  61267. }
  61268. if (bone.animations && bone.animations.length > 0) {
  61269. serializedBone.animation = bone.animations[0].serialize();
  61270. }
  61271. serializationObject.ranges = [];
  61272. for (var name in this._ranges) {
  61273. var source = this._ranges[name];
  61274. if (!source) {
  61275. continue;
  61276. }
  61277. var range = {};
  61278. range.name = name;
  61279. range.from = source.from;
  61280. range.to = source.to;
  61281. serializationObject.ranges.push(range);
  61282. }
  61283. }
  61284. return serializationObject;
  61285. };
  61286. Skeleton.Parse = function (parsedSkeleton, scene) {
  61287. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  61288. if (parsedSkeleton.dimensionsAtRest) {
  61289. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  61290. }
  61291. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  61292. var index;
  61293. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  61294. var parsedBone = parsedSkeleton.bones[index];
  61295. var parentBone = null;
  61296. if (parsedBone.parentBoneIndex > -1) {
  61297. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  61298. }
  61299. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  61300. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  61301. if (parsedBone.length) {
  61302. bone.length = parsedBone.length;
  61303. }
  61304. if (parsedBone.animation) {
  61305. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  61306. }
  61307. }
  61308. // placed after bones, so createAnimationRange can cascade down
  61309. if (parsedSkeleton.ranges) {
  61310. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  61311. var data = parsedSkeleton.ranges[index];
  61312. skeleton.createAnimationRange(data.name, data.from, data.to);
  61313. }
  61314. }
  61315. return skeleton;
  61316. };
  61317. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  61318. if (forceUpdate === void 0) { forceUpdate = false; }
  61319. var renderId = this._scene.getRenderId();
  61320. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  61321. this.bones[0].computeAbsoluteTransforms();
  61322. this._lastAbsoluteTransformsUpdateId = renderId;
  61323. }
  61324. };
  61325. Skeleton.prototype.getPoseMatrix = function () {
  61326. var poseMatrix = null;
  61327. if (this._meshesWithPoseMatrix.length > 0) {
  61328. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  61329. }
  61330. return poseMatrix;
  61331. };
  61332. Skeleton.prototype.sortBones = function () {
  61333. var bones = new Array();
  61334. var visited = new Array(this.bones.length);
  61335. for (var index = 0; index < this.bones.length; index++) {
  61336. this._sortBones(index, bones, visited);
  61337. }
  61338. this.bones = bones;
  61339. };
  61340. Skeleton.prototype._sortBones = function (index, bones, visited) {
  61341. if (visited[index]) {
  61342. return;
  61343. }
  61344. visited[index] = true;
  61345. var bone = this.bones[index];
  61346. if (bone._index === undefined) {
  61347. bone._index = index;
  61348. }
  61349. var parentBone = bone.getParent();
  61350. if (parentBone) {
  61351. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  61352. }
  61353. bones.push(bone);
  61354. };
  61355. return Skeleton;
  61356. }());
  61357. BABYLON.Skeleton = Skeleton;
  61358. })(BABYLON || (BABYLON = {}));
  61359. //# sourceMappingURL=babylon.skeleton.js.map
  61360. var BABYLON;
  61361. (function (BABYLON) {
  61362. var SphericalPolynomial = /** @class */ (function () {
  61363. function SphericalPolynomial() {
  61364. this.x = BABYLON.Vector3.Zero();
  61365. this.y = BABYLON.Vector3.Zero();
  61366. this.z = BABYLON.Vector3.Zero();
  61367. this.xx = BABYLON.Vector3.Zero();
  61368. this.yy = BABYLON.Vector3.Zero();
  61369. this.zz = BABYLON.Vector3.Zero();
  61370. this.xy = BABYLON.Vector3.Zero();
  61371. this.yz = BABYLON.Vector3.Zero();
  61372. this.zx = BABYLON.Vector3.Zero();
  61373. }
  61374. SphericalPolynomial.prototype.addAmbient = function (color) {
  61375. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  61376. this.xx = this.xx.add(colorVector);
  61377. this.yy = this.yy.add(colorVector);
  61378. this.zz = this.zz.add(colorVector);
  61379. };
  61380. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  61381. var result = new SphericalPolynomial();
  61382. result.x = harmonics.L11.scale(1.02333);
  61383. result.y = harmonics.L1_1.scale(1.02333);
  61384. result.z = harmonics.L10.scale(1.02333);
  61385. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  61386. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  61387. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  61388. result.yz = harmonics.L2_1.scale(0.858086);
  61389. result.zx = harmonics.L21.scale(0.858086);
  61390. result.xy = harmonics.L2_2.scale(0.858086);
  61391. result.scale(1.0 / Math.PI);
  61392. return result;
  61393. };
  61394. SphericalPolynomial.prototype.scale = function (scale) {
  61395. this.x = this.x.scale(scale);
  61396. this.y = this.y.scale(scale);
  61397. this.z = this.z.scale(scale);
  61398. this.xx = this.xx.scale(scale);
  61399. this.yy = this.yy.scale(scale);
  61400. this.zz = this.zz.scale(scale);
  61401. this.yz = this.yz.scale(scale);
  61402. this.zx = this.zx.scale(scale);
  61403. this.xy = this.xy.scale(scale);
  61404. };
  61405. return SphericalPolynomial;
  61406. }());
  61407. BABYLON.SphericalPolynomial = SphericalPolynomial;
  61408. var SphericalHarmonics = /** @class */ (function () {
  61409. function SphericalHarmonics() {
  61410. this.L00 = BABYLON.Vector3.Zero();
  61411. this.L1_1 = BABYLON.Vector3.Zero();
  61412. this.L10 = BABYLON.Vector3.Zero();
  61413. this.L11 = BABYLON.Vector3.Zero();
  61414. this.L2_2 = BABYLON.Vector3.Zero();
  61415. this.L2_1 = BABYLON.Vector3.Zero();
  61416. this.L20 = BABYLON.Vector3.Zero();
  61417. this.L21 = BABYLON.Vector3.Zero();
  61418. this.L22 = BABYLON.Vector3.Zero();
  61419. }
  61420. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  61421. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  61422. var c = colorVector.scale(deltaSolidAngle);
  61423. this.L00 = this.L00.add(c.scale(0.282095));
  61424. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  61425. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  61426. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  61427. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  61428. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  61429. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  61430. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  61431. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  61432. };
  61433. SphericalHarmonics.prototype.scale = function (scale) {
  61434. this.L00 = this.L00.scale(scale);
  61435. this.L1_1 = this.L1_1.scale(scale);
  61436. this.L10 = this.L10.scale(scale);
  61437. this.L11 = this.L11.scale(scale);
  61438. this.L2_2 = this.L2_2.scale(scale);
  61439. this.L2_1 = this.L2_1.scale(scale);
  61440. this.L20 = this.L20.scale(scale);
  61441. this.L21 = this.L21.scale(scale);
  61442. this.L22 = this.L22.scale(scale);
  61443. };
  61444. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  61445. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  61446. //
  61447. // E_lm = A_l * L_lm
  61448. //
  61449. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  61450. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  61451. // the scaling factors are given in equation 9.
  61452. // Constant (Band 0)
  61453. this.L00 = this.L00.scale(3.141593);
  61454. // Linear (Band 1)
  61455. this.L1_1 = this.L1_1.scale(2.094395);
  61456. this.L10 = this.L10.scale(2.094395);
  61457. this.L11 = this.L11.scale(2.094395);
  61458. // Quadratic (Band 2)
  61459. this.L2_2 = this.L2_2.scale(0.785398);
  61460. this.L2_1 = this.L2_1.scale(0.785398);
  61461. this.L20 = this.L20.scale(0.785398);
  61462. this.L21 = this.L21.scale(0.785398);
  61463. this.L22 = this.L22.scale(0.785398);
  61464. };
  61465. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  61466. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  61467. // L = (1/pi) * E * rho
  61468. //
  61469. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  61470. this.scale(1.0 / Math.PI);
  61471. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  61472. // (The pixel shader must apply albedo after texture fetches, etc).
  61473. };
  61474. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  61475. var result = new SphericalHarmonics();
  61476. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  61477. result.L1_1 = polynomial.y.scale(0.977204);
  61478. result.L10 = polynomial.z.scale(0.977204);
  61479. result.L11 = polynomial.x.scale(0.977204);
  61480. result.L2_2 = polynomial.xy.scale(1.16538);
  61481. result.L2_1 = polynomial.yz.scale(1.16538);
  61482. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  61483. result.L21 = polynomial.zx.scale(1.16538);
  61484. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  61485. result.scale(Math.PI);
  61486. return result;
  61487. };
  61488. return SphericalHarmonics;
  61489. }());
  61490. BABYLON.SphericalHarmonics = SphericalHarmonics;
  61491. })(BABYLON || (BABYLON = {}));
  61492. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  61493. var BABYLON;
  61494. (function (BABYLON) {
  61495. var Internals;
  61496. (function (Internals) {
  61497. var FileFaceOrientation = /** @class */ (function () {
  61498. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  61499. this.name = name;
  61500. this.worldAxisForNormal = worldAxisForNormal;
  61501. this.worldAxisForFileX = worldAxisForFileX;
  61502. this.worldAxisForFileY = worldAxisForFileY;
  61503. }
  61504. return FileFaceOrientation;
  61505. }());
  61506. ;
  61507. /**
  61508. * Helper class dealing with the extraction of spherical polynomial dataArray
  61509. * from a cube map.
  61510. */
  61511. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  61512. function CubeMapToSphericalPolynomialTools() {
  61513. }
  61514. /**
  61515. * Converts a texture to the according Spherical Polynomial data.
  61516. * This extracts the first 3 orders only as they are the only one used in the lighting.
  61517. *
  61518. * @param texture The texture to extract the information from.
  61519. * @return The Spherical Polynomial data.
  61520. */
  61521. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  61522. if (!texture.isCube) {
  61523. // Only supports cube Textures currently.
  61524. return null;
  61525. }
  61526. var size = texture.getSize().width;
  61527. var right = texture.readPixels(0);
  61528. var left = texture.readPixels(1);
  61529. var up;
  61530. var down;
  61531. if (texture.isRenderTarget) {
  61532. up = texture.readPixels(3);
  61533. down = texture.readPixels(2);
  61534. }
  61535. else {
  61536. up = texture.readPixels(2);
  61537. down = texture.readPixels(3);
  61538. }
  61539. var front = texture.readPixels(4);
  61540. var back = texture.readPixels(5);
  61541. var gammaSpace = texture.gammaSpace;
  61542. // Always read as RGBA.
  61543. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  61544. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61545. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  61546. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61547. }
  61548. var cubeInfo = {
  61549. size: size,
  61550. right: right,
  61551. left: left,
  61552. up: up,
  61553. down: down,
  61554. front: front,
  61555. back: back,
  61556. format: format,
  61557. type: type,
  61558. gammaSpace: gammaSpace,
  61559. };
  61560. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  61561. };
  61562. /**
  61563. * Converts a cubemap to the according Spherical Polynomial data.
  61564. * This extracts the first 3 orders only as they are the only one used in the lighting.
  61565. *
  61566. * @param cubeInfo The Cube map to extract the information from.
  61567. * @return The Spherical Polynomial data.
  61568. */
  61569. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  61570. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  61571. var totalSolidAngle = 0.0;
  61572. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  61573. var du = 2.0 / cubeInfo.size;
  61574. var dv = du;
  61575. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  61576. var minUV = du * 0.5 - 1.0;
  61577. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  61578. var fileFace = this.FileFaces[faceIndex];
  61579. var dataArray = cubeInfo[fileFace.name];
  61580. var v = minUV;
  61581. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  61582. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  61583. // Because SP is still linear, so summation is fine in that basis.
  61584. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  61585. for (var y = 0; y < cubeInfo.size; y++) {
  61586. var u = minUV;
  61587. for (var x = 0; x < cubeInfo.size; x++) {
  61588. // World direction (not normalised)
  61589. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  61590. worldDirection.normalize();
  61591. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  61592. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  61593. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  61594. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  61595. // Handle Integer types.
  61596. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  61597. r /= 255;
  61598. g /= 255;
  61599. b /= 255;
  61600. }
  61601. // Handle Gamma space textures.
  61602. if (cubeInfo.gammaSpace) {
  61603. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  61604. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  61605. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  61606. }
  61607. var color = new BABYLON.Color3(r, g, b);
  61608. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  61609. totalSolidAngle += deltaSolidAngle;
  61610. u += du;
  61611. }
  61612. v += dv;
  61613. }
  61614. }
  61615. // Solid angle for entire sphere is 4*pi
  61616. var sphereSolidAngle = 4.0 * Math.PI;
  61617. // Adjust the solid angle to allow for how many faces we processed.
  61618. var facesProcessed = 6.0;
  61619. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  61620. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  61621. // This is needed because the numerical integration over the cube uses a
  61622. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  61623. // and also to compensate for accumulative error due to float precision in the summation.
  61624. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  61625. sphericalHarmonics.scale(correctionFactor);
  61626. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  61627. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  61628. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  61629. };
  61630. CubeMapToSphericalPolynomialTools.FileFaces = [
  61631. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  61632. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  61633. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  61634. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  61635. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  61636. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  61637. ];
  61638. return CubeMapToSphericalPolynomialTools;
  61639. }());
  61640. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  61641. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  61642. })(BABYLON || (BABYLON = {}));
  61643. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  61644. var BABYLON;
  61645. (function (BABYLON) {
  61646. var Internals;
  61647. (function (Internals) {
  61648. /**
  61649. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  61650. */
  61651. var PanoramaToCubeMapTools = /** @class */ (function () {
  61652. function PanoramaToCubeMapTools() {
  61653. }
  61654. /**
  61655. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  61656. *
  61657. * @param float32Array The source data.
  61658. * @param inputWidth The width of the input panorama.
  61659. * @param inputhHeight The height of the input panorama.
  61660. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  61661. * @return The cubemap data
  61662. */
  61663. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  61664. if (!float32Array) {
  61665. throw "ConvertPanoramaToCubemap: input cannot be null";
  61666. }
  61667. if (float32Array.length != inputWidth * inputHeight * 3) {
  61668. throw "ConvertPanoramaToCubemap: input size is wrong";
  61669. }
  61670. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  61671. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  61672. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  61673. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  61674. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  61675. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  61676. return {
  61677. front: textureFront,
  61678. back: textureBack,
  61679. left: textureLeft,
  61680. right: textureRight,
  61681. up: textureUp,
  61682. down: textureDown,
  61683. size: size,
  61684. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  61685. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  61686. gammaSpace: false,
  61687. };
  61688. };
  61689. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  61690. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  61691. var textureArray = new Float32Array(buffer);
  61692. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  61693. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  61694. var dy = 1 / texSize;
  61695. var fy = 0;
  61696. for (var y = 0; y < texSize; y++) {
  61697. var xv1 = faceData[0];
  61698. var xv2 = faceData[2];
  61699. for (var x = 0; x < texSize; x++) {
  61700. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  61701. v.normalize();
  61702. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  61703. // 3 channels per pixels
  61704. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  61705. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  61706. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  61707. xv1 = xv1.add(rotDX1);
  61708. xv2 = xv2.add(rotDX2);
  61709. }
  61710. fy += dy;
  61711. }
  61712. return textureArray;
  61713. };
  61714. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  61715. var theta = Math.atan2(vDir.z, vDir.x);
  61716. var phi = Math.acos(vDir.y);
  61717. while (theta < -Math.PI)
  61718. theta += 2 * Math.PI;
  61719. while (theta > Math.PI)
  61720. theta -= 2 * Math.PI;
  61721. var dx = theta / Math.PI;
  61722. var dy = phi / Math.PI;
  61723. // recenter.
  61724. dx = dx * 0.5 + 0.5;
  61725. var px = Math.round(dx * inputWidth);
  61726. if (px < 0)
  61727. px = 0;
  61728. else if (px >= inputWidth)
  61729. px = inputWidth - 1;
  61730. var py = Math.round(dy * inputHeight);
  61731. if (py < 0)
  61732. py = 0;
  61733. else if (py >= inputHeight)
  61734. py = inputHeight - 1;
  61735. var inputY = (inputHeight - py - 1);
  61736. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  61737. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  61738. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  61739. return {
  61740. r: r,
  61741. g: g,
  61742. b: b
  61743. };
  61744. };
  61745. PanoramaToCubeMapTools.FACE_FRONT = [
  61746. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  61747. new BABYLON.Vector3(1.0, -1.0, -1.0),
  61748. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  61749. new BABYLON.Vector3(1.0, 1.0, -1.0)
  61750. ];
  61751. PanoramaToCubeMapTools.FACE_BACK = [
  61752. new BABYLON.Vector3(1.0, -1.0, 1.0),
  61753. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  61754. new BABYLON.Vector3(1.0, 1.0, 1.0),
  61755. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  61756. ];
  61757. PanoramaToCubeMapTools.FACE_RIGHT = [
  61758. new BABYLON.Vector3(1.0, -1.0, -1.0),
  61759. new BABYLON.Vector3(1.0, -1.0, 1.0),
  61760. new BABYLON.Vector3(1.0, 1.0, -1.0),
  61761. new BABYLON.Vector3(1.0, 1.0, 1.0)
  61762. ];
  61763. PanoramaToCubeMapTools.FACE_LEFT = [
  61764. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  61765. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  61766. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  61767. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  61768. ];
  61769. PanoramaToCubeMapTools.FACE_DOWN = [
  61770. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  61771. new BABYLON.Vector3(1.0, 1.0, -1.0),
  61772. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  61773. new BABYLON.Vector3(1.0, 1.0, 1.0)
  61774. ];
  61775. PanoramaToCubeMapTools.FACE_UP = [
  61776. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  61777. new BABYLON.Vector3(1.0, -1.0, 1.0),
  61778. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  61779. new BABYLON.Vector3(1.0, -1.0, -1.0)
  61780. ];
  61781. return PanoramaToCubeMapTools;
  61782. }());
  61783. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  61784. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  61785. })(BABYLON || (BABYLON = {}));
  61786. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  61787. var BABYLON;
  61788. (function (BABYLON) {
  61789. var Internals;
  61790. (function (Internals) {
  61791. ;
  61792. /**
  61793. * This groups tools to convert HDR texture to native colors array.
  61794. */
  61795. var HDRTools = /** @class */ (function () {
  61796. function HDRTools() {
  61797. }
  61798. HDRTools.Ldexp = function (mantissa, exponent) {
  61799. if (exponent > 1023) {
  61800. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  61801. }
  61802. if (exponent < -1074) {
  61803. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  61804. }
  61805. return mantissa * Math.pow(2, exponent);
  61806. };
  61807. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  61808. if (exponent > 0) {
  61809. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  61810. float32array[index + 0] = red * exponent;
  61811. float32array[index + 1] = green * exponent;
  61812. float32array[index + 2] = blue * exponent;
  61813. }
  61814. else {
  61815. float32array[index + 0] = 0;
  61816. float32array[index + 1] = 0;
  61817. float32array[index + 2] = 0;
  61818. }
  61819. };
  61820. HDRTools.readStringLine = function (uint8array, startIndex) {
  61821. var line = "";
  61822. var character = "";
  61823. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  61824. character = String.fromCharCode(uint8array[i]);
  61825. if (character == "\n") {
  61826. break;
  61827. }
  61828. line += character;
  61829. }
  61830. return line;
  61831. };
  61832. /**
  61833. * Reads header information from an RGBE texture stored in a native array.
  61834. * More information on this format are available here:
  61835. * https://en.wikipedia.org/wiki/RGBE_image_format
  61836. *
  61837. * @param uint8array The binary file stored in native array.
  61838. * @return The header information.
  61839. */
  61840. HDRTools.RGBE_ReadHeader = function (uint8array) {
  61841. var height = 0;
  61842. var width = 0;
  61843. var line = this.readStringLine(uint8array, 0);
  61844. if (line[0] != '#' || line[1] != '?') {
  61845. throw "Bad HDR Format.";
  61846. }
  61847. var endOfHeader = false;
  61848. var findFormat = false;
  61849. var lineIndex = 0;
  61850. do {
  61851. lineIndex += (line.length + 1);
  61852. line = this.readStringLine(uint8array, lineIndex);
  61853. if (line == "FORMAT=32-bit_rle_rgbe") {
  61854. findFormat = true;
  61855. }
  61856. else if (line.length == 0) {
  61857. endOfHeader = true;
  61858. }
  61859. } while (!endOfHeader);
  61860. if (!findFormat) {
  61861. throw "HDR Bad header format, unsupported FORMAT";
  61862. }
  61863. lineIndex += (line.length + 1);
  61864. line = this.readStringLine(uint8array, lineIndex);
  61865. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  61866. var match = sizeRegexp.exec(line);
  61867. // TODO. Support +Y and -X if needed.
  61868. if (!match || match.length < 3) {
  61869. throw "HDR Bad header format, no size";
  61870. }
  61871. width = parseInt(match[2]);
  61872. height = parseInt(match[1]);
  61873. if (width < 8 || width > 0x7fff) {
  61874. throw "HDR Bad header format, unsupported size";
  61875. }
  61876. lineIndex += (line.length + 1);
  61877. return {
  61878. height: height,
  61879. width: width,
  61880. dataPosition: lineIndex
  61881. };
  61882. };
  61883. /**
  61884. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  61885. * This RGBE texture needs to store the information as a panorama.
  61886. *
  61887. * More information on this format are available here:
  61888. * https://en.wikipedia.org/wiki/RGBE_image_format
  61889. *
  61890. * @param buffer The binary file stored in an array buffer.
  61891. * @param size The expected size of the extracted cubemap.
  61892. * @return The Cube Map information.
  61893. */
  61894. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  61895. var uint8array = new Uint8Array(buffer);
  61896. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  61897. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  61898. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  61899. return cubeMapData;
  61900. };
  61901. /**
  61902. * Returns the pixels data extracted from an RGBE texture.
  61903. * This pixels will be stored left to right up to down in the R G B order in one array.
  61904. *
  61905. * More information on this format are available here:
  61906. * https://en.wikipedia.org/wiki/RGBE_image_format
  61907. *
  61908. * @param uint8array The binary file stored in an array buffer.
  61909. * @param hdrInfo The header information of the file.
  61910. * @return The pixels data in RGB right to left up to down order.
  61911. */
  61912. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  61913. // Keep for multi format supports.
  61914. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  61915. };
  61916. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  61917. var num_scanlines = hdrInfo.height;
  61918. var scanline_width = hdrInfo.width;
  61919. var a, b, c, d, count;
  61920. var dataIndex = hdrInfo.dataPosition;
  61921. var index = 0, endIndex = 0, i = 0;
  61922. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  61923. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  61924. // 3 channels of 4 bytes per pixel in float.
  61925. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  61926. var resultArray = new Float32Array(resultBuffer);
  61927. // read in each successive scanline
  61928. while (num_scanlines > 0) {
  61929. a = uint8array[dataIndex++];
  61930. b = uint8array[dataIndex++];
  61931. c = uint8array[dataIndex++];
  61932. d = uint8array[dataIndex++];
  61933. if (a != 2 || b != 2 || (c & 0x80)) {
  61934. // this file is not run length encoded
  61935. throw "HDR Bad header format, not RLE";
  61936. }
  61937. if (((c << 8) | d) != scanline_width) {
  61938. throw "HDR Bad header format, wrong scan line width";
  61939. }
  61940. index = 0;
  61941. // read each of the four channels for the scanline into the buffer
  61942. for (i = 0; i < 4; i++) {
  61943. endIndex = (i + 1) * scanline_width;
  61944. while (index < endIndex) {
  61945. a = uint8array[dataIndex++];
  61946. b = uint8array[dataIndex++];
  61947. if (a > 128) {
  61948. // a run of the same value
  61949. count = a - 128;
  61950. if ((count == 0) || (count > endIndex - index)) {
  61951. throw "HDR Bad Format, bad scanline data (run)";
  61952. }
  61953. while (count-- > 0) {
  61954. scanLineArray[index++] = b;
  61955. }
  61956. }
  61957. else {
  61958. // a non-run
  61959. count = a;
  61960. if ((count == 0) || (count > endIndex - index)) {
  61961. throw "HDR Bad Format, bad scanline data (non-run)";
  61962. }
  61963. scanLineArray[index++] = b;
  61964. if (--count > 0) {
  61965. for (var j = 0; j < count; j++) {
  61966. scanLineArray[index++] = uint8array[dataIndex++];
  61967. }
  61968. }
  61969. }
  61970. }
  61971. }
  61972. // now convert data from buffer into floats
  61973. for (i = 0; i < scanline_width; i++) {
  61974. a = scanLineArray[i];
  61975. b = scanLineArray[i + scanline_width];
  61976. c = scanLineArray[i + 2 * scanline_width];
  61977. d = scanLineArray[i + 3 * scanline_width];
  61978. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  61979. }
  61980. num_scanlines--;
  61981. }
  61982. return resultArray;
  61983. };
  61984. return HDRTools;
  61985. }());
  61986. Internals.HDRTools = HDRTools;
  61987. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  61988. })(BABYLON || (BABYLON = {}));
  61989. //# sourceMappingURL=babylon.hdr.js.map
  61990. var BABYLON;
  61991. (function (BABYLON) {
  61992. /**
  61993. * This represents a texture coming from an HDR input.
  61994. *
  61995. * The only supported format is currently panorama picture stored in RGBE format.
  61996. * Example of such files can be found on HDRLib: http://hdrlib.com/
  61997. */
  61998. var HDRCubeTexture = /** @class */ (function (_super) {
  61999. __extends(HDRCubeTexture, _super);
  62000. /**
  62001. * Instantiates an HDRTexture from the following parameters.
  62002. *
  62003. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  62004. * @param scene The scene the texture will be used in
  62005. * @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.
  62006. * @param noMipmap Forces to not generate the mipmap if true
  62007. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  62008. * @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)
  62009. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  62010. */
  62011. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  62012. if (noMipmap === void 0) { noMipmap = false; }
  62013. if (generateHarmonics === void 0) { generateHarmonics = true; }
  62014. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  62015. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  62016. if (onLoad === void 0) { onLoad = null; }
  62017. if (onError === void 0) { onError = null; }
  62018. var _this = _super.call(this, scene) || this;
  62019. _this._useInGammaSpace = false;
  62020. _this._generateHarmonics = true;
  62021. _this._isBABYLONPreprocessed = false;
  62022. _this._onLoad = null;
  62023. _this._onError = null;
  62024. /**
  62025. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  62026. */
  62027. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  62028. /**
  62029. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  62030. * This is usefull at run time to apply the good shader.
  62031. */
  62032. _this.isPMREM = false;
  62033. _this._isBlocking = true;
  62034. if (!url) {
  62035. return _this;
  62036. }
  62037. _this.name = url;
  62038. _this.url = url;
  62039. _this.hasAlpha = false;
  62040. _this.isCube = true;
  62041. _this._textureMatrix = BABYLON.Matrix.Identity();
  62042. _this._onLoad = onLoad;
  62043. _this._onError = onError;
  62044. _this.gammaSpace = false;
  62045. if (size) {
  62046. _this._isBABYLONPreprocessed = false;
  62047. _this._noMipmap = noMipmap;
  62048. _this._size = size;
  62049. _this._useInGammaSpace = useInGammaSpace;
  62050. _this._usePMREMGenerator = usePMREMGenerator &&
  62051. scene.getEngine().getCaps().textureLOD &&
  62052. _this.getScene().getEngine().getCaps().textureFloat &&
  62053. !_this._useInGammaSpace;
  62054. }
  62055. else {
  62056. _this._isBABYLONPreprocessed = true;
  62057. _this._noMipmap = false;
  62058. _this._useInGammaSpace = false;
  62059. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  62060. _this.getScene().getEngine().getCaps().textureFloat &&
  62061. !_this._useInGammaSpace;
  62062. }
  62063. _this.isPMREM = _this._usePMREMGenerator;
  62064. _this._texture = _this._getFromCache(url, _this._noMipmap);
  62065. if (!_this._texture) {
  62066. if (!scene.useDelayedTextureLoading) {
  62067. _this.loadTexture();
  62068. }
  62069. else {
  62070. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  62071. }
  62072. }
  62073. return _this;
  62074. }
  62075. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  62076. /**
  62077. * Gets wether or not the texture is blocking during loading.
  62078. */
  62079. get: function () {
  62080. return this._isBlocking;
  62081. },
  62082. /**
  62083. * Sets wether or not the texture is blocking during loading.
  62084. */
  62085. set: function (value) {
  62086. this._isBlocking = value;
  62087. },
  62088. enumerable: true,
  62089. configurable: true
  62090. });
  62091. /**
  62092. * Occurs when the file is a preprocessed .babylon.hdr file.
  62093. */
  62094. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  62095. var _this = this;
  62096. var mipLevels = 0;
  62097. var floatArrayView = null;
  62098. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  62099. var mips = new Array();
  62100. var startIndex = 30;
  62101. for (var level = 0; level < mipLevels; level++) {
  62102. mips.push([]);
  62103. // Fill each pixel of the mip level.
  62104. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  62105. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  62106. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  62107. mips[level].push(faceData);
  62108. startIndex += faceSize;
  62109. }
  62110. }
  62111. return mips;
  62112. } : null;
  62113. var callback = function (buffer) {
  62114. // Create Native Array Views
  62115. var intArrayView = new Int32Array(buffer);
  62116. floatArrayView = new Float32Array(buffer);
  62117. // Fill header.
  62118. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  62119. _this._size = intArrayView[1]; // CubeMap max mip face size.
  62120. // Update Texture Information.
  62121. _this._texture.updateSize(_this._size, _this._size);
  62122. // Fill polynomial information.
  62123. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  62124. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  62125. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  62126. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  62127. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  62128. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  62129. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  62130. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  62131. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  62132. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  62133. _this.sphericalPolynomial = sphericalPolynomial;
  62134. // Fill pixel data.
  62135. mipLevels = intArrayView[29]; // Number of mip levels.
  62136. var startIndex = 30;
  62137. var data = [];
  62138. var faceSize = Math.pow(_this._size, 2) * 3;
  62139. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  62140. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  62141. startIndex += faceSize;
  62142. }
  62143. var results = [];
  62144. var byteArray = null;
  62145. // Push each faces.
  62146. for (var k = 0; k < 6; k++) {
  62147. var dataFace = null;
  62148. // To be deprecated.
  62149. if (version === 1) {
  62150. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  62151. dataFace = data[j];
  62152. }
  62153. // If special cases.
  62154. if (!mipmapGenerator) {
  62155. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  62156. // 3 channels of 1 bytes per pixel in bytes.
  62157. var byteBuffer = new ArrayBuffer(faceSize);
  62158. byteArray = new Uint8Array(byteBuffer);
  62159. }
  62160. for (var i = 0; i < _this._size * _this._size; i++) {
  62161. // Put in gamma space if requested.
  62162. if (_this._useInGammaSpace) {
  62163. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  62164. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  62165. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  62166. }
  62167. // Convert to int texture for fallback.
  62168. if (byteArray) {
  62169. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  62170. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  62171. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  62172. // May use luminance instead if the result is not accurate.
  62173. var max = Math.max(Math.max(r, g), b);
  62174. if (max > 255) {
  62175. var scale = 255 / max;
  62176. r *= scale;
  62177. g *= scale;
  62178. b *= scale;
  62179. }
  62180. byteArray[(i * 3) + 0] = r;
  62181. byteArray[(i * 3) + 1] = g;
  62182. byteArray[(i * 3) + 2] = b;
  62183. }
  62184. }
  62185. }
  62186. // Fill the array accordingly.
  62187. if (byteArray) {
  62188. results.push(byteArray);
  62189. }
  62190. else {
  62191. results.push(dataFace);
  62192. }
  62193. }
  62194. return results;
  62195. };
  62196. this._texture = this.getScene().getEngine().createRawCubeTextureFromUrl(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  62197. };
  62198. /**
  62199. * Occurs when the file is raw .hdr file.
  62200. */
  62201. HDRCubeTexture.prototype.loadHDRTexture = function () {
  62202. var _this = this;
  62203. var callback = function (buffer) {
  62204. // Extract the raw linear data.
  62205. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  62206. // Generate harmonics if needed.
  62207. if (_this._generateHarmonics) {
  62208. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  62209. _this.sphericalPolynomial = sphericalPolynomial;
  62210. }
  62211. var results = [];
  62212. var byteArray = null;
  62213. // Push each faces.
  62214. for (var j = 0; j < 6; j++) {
  62215. // Create uintarray fallback.
  62216. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  62217. // 3 channels of 1 bytes per pixel in bytes.
  62218. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  62219. byteArray = new Uint8Array(byteBuffer);
  62220. }
  62221. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  62222. // If special cases.
  62223. if (_this._useInGammaSpace || byteArray) {
  62224. for (var i = 0; i < _this._size * _this._size; i++) {
  62225. // Put in gamma space if requested.
  62226. if (_this._useInGammaSpace) {
  62227. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  62228. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  62229. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  62230. }
  62231. // Convert to int texture for fallback.
  62232. if (byteArray) {
  62233. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  62234. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  62235. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  62236. // May use luminance instead if the result is not accurate.
  62237. var max = Math.max(Math.max(r, g), b);
  62238. if (max > 255) {
  62239. var scale = 255 / max;
  62240. r *= scale;
  62241. g *= scale;
  62242. b *= scale;
  62243. }
  62244. byteArray[(i * 3) + 0] = r;
  62245. byteArray[(i * 3) + 1] = g;
  62246. byteArray[(i * 3) + 2] = b;
  62247. }
  62248. }
  62249. }
  62250. if (byteArray) {
  62251. results.push(byteArray);
  62252. }
  62253. else {
  62254. results.push(dataFace);
  62255. }
  62256. }
  62257. return results;
  62258. };
  62259. var mipmapGenerator = null;
  62260. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  62261. // if (!this._noMipmap &&
  62262. // this._usePMREMGenerator) {
  62263. // mipmapGenerator = (data: ArrayBufferView[]) => {
  62264. // // Custom setup of the generator matching with the PBR shader values.
  62265. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  62266. // this._size,
  62267. // this._size,
  62268. // 0,
  62269. // 3,
  62270. // this.getScene().getEngine().getCaps().textureFloat,
  62271. // 2048,
  62272. // 0.25,
  62273. // false,
  62274. // true);
  62275. // return generator.filterCubeMap();
  62276. // };
  62277. // }
  62278. this._texture = this.getScene().getEngine().createRawCubeTextureFromUrl(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  62279. };
  62280. /**
  62281. * Starts the loading process of the texture.
  62282. */
  62283. HDRCubeTexture.prototype.loadTexture = function () {
  62284. if (this._isBABYLONPreprocessed) {
  62285. this.loadBabylonTexture();
  62286. }
  62287. else {
  62288. this.loadHDRTexture();
  62289. }
  62290. };
  62291. HDRCubeTexture.prototype.clone = function () {
  62292. var size = this._isBABYLONPreprocessed ? null : this._size;
  62293. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  62294. // Base texture
  62295. newTexture.level = this.level;
  62296. newTexture.wrapU = this.wrapU;
  62297. newTexture.wrapV = this.wrapV;
  62298. newTexture.coordinatesIndex = this.coordinatesIndex;
  62299. newTexture.coordinatesMode = this.coordinatesMode;
  62300. return newTexture;
  62301. };
  62302. // Methods
  62303. HDRCubeTexture.prototype.delayLoad = function () {
  62304. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  62305. return;
  62306. }
  62307. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  62308. this._texture = this._getFromCache(this.url, this._noMipmap);
  62309. if (!this._texture) {
  62310. this.loadTexture();
  62311. }
  62312. };
  62313. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  62314. return this._textureMatrix;
  62315. };
  62316. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  62317. this._textureMatrix = value;
  62318. };
  62319. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  62320. var texture = null;
  62321. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  62322. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  62323. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  62324. texture.name = parsedTexture.name;
  62325. texture.hasAlpha = parsedTexture.hasAlpha;
  62326. texture.level = parsedTexture.level;
  62327. texture.coordinatesMode = parsedTexture.coordinatesMode;
  62328. texture.isBlocking = parsedTexture.isBlocking;
  62329. }
  62330. return texture;
  62331. };
  62332. HDRCubeTexture.prototype.serialize = function () {
  62333. if (!this.name) {
  62334. return null;
  62335. }
  62336. var serializationObject = {};
  62337. serializationObject.name = this.name;
  62338. serializationObject.hasAlpha = this.hasAlpha;
  62339. serializationObject.isCube = true;
  62340. serializationObject.level = this.level;
  62341. serializationObject.size = this._size;
  62342. serializationObject.coordinatesMode = this.coordinatesMode;
  62343. serializationObject.useInGammaSpace = this._useInGammaSpace;
  62344. serializationObject.generateHarmonics = this._generateHarmonics;
  62345. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  62346. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  62347. serializationObject.customType = "BABYLON.HDRCubeTexture";
  62348. serializationObject.noMipmap = this._noMipmap;
  62349. serializationObject.isBlocking = this._isBlocking;
  62350. return serializationObject;
  62351. };
  62352. /**
  62353. * Saves as a file the data contained in the texture in a binary format.
  62354. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  62355. * as the spherical used in the lighting.
  62356. * @param url The HDR file url.
  62357. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  62358. * @param onError Method called if any error happens during download.
  62359. * @return The packed binary data.
  62360. */
  62361. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  62362. if (onError === void 0) { onError = null; }
  62363. var callback = function (buffer) {
  62364. var data = new Blob([buffer], { type: 'application/octet-stream' });
  62365. // Returns a URL you can use as a href.
  62366. var objUrl = window.URL.createObjectURL(data);
  62367. // Simulates a link to it and click to dowload.
  62368. var a = document.createElement("a");
  62369. document.body.appendChild(a);
  62370. a.style.display = "none";
  62371. a.href = objUrl;
  62372. a.download = "envmap.babylon.hdr";
  62373. a.click();
  62374. };
  62375. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  62376. };
  62377. /**
  62378. * Serializes the data contained in the texture in a binary format.
  62379. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  62380. * as the spherical used in the lighting.
  62381. * @param url The HDR file url.
  62382. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  62383. * @param onError Method called if any error happens during download.
  62384. * @return The packed binary data.
  62385. */
  62386. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  62387. if (onError === void 0) { onError = null; }
  62388. // Needs the url tho create the texture.
  62389. if (!url) {
  62390. return null;
  62391. }
  62392. // Check Power of two size.
  62393. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  62394. return null;
  62395. }
  62396. // Coming Back in 3.1.
  62397. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  62398. return null;
  62399. };
  62400. HDRCubeTexture._facesMapping = [
  62401. "right",
  62402. "left",
  62403. "up",
  62404. "down",
  62405. "front",
  62406. "back"
  62407. ];
  62408. return HDRCubeTexture;
  62409. }(BABYLON.BaseTexture));
  62410. BABYLON.HDRCubeTexture = HDRCubeTexture;
  62411. })(BABYLON || (BABYLON = {}));
  62412. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  62413. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  62414. // Huge respect for a such great lib.
  62415. // Earcut license:
  62416. // Copyright (c) 2016, Mapbox
  62417. //
  62418. // Permission to use, copy, modify, and/or distribute this software for any purpose
  62419. // with or without fee is hereby granted, provided that the above copyright notice
  62420. // and this permission notice appear in all copies.
  62421. //
  62422. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  62423. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  62424. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  62425. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  62426. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  62427. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  62428. // THIS SOFTWARE.
  62429. var Earcut;
  62430. (function (Earcut) {
  62431. /**
  62432. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  62433. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  62434. * @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).
  62435. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  62436. */
  62437. function earcut(data, holeIndices, dim) {
  62438. dim = dim || 2;
  62439. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  62440. if (!outerNode)
  62441. return triangles;
  62442. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  62443. if (hasHoles)
  62444. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  62445. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  62446. if (data.length > 80 * dim) {
  62447. minX = maxX = data[0];
  62448. minY = maxY = data[1];
  62449. for (var i = dim; i < outerLen; i += dim) {
  62450. x = data[i];
  62451. y = data[i + 1];
  62452. if (x < minX)
  62453. minX = x;
  62454. if (y < minY)
  62455. minY = y;
  62456. if (x > maxX)
  62457. maxX = x;
  62458. if (y > maxY)
  62459. maxY = y;
  62460. }
  62461. // minX, minY and size are later used to transform coords into integers for z-order calculation
  62462. size = Math.max(maxX - minX, maxY - minY);
  62463. }
  62464. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  62465. return triangles;
  62466. }
  62467. Earcut.earcut = earcut;
  62468. var Node = /** @class */ (function () {
  62469. function Node(i, x, y) {
  62470. this.i = i;
  62471. this.x = x;
  62472. this.y = y;
  62473. this.prev = null;
  62474. this.next = null;
  62475. this.z = null;
  62476. this.prevZ = null;
  62477. this.nextZ = null;
  62478. this.steiner = false;
  62479. }
  62480. return Node;
  62481. }());
  62482. // create a circular doubly linked list from polygon points in the specified winding order
  62483. function linkedList(data, start, end, dim, clockwise) {
  62484. var i, last = null;
  62485. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  62486. for (i = start; i < end; i += dim)
  62487. last = insertNode(i, data[i], data[i + 1], last);
  62488. }
  62489. else {
  62490. for (i = end - dim; i >= start; i -= dim)
  62491. last = insertNode(i, data[i], data[i + 1], last);
  62492. }
  62493. if (last && equals(last, last.next)) {
  62494. removeNode(last);
  62495. last = last.next;
  62496. }
  62497. return last;
  62498. }
  62499. // eliminate colinear or duplicate points
  62500. function filterPoints(start, end) {
  62501. if (!start)
  62502. return start;
  62503. if (!end)
  62504. end = start;
  62505. var p = start, again;
  62506. do {
  62507. again = false;
  62508. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  62509. removeNode(p);
  62510. p = end = p.prev;
  62511. if (p === p.next)
  62512. return undefined;
  62513. again = true;
  62514. }
  62515. else {
  62516. p = p.next;
  62517. }
  62518. } while (again || p !== end);
  62519. return end;
  62520. }
  62521. // main ear slicing loop which triangulates a polygon (given as a linked list)
  62522. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  62523. if (!ear)
  62524. return;
  62525. // interlink polygon nodes in z-order
  62526. if (!pass && size)
  62527. indexCurve(ear, minX, minY, size);
  62528. var stop = ear, prev, next;
  62529. // iterate through ears, slicing them one by one
  62530. while (ear.prev !== ear.next) {
  62531. prev = ear.prev;
  62532. next = ear.next;
  62533. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  62534. // cut off the triangle
  62535. triangles.push(prev.i / dim);
  62536. triangles.push(ear.i / dim);
  62537. triangles.push(next.i / dim);
  62538. removeNode(ear);
  62539. // skipping the next vertice leads to less sliver triangles
  62540. ear = next.next;
  62541. stop = next.next;
  62542. continue;
  62543. }
  62544. ear = next;
  62545. // if we looped through the whole remaining polygon and can't find any more ears
  62546. if (ear === stop) {
  62547. // try filtering points and slicing again
  62548. if (!pass) {
  62549. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  62550. // if this didn't work, try curing all small self-intersections locally
  62551. }
  62552. else if (pass === 1) {
  62553. ear = cureLocalIntersections(ear, triangles, dim);
  62554. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  62555. // as a last resort, try splitting the remaining polygon into two
  62556. }
  62557. else if (pass === 2) {
  62558. splitEarcut(ear, triangles, dim, minX, minY, size);
  62559. }
  62560. break;
  62561. }
  62562. }
  62563. }
  62564. // check whether a polygon node forms a valid ear with adjacent nodes
  62565. function isEar(ear) {
  62566. var a = ear.prev, b = ear, c = ear.next;
  62567. if (area(a, b, c) >= 0)
  62568. return false; // reflex, can't be an ear
  62569. // now make sure we don't have other points inside the potential ear
  62570. var p = ear.next.next;
  62571. while (p !== ear.prev) {
  62572. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  62573. area(p.prev, p, p.next) >= 0)
  62574. return false;
  62575. p = p.next;
  62576. }
  62577. return true;
  62578. }
  62579. function isEarHashed(ear, minX, minY, size) {
  62580. var a = ear.prev, b = ear, c = ear.next;
  62581. if (area(a, b, c) >= 0)
  62582. return false; // reflex, can't be an ear
  62583. // triangle bbox; min & max are calculated like this for speed
  62584. 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);
  62585. // z-order range for the current triangle bbox;
  62586. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  62587. // first look for points inside the triangle in increasing z-order
  62588. var p = ear.nextZ;
  62589. while (p && p.z <= maxZ) {
  62590. if (p !== ear.prev &&
  62591. p !== ear.next &&
  62592. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  62593. area(p.prev, p, p.next) >= 0)
  62594. return false;
  62595. p = p.nextZ;
  62596. }
  62597. // then look for points in decreasing z-order
  62598. p = ear.prevZ;
  62599. while (p && p.z >= minZ) {
  62600. if (p !== ear.prev &&
  62601. p !== ear.next &&
  62602. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  62603. area(p.prev, p, p.next) >= 0)
  62604. return false;
  62605. p = p.prevZ;
  62606. }
  62607. return true;
  62608. }
  62609. // go through all polygon nodes and cure small local self-intersections
  62610. function cureLocalIntersections(start, triangles, dim) {
  62611. var p = start;
  62612. do {
  62613. var a = p.prev, b = p.next.next;
  62614. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  62615. triangles.push(a.i / dim);
  62616. triangles.push(p.i / dim);
  62617. triangles.push(b.i / dim);
  62618. // remove two nodes involved
  62619. removeNode(p);
  62620. removeNode(p.next);
  62621. p = start = b;
  62622. }
  62623. p = p.next;
  62624. } while (p !== start);
  62625. return p;
  62626. }
  62627. // try splitting polygon into two and triangulate them independently
  62628. function splitEarcut(start, triangles, dim, minX, minY, size) {
  62629. // look for a valid diagonal that divides the polygon into two
  62630. var a = start;
  62631. do {
  62632. var b = a.next.next;
  62633. while (b !== a.prev) {
  62634. if (a.i !== b.i && isValidDiagonal(a, b)) {
  62635. // split the polygon in two by the diagonal
  62636. var c = splitPolygon(a, b);
  62637. // filter colinear points around the cuts
  62638. a = filterPoints(a, a.next);
  62639. c = filterPoints(c, c.next);
  62640. // run earcut on each half
  62641. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  62642. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  62643. return;
  62644. }
  62645. b = b.next;
  62646. }
  62647. a = a.next;
  62648. } while (a !== start);
  62649. }
  62650. // link every hole into the outer loop, producing a single-ring polygon without holes
  62651. function eliminateHoles(data, holeIndices, outerNode, dim) {
  62652. var queue = [], i, len, start, end, list;
  62653. for (i = 0, len = holeIndices.length; i < len; i++) {
  62654. start = holeIndices[i] * dim;
  62655. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  62656. list = linkedList(data, start, end, dim, false);
  62657. if (list === list.next)
  62658. list.steiner = true;
  62659. queue.push(getLeftmost(list));
  62660. }
  62661. queue.sort(compareX);
  62662. // process holes from left to right
  62663. for (i = 0; i < queue.length; i++) {
  62664. eliminateHole(queue[i], outerNode);
  62665. outerNode = filterPoints(outerNode, outerNode.next);
  62666. }
  62667. return outerNode;
  62668. }
  62669. function compareX(a, b) {
  62670. return a.x - b.x;
  62671. }
  62672. // find a bridge between vertices that connects hole with an outer ring and and link it
  62673. function eliminateHole(hole, outerNode) {
  62674. outerNode = findHoleBridge(hole, outerNode);
  62675. if (outerNode) {
  62676. var b = splitPolygon(outerNode, hole);
  62677. filterPoints(b, b.next);
  62678. }
  62679. }
  62680. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  62681. function findHoleBridge(hole, outerNode) {
  62682. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  62683. // find a segment intersected by a ray from the hole's leftmost point to the left;
  62684. // segment's endpoint with lesser x will be potential connection point
  62685. do {
  62686. if (hy <= p.y && hy >= p.next.y) {
  62687. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  62688. if (x <= hx && x > qx) {
  62689. qx = x;
  62690. if (x === hx) {
  62691. if (hy === p.y)
  62692. return p;
  62693. if (hy === p.next.y)
  62694. return p.next;
  62695. }
  62696. m = p.x < p.next.x ? p : p.next;
  62697. }
  62698. }
  62699. p = p.next;
  62700. } while (p !== outerNode);
  62701. if (!m)
  62702. return null;
  62703. if (hx === qx)
  62704. return m.prev; // hole touches outer segment; pick lower endpoint
  62705. // look for points inside the triangle of hole point, segment intersection and endpoint;
  62706. // if there are no points found, we have a valid connection;
  62707. // otherwise choose the point of the minimum angle with the ray as connection point
  62708. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  62709. p = m.next;
  62710. while (p !== stop) {
  62711. if (hx >= p.x &&
  62712. p.x >= mx &&
  62713. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  62714. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  62715. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  62716. m = p;
  62717. tanMin = tan;
  62718. }
  62719. }
  62720. p = p.next;
  62721. }
  62722. return m;
  62723. }
  62724. // interlink polygon nodes in z-order
  62725. function indexCurve(start, minX, minY, size) {
  62726. var p = start;
  62727. do {
  62728. if (p.z === null)
  62729. p.z = zOrder(p.x, p.y, minX, minY, size);
  62730. p.prevZ = p.prev;
  62731. p.nextZ = p.next;
  62732. p = p.next;
  62733. } while (p !== start);
  62734. p.prevZ.nextZ = null;
  62735. p.prevZ = null;
  62736. sortLinked(p);
  62737. }
  62738. // Simon Tatham's linked list merge sort algorithm
  62739. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  62740. function sortLinked(list) {
  62741. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  62742. do {
  62743. p = list;
  62744. list = null;
  62745. tail = null;
  62746. numMerges = 0;
  62747. while (p) {
  62748. numMerges++;
  62749. q = p;
  62750. pSize = 0;
  62751. for (i = 0; i < inSize; i++) {
  62752. pSize++;
  62753. q = q.nextZ;
  62754. if (!q)
  62755. break;
  62756. }
  62757. qSize = inSize;
  62758. while (pSize > 0 || (qSize > 0 && q)) {
  62759. if (pSize === 0) {
  62760. e = q;
  62761. q = q.nextZ;
  62762. qSize--;
  62763. }
  62764. else if (qSize === 0 || !q) {
  62765. e = p;
  62766. p = p.nextZ;
  62767. pSize--;
  62768. }
  62769. else if (p.z <= q.z) {
  62770. e = p;
  62771. p = p.nextZ;
  62772. pSize--;
  62773. }
  62774. else {
  62775. e = q;
  62776. q = q.nextZ;
  62777. qSize--;
  62778. }
  62779. if (tail)
  62780. tail.nextZ = e;
  62781. else
  62782. list = e;
  62783. e.prevZ = tail;
  62784. tail = e;
  62785. }
  62786. p = q;
  62787. }
  62788. tail.nextZ = null;
  62789. inSize *= 2;
  62790. } while (numMerges > 1);
  62791. return list;
  62792. }
  62793. // z-order of a point given coords and size of the data bounding box
  62794. function zOrder(x, y, minX, minY, size) {
  62795. // coords are transformed into non-negative 15-bit integer range
  62796. x = 32767 * (x - minX) / size;
  62797. y = 32767 * (y - minY) / size;
  62798. x = (x | (x << 8)) & 0x00FF00FF;
  62799. x = (x | (x << 4)) & 0x0F0F0F0F;
  62800. x = (x | (x << 2)) & 0x33333333;
  62801. x = (x | (x << 1)) & 0x55555555;
  62802. y = (y | (y << 8)) & 0x00FF00FF;
  62803. y = (y | (y << 4)) & 0x0F0F0F0F;
  62804. y = (y | (y << 2)) & 0x33333333;
  62805. y = (y | (y << 1)) & 0x55555555;
  62806. return x | (y << 1);
  62807. }
  62808. // find the leftmost node of a polygon ring
  62809. function getLeftmost(start) {
  62810. var p = start, leftmost = start;
  62811. do {
  62812. if (p.x < leftmost.x)
  62813. leftmost = p;
  62814. p = p.next;
  62815. } while (p !== start);
  62816. return leftmost;
  62817. }
  62818. // check if a point lies within a convex triangle
  62819. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  62820. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  62821. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  62822. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  62823. }
  62824. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  62825. function isValidDiagonal(a, b) {
  62826. return a.next.i !== b.i &&
  62827. a.prev.i !== b.i &&
  62828. !intersectsPolygon(a, b) &&
  62829. locallyInside(a, b) &&
  62830. locallyInside(b, a) &&
  62831. middleInside(a, b);
  62832. }
  62833. // signed area of a triangle
  62834. function area(p, q, r) {
  62835. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  62836. }
  62837. // check if two points are equal
  62838. function equals(p1, p2) {
  62839. return p1.x === p2.x && p1.y === p2.y;
  62840. }
  62841. // check if two segments intersect
  62842. function intersects(p1, q1, p2, q2) {
  62843. if ((equals(p1, q1) && equals(p2, q2)) ||
  62844. (equals(p1, q2) && equals(p2, q1)))
  62845. return true;
  62846. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  62847. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  62848. }
  62849. // check if a polygon diagonal intersects any polygon segments
  62850. function intersectsPolygon(a, b) {
  62851. var p = a;
  62852. do {
  62853. if (p.i !== a.i &&
  62854. p.next.i !== a.i &&
  62855. p.i !== b.i &&
  62856. p.next.i !== b.i &&
  62857. intersects(p, p.next, a, b))
  62858. return true;
  62859. p = p.next;
  62860. } while (p !== a);
  62861. return false;
  62862. }
  62863. // check if a polygon diagonal is locally inside the polygon
  62864. function locallyInside(a, b) {
  62865. return area(a.prev, a, a.next) < 0
  62866. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  62867. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  62868. }
  62869. // check if the middle point of a polygon diagonal is inside the polygon
  62870. function middleInside(a, b) {
  62871. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  62872. do {
  62873. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  62874. inside = !inside;
  62875. p = p.next;
  62876. } while (p !== a);
  62877. return inside;
  62878. }
  62879. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  62880. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  62881. function splitPolygon(a, b) {
  62882. 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;
  62883. a.next = b;
  62884. b.prev = a;
  62885. a2.next = an;
  62886. an.prev = a2;
  62887. b2.next = a2;
  62888. a2.prev = b2;
  62889. bp.next = b2;
  62890. b2.prev = bp;
  62891. return b2;
  62892. }
  62893. // create a node and optionally link it with previous one (in a circular doubly linked list)
  62894. function insertNode(i, x, y, last) {
  62895. var p = new Node(i, x, y);
  62896. if (!last) {
  62897. p.prev = p;
  62898. p.next = p;
  62899. }
  62900. else {
  62901. p.next = last.next;
  62902. p.prev = last;
  62903. last.next.prev = p;
  62904. last.next = p;
  62905. }
  62906. return p;
  62907. }
  62908. function removeNode(p) {
  62909. p.next.prev = p.prev;
  62910. p.prev.next = p.next;
  62911. if (p.prevZ)
  62912. p.prevZ.nextZ = p.nextZ;
  62913. if (p.nextZ)
  62914. p.nextZ.prevZ = p.prevZ;
  62915. }
  62916. /**
  62917. * return a percentage difference between the polygon area and its triangulation area;
  62918. * used to verify correctness of triangulation
  62919. */
  62920. function deviation(data, holeIndices, dim, triangles) {
  62921. var hasHoles = holeIndices && holeIndices.length;
  62922. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  62923. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  62924. if (hasHoles) {
  62925. for (var i = 0, len = holeIndices.length; i < len; i++) {
  62926. var start = holeIndices[i] * dim;
  62927. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  62928. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  62929. }
  62930. }
  62931. var trianglesArea = 0;
  62932. for (i = 0; i < triangles.length; i += 3) {
  62933. var a = triangles[i] * dim;
  62934. var b = triangles[i + 1] * dim;
  62935. var c = triangles[i + 2] * dim;
  62936. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  62937. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  62938. }
  62939. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  62940. }
  62941. Earcut.deviation = deviation;
  62942. ;
  62943. function signedArea(data, start, end, dim) {
  62944. var sum = 0;
  62945. for (var i = start, j = end - dim; i < end; i += dim) {
  62946. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  62947. j = i;
  62948. }
  62949. return sum;
  62950. }
  62951. /**
  62952. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  62953. */
  62954. function flatten(data) {
  62955. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  62956. for (var i = 0; i < data.length; i++) {
  62957. for (var j = 0; j < data[i].length; j++) {
  62958. for (var d = 0; d < dim; d++)
  62959. result.vertices.push(data[i][j][d]);
  62960. }
  62961. if (i > 0) {
  62962. holeIndex += data[i - 1].length;
  62963. result.holes.push(holeIndex);
  62964. }
  62965. }
  62966. return result;
  62967. }
  62968. Earcut.flatten = flatten;
  62969. ;
  62970. })(Earcut || (Earcut = {}));
  62971. //# sourceMappingURL=babylon.earcut.js.map
  62972. /// <reference path="..\Math\babylon.math.ts" />
  62973. var BABYLON;
  62974. (function (BABYLON) {
  62975. var IndexedVector2 = /** @class */ (function (_super) {
  62976. __extends(IndexedVector2, _super);
  62977. function IndexedVector2(original, index) {
  62978. var _this = _super.call(this, original.x, original.y) || this;
  62979. _this.index = index;
  62980. return _this;
  62981. }
  62982. return IndexedVector2;
  62983. }(BABYLON.Vector2));
  62984. var PolygonPoints = /** @class */ (function () {
  62985. function PolygonPoints() {
  62986. this.elements = new Array();
  62987. }
  62988. PolygonPoints.prototype.add = function (originalPoints) {
  62989. var _this = this;
  62990. var result = new Array();
  62991. originalPoints.forEach(function (point) {
  62992. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  62993. var newPoint = new IndexedVector2(point, _this.elements.length);
  62994. result.push(newPoint);
  62995. _this.elements.push(newPoint);
  62996. }
  62997. });
  62998. return result;
  62999. };
  63000. PolygonPoints.prototype.computeBounds = function () {
  63001. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  63002. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  63003. this.elements.forEach(function (point) {
  63004. // x
  63005. if (point.x < lmin.x) {
  63006. lmin.x = point.x;
  63007. }
  63008. else if (point.x > lmax.x) {
  63009. lmax.x = point.x;
  63010. }
  63011. // y
  63012. if (point.y < lmin.y) {
  63013. lmin.y = point.y;
  63014. }
  63015. else if (point.y > lmax.y) {
  63016. lmax.y = point.y;
  63017. }
  63018. });
  63019. return {
  63020. min: lmin,
  63021. max: lmax,
  63022. width: lmax.x - lmin.x,
  63023. height: lmax.y - lmin.y
  63024. };
  63025. };
  63026. return PolygonPoints;
  63027. }());
  63028. var Polygon = /** @class */ (function () {
  63029. function Polygon() {
  63030. }
  63031. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  63032. return [
  63033. new BABYLON.Vector2(xmin, ymin),
  63034. new BABYLON.Vector2(xmax, ymin),
  63035. new BABYLON.Vector2(xmax, ymax),
  63036. new BABYLON.Vector2(xmin, ymax)
  63037. ];
  63038. };
  63039. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  63040. if (cx === void 0) { cx = 0; }
  63041. if (cy === void 0) { cy = 0; }
  63042. if (numberOfSides === void 0) { numberOfSides = 32; }
  63043. var result = new Array();
  63044. var angle = 0;
  63045. var increment = (Math.PI * 2) / numberOfSides;
  63046. for (var i = 0; i < numberOfSides; i++) {
  63047. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  63048. angle -= increment;
  63049. }
  63050. return result;
  63051. };
  63052. Polygon.Parse = function (input) {
  63053. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  63054. var i, result = [];
  63055. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  63056. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  63057. }
  63058. return result;
  63059. };
  63060. Polygon.StartingAt = function (x, y) {
  63061. return BABYLON.Path2.StartingAt(x, y);
  63062. };
  63063. return Polygon;
  63064. }());
  63065. BABYLON.Polygon = Polygon;
  63066. var PolygonMeshBuilder = /** @class */ (function () {
  63067. function PolygonMeshBuilder(name, contours, scene) {
  63068. this._points = new PolygonPoints();
  63069. this._outlinepoints = new PolygonPoints();
  63070. this._holes = new Array();
  63071. this._epoints = new Array();
  63072. this._eholes = new Array();
  63073. this._name = name;
  63074. this._scene = scene;
  63075. var points;
  63076. if (contours instanceof BABYLON.Path2) {
  63077. points = contours.getPoints();
  63078. }
  63079. else {
  63080. points = contours;
  63081. }
  63082. this._addToepoint(points);
  63083. this._points.add(points);
  63084. this._outlinepoints.add(points);
  63085. }
  63086. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  63087. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  63088. var p = points_1[_i];
  63089. this._epoints.push(p.x, p.y);
  63090. }
  63091. };
  63092. PolygonMeshBuilder.prototype.addHole = function (hole) {
  63093. this._points.add(hole);
  63094. var holepoints = new PolygonPoints();
  63095. holepoints.add(hole);
  63096. this._holes.push(holepoints);
  63097. this._eholes.push(this._epoints.length / 2);
  63098. this._addToepoint(hole);
  63099. return this;
  63100. };
  63101. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  63102. var _this = this;
  63103. if (updatable === void 0) { updatable = false; }
  63104. var result = new BABYLON.Mesh(this._name, this._scene);
  63105. var normals = new Array();
  63106. var positions = new Array();
  63107. var uvs = new Array();
  63108. var bounds = this._points.computeBounds();
  63109. this._points.elements.forEach(function (p) {
  63110. normals.push(0, 1.0, 0);
  63111. positions.push(p.x, 0, p.y);
  63112. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  63113. });
  63114. var indices = new Array();
  63115. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  63116. for (var i = 0; i < res.length; i++) {
  63117. indices.push(res[i]);
  63118. }
  63119. if (depth > 0) {
  63120. var positionscount = (positions.length / 3); //get the current pointcount
  63121. this._points.elements.forEach(function (p) {
  63122. normals.push(0, -1.0, 0);
  63123. positions.push(p.x, -depth, p.y);
  63124. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  63125. });
  63126. var totalCount = indices.length;
  63127. for (var i = 0; i < totalCount; i += 3) {
  63128. var i0 = indices[i + 0];
  63129. var i1 = indices[i + 1];
  63130. var i2 = indices[i + 2];
  63131. indices.push(i2 + positionscount);
  63132. indices.push(i1 + positionscount);
  63133. indices.push(i0 + positionscount);
  63134. }
  63135. //Add the sides
  63136. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  63137. this._holes.forEach(function (hole) {
  63138. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  63139. });
  63140. }
  63141. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  63142. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  63143. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  63144. result.setIndices(indices);
  63145. return result;
  63146. };
  63147. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  63148. var StartIndex = positions.length / 3;
  63149. var ulength = 0;
  63150. for (var i = 0; i < points.elements.length; i++) {
  63151. var p = points.elements[i];
  63152. var p1;
  63153. if ((i + 1) > points.elements.length - 1) {
  63154. p1 = points.elements[0];
  63155. }
  63156. else {
  63157. p1 = points.elements[i + 1];
  63158. }
  63159. positions.push(p.x, 0, p.y);
  63160. positions.push(p.x, -depth, p.y);
  63161. positions.push(p1.x, 0, p1.y);
  63162. positions.push(p1.x, -depth, p1.y);
  63163. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  63164. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  63165. var v3 = v2.subtract(v1);
  63166. var v4 = new BABYLON.Vector3(0, 1, 0);
  63167. var vn = BABYLON.Vector3.Cross(v3, v4);
  63168. vn = vn.normalize();
  63169. uvs.push(ulength / bounds.width, 0);
  63170. uvs.push(ulength / bounds.width, 1);
  63171. ulength += v3.length();
  63172. uvs.push((ulength / bounds.width), 0);
  63173. uvs.push((ulength / bounds.width), 1);
  63174. if (!flip) {
  63175. normals.push(-vn.x, -vn.y, -vn.z);
  63176. normals.push(-vn.x, -vn.y, -vn.z);
  63177. normals.push(-vn.x, -vn.y, -vn.z);
  63178. normals.push(-vn.x, -vn.y, -vn.z);
  63179. indices.push(StartIndex);
  63180. indices.push(StartIndex + 1);
  63181. indices.push(StartIndex + 2);
  63182. indices.push(StartIndex + 1);
  63183. indices.push(StartIndex + 3);
  63184. indices.push(StartIndex + 2);
  63185. }
  63186. else {
  63187. normals.push(vn.x, vn.y, vn.z);
  63188. normals.push(vn.x, vn.y, vn.z);
  63189. normals.push(vn.x, vn.y, vn.z);
  63190. normals.push(vn.x, vn.y, vn.z);
  63191. indices.push(StartIndex);
  63192. indices.push(StartIndex + 2);
  63193. indices.push(StartIndex + 1);
  63194. indices.push(StartIndex + 1);
  63195. indices.push(StartIndex + 2);
  63196. indices.push(StartIndex + 3);
  63197. }
  63198. StartIndex += 4;
  63199. }
  63200. ;
  63201. };
  63202. return PolygonMeshBuilder;
  63203. }());
  63204. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  63205. })(BABYLON || (BABYLON = {}));
  63206. //# sourceMappingURL=babylon.polygonMesh.js.map
  63207. var BABYLON;
  63208. (function (BABYLON) {
  63209. // Unique ID when we import meshes from Babylon to CSG
  63210. var currentCSGMeshId = 0;
  63211. // # class Vertex
  63212. // Represents a vertex of a polygon. Use your own vertex class instead of this
  63213. // one to provide additional features like texture coordinates and vertex
  63214. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  63215. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  63216. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  63217. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  63218. // is not used anywhere else.
  63219. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  63220. var Vertex = /** @class */ (function () {
  63221. function Vertex(pos, normal, uv) {
  63222. this.pos = pos;
  63223. this.normal = normal;
  63224. this.uv = uv;
  63225. }
  63226. Vertex.prototype.clone = function () {
  63227. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  63228. };
  63229. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  63230. // orientation of a polygon is flipped.
  63231. Vertex.prototype.flip = function () {
  63232. this.normal = this.normal.scale(-1);
  63233. };
  63234. // Create a new vertex between this vertex and `other` by linearly
  63235. // interpolating all properties using a parameter of `t`. Subclasses should
  63236. // override this to interpolate additional properties.
  63237. Vertex.prototype.interpolate = function (other, t) {
  63238. 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));
  63239. };
  63240. return Vertex;
  63241. }());
  63242. // # class Plane
  63243. // Represents a plane in 3D space.
  63244. var Plane = /** @class */ (function () {
  63245. function Plane(normal, w) {
  63246. this.normal = normal;
  63247. this.w = w;
  63248. }
  63249. Plane.FromPoints = function (a, b, c) {
  63250. var v0 = c.subtract(a);
  63251. var v1 = b.subtract(a);
  63252. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  63253. return null;
  63254. }
  63255. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  63256. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  63257. };
  63258. Plane.prototype.clone = function () {
  63259. return new Plane(this.normal.clone(), this.w);
  63260. };
  63261. Plane.prototype.flip = function () {
  63262. this.normal.scaleInPlace(-1);
  63263. this.w = -this.w;
  63264. };
  63265. // Split `polygon` by this plane if needed, then put the polygon or polygon
  63266. // fragments in the appropriate lists. Coplanar polygons go into either
  63267. // `coplanarFront` or `coplanarBack` depending on their orientation with
  63268. // respect to this plane. Polygons in front or in back of this plane go into
  63269. // either `front` or `back`.
  63270. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  63271. var COPLANAR = 0;
  63272. var FRONT = 1;
  63273. var BACK = 2;
  63274. var SPANNING = 3;
  63275. // Classify each point as well as the entire polygon into one of the above
  63276. // four classes.
  63277. var polygonType = 0;
  63278. var types = [];
  63279. var i;
  63280. var t;
  63281. for (i = 0; i < polygon.vertices.length; i++) {
  63282. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  63283. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  63284. polygonType |= type;
  63285. types.push(type);
  63286. }
  63287. // Put the polygon in the correct list, splitting it when necessary.
  63288. switch (polygonType) {
  63289. case COPLANAR:
  63290. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  63291. break;
  63292. case FRONT:
  63293. front.push(polygon);
  63294. break;
  63295. case BACK:
  63296. back.push(polygon);
  63297. break;
  63298. case SPANNING:
  63299. var f = [], b = [];
  63300. for (i = 0; i < polygon.vertices.length; i++) {
  63301. var j = (i + 1) % polygon.vertices.length;
  63302. var ti = types[i], tj = types[j];
  63303. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  63304. if (ti !== BACK)
  63305. f.push(vi);
  63306. if (ti !== FRONT)
  63307. b.push(ti !== BACK ? vi.clone() : vi);
  63308. if ((ti | tj) === SPANNING) {
  63309. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  63310. var v = vi.interpolate(vj, t);
  63311. f.push(v);
  63312. b.push(v.clone());
  63313. }
  63314. }
  63315. var poly;
  63316. if (f.length >= 3) {
  63317. poly = new Polygon(f, polygon.shared);
  63318. if (poly.plane)
  63319. front.push(poly);
  63320. }
  63321. if (b.length >= 3) {
  63322. poly = new Polygon(b, polygon.shared);
  63323. if (poly.plane)
  63324. back.push(poly);
  63325. }
  63326. break;
  63327. }
  63328. };
  63329. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  63330. // point is on the plane.
  63331. Plane.EPSILON = 1e-5;
  63332. return Plane;
  63333. }());
  63334. // # class Polygon
  63335. // Represents a convex polygon. The vertices used to initialize a polygon must
  63336. // be coplanar and form a convex loop.
  63337. //
  63338. // Each convex polygon has a `shared` property, which is shared between all
  63339. // polygons that are clones of each other or were split from the same polygon.
  63340. // This can be used to define per-polygon properties (such as surface color).
  63341. var Polygon = /** @class */ (function () {
  63342. function Polygon(vertices, shared) {
  63343. this.vertices = vertices;
  63344. this.shared = shared;
  63345. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  63346. }
  63347. Polygon.prototype.clone = function () {
  63348. var vertices = this.vertices.map(function (v) { return v.clone(); });
  63349. return new Polygon(vertices, this.shared);
  63350. };
  63351. Polygon.prototype.flip = function () {
  63352. this.vertices.reverse().map(function (v) { v.flip(); });
  63353. this.plane.flip();
  63354. };
  63355. return Polygon;
  63356. }());
  63357. // # class Node
  63358. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  63359. // by picking a polygon to split along. That polygon (and all other coplanar
  63360. // polygons) are added directly to that node and the other polygons are added to
  63361. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  63362. // no distinction between internal and leaf nodes.
  63363. var Node = /** @class */ (function () {
  63364. function Node(polygons) {
  63365. this.plane = null;
  63366. this.front = null;
  63367. this.back = null;
  63368. this.polygons = new Array();
  63369. if (polygons) {
  63370. this.build(polygons);
  63371. }
  63372. }
  63373. Node.prototype.clone = function () {
  63374. var node = new Node();
  63375. node.plane = this.plane && this.plane.clone();
  63376. node.front = this.front && this.front.clone();
  63377. node.back = this.back && this.back.clone();
  63378. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  63379. return node;
  63380. };
  63381. // Convert solid space to empty space and empty space to solid space.
  63382. Node.prototype.invert = function () {
  63383. for (var i = 0; i < this.polygons.length; i++) {
  63384. this.polygons[i].flip();
  63385. }
  63386. if (this.plane) {
  63387. this.plane.flip();
  63388. }
  63389. if (this.front) {
  63390. this.front.invert();
  63391. }
  63392. if (this.back) {
  63393. this.back.invert();
  63394. }
  63395. var temp = this.front;
  63396. this.front = this.back;
  63397. this.back = temp;
  63398. };
  63399. // Recursively remove all polygons in `polygons` that are inside this BSP
  63400. // tree.
  63401. Node.prototype.clipPolygons = function (polygons) {
  63402. if (!this.plane)
  63403. return polygons.slice();
  63404. var front = new Array(), back = new Array();
  63405. for (var i = 0; i < polygons.length; i++) {
  63406. this.plane.splitPolygon(polygons[i], front, back, front, back);
  63407. }
  63408. if (this.front) {
  63409. front = this.front.clipPolygons(front);
  63410. }
  63411. if (this.back) {
  63412. back = this.back.clipPolygons(back);
  63413. }
  63414. else {
  63415. back = [];
  63416. }
  63417. return front.concat(back);
  63418. };
  63419. // Remove all polygons in this BSP tree that are inside the other BSP tree
  63420. // `bsp`.
  63421. Node.prototype.clipTo = function (bsp) {
  63422. this.polygons = bsp.clipPolygons(this.polygons);
  63423. if (this.front)
  63424. this.front.clipTo(bsp);
  63425. if (this.back)
  63426. this.back.clipTo(bsp);
  63427. };
  63428. // Return a list of all polygons in this BSP tree.
  63429. Node.prototype.allPolygons = function () {
  63430. var polygons = this.polygons.slice();
  63431. if (this.front)
  63432. polygons = polygons.concat(this.front.allPolygons());
  63433. if (this.back)
  63434. polygons = polygons.concat(this.back.allPolygons());
  63435. return polygons;
  63436. };
  63437. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  63438. // new polygons are filtered down to the bottom of the tree and become new
  63439. // nodes there. Each set of polygons is partitioned using the first polygon
  63440. // (no heuristic is used to pick a good split).
  63441. Node.prototype.build = function (polygons) {
  63442. if (!polygons.length)
  63443. return;
  63444. if (!this.plane)
  63445. this.plane = polygons[0].plane.clone();
  63446. var front = new Array(), back = new Array();
  63447. for (var i = 0; i < polygons.length; i++) {
  63448. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  63449. }
  63450. if (front.length) {
  63451. if (!this.front)
  63452. this.front = new Node();
  63453. this.front.build(front);
  63454. }
  63455. if (back.length) {
  63456. if (!this.back)
  63457. this.back = new Node();
  63458. this.back.build(back);
  63459. }
  63460. };
  63461. return Node;
  63462. }());
  63463. var CSG = /** @class */ (function () {
  63464. function CSG() {
  63465. this.polygons = new Array();
  63466. }
  63467. // Convert BABYLON.Mesh to BABYLON.CSG
  63468. CSG.FromMesh = function (mesh) {
  63469. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  63470. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  63471. if (mesh instanceof BABYLON.Mesh) {
  63472. mesh.computeWorldMatrix(true);
  63473. matrix = mesh.getWorldMatrix();
  63474. meshPosition = mesh.position.clone();
  63475. meshRotation = mesh.rotation.clone();
  63476. if (mesh.rotationQuaternion) {
  63477. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  63478. }
  63479. meshScaling = mesh.scaling.clone();
  63480. }
  63481. else {
  63482. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  63483. }
  63484. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  63485. var subMeshes = mesh.subMeshes;
  63486. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  63487. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  63488. vertices = [];
  63489. for (var j = 0; j < 3; j++) {
  63490. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  63491. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  63492. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  63493. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  63494. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  63495. vertex = new Vertex(position, normal, uv);
  63496. vertices.push(vertex);
  63497. }
  63498. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  63499. // To handle the case of degenerated triangle
  63500. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  63501. if (polygon.plane)
  63502. polygons.push(polygon);
  63503. }
  63504. }
  63505. var csg = CSG.FromPolygons(polygons);
  63506. csg.matrix = matrix;
  63507. csg.position = meshPosition;
  63508. csg.rotation = meshRotation;
  63509. csg.scaling = meshScaling;
  63510. csg.rotationQuaternion = meshRotationQuaternion;
  63511. currentCSGMeshId++;
  63512. return csg;
  63513. };
  63514. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  63515. CSG.FromPolygons = function (polygons) {
  63516. var csg = new CSG();
  63517. csg.polygons = polygons;
  63518. return csg;
  63519. };
  63520. CSG.prototype.clone = function () {
  63521. var csg = new CSG();
  63522. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  63523. csg.copyTransformAttributes(this);
  63524. return csg;
  63525. };
  63526. CSG.prototype.union = function (csg) {
  63527. var a = new Node(this.clone().polygons);
  63528. var b = new Node(csg.clone().polygons);
  63529. a.clipTo(b);
  63530. b.clipTo(a);
  63531. b.invert();
  63532. b.clipTo(a);
  63533. b.invert();
  63534. a.build(b.allPolygons());
  63535. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  63536. };
  63537. CSG.prototype.unionInPlace = function (csg) {
  63538. var a = new Node(this.polygons);
  63539. var b = new Node(csg.polygons);
  63540. a.clipTo(b);
  63541. b.clipTo(a);
  63542. b.invert();
  63543. b.clipTo(a);
  63544. b.invert();
  63545. a.build(b.allPolygons());
  63546. this.polygons = a.allPolygons();
  63547. };
  63548. CSG.prototype.subtract = function (csg) {
  63549. var a = new Node(this.clone().polygons);
  63550. var b = new Node(csg.clone().polygons);
  63551. a.invert();
  63552. a.clipTo(b);
  63553. b.clipTo(a);
  63554. b.invert();
  63555. b.clipTo(a);
  63556. b.invert();
  63557. a.build(b.allPolygons());
  63558. a.invert();
  63559. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  63560. };
  63561. CSG.prototype.subtractInPlace = function (csg) {
  63562. var a = new Node(this.polygons);
  63563. var b = new Node(csg.polygons);
  63564. a.invert();
  63565. a.clipTo(b);
  63566. b.clipTo(a);
  63567. b.invert();
  63568. b.clipTo(a);
  63569. b.invert();
  63570. a.build(b.allPolygons());
  63571. a.invert();
  63572. this.polygons = a.allPolygons();
  63573. };
  63574. CSG.prototype.intersect = function (csg) {
  63575. var a = new Node(this.clone().polygons);
  63576. var b = new Node(csg.clone().polygons);
  63577. a.invert();
  63578. b.clipTo(a);
  63579. b.invert();
  63580. a.clipTo(b);
  63581. b.clipTo(a);
  63582. a.build(b.allPolygons());
  63583. a.invert();
  63584. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  63585. };
  63586. CSG.prototype.intersectInPlace = function (csg) {
  63587. var a = new Node(this.polygons);
  63588. var b = new Node(csg.polygons);
  63589. a.invert();
  63590. b.clipTo(a);
  63591. b.invert();
  63592. a.clipTo(b);
  63593. b.clipTo(a);
  63594. a.build(b.allPolygons());
  63595. a.invert();
  63596. this.polygons = a.allPolygons();
  63597. };
  63598. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  63599. // not modified.
  63600. CSG.prototype.inverse = function () {
  63601. var csg = this.clone();
  63602. csg.inverseInPlace();
  63603. return csg;
  63604. };
  63605. CSG.prototype.inverseInPlace = function () {
  63606. this.polygons.map(function (p) { p.flip(); });
  63607. };
  63608. // This is used to keep meshes transformations so they can be restored
  63609. // when we build back a Babylon Mesh
  63610. // NB : All CSG operations are performed in world coordinates
  63611. CSG.prototype.copyTransformAttributes = function (csg) {
  63612. this.matrix = csg.matrix;
  63613. this.position = csg.position;
  63614. this.rotation = csg.rotation;
  63615. this.scaling = csg.scaling;
  63616. this.rotationQuaternion = csg.rotationQuaternion;
  63617. return this;
  63618. };
  63619. // Build Raw mesh from CSG
  63620. // Coordinates here are in world space
  63621. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  63622. var matrix = this.matrix.clone();
  63623. matrix.invert();
  63624. 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;
  63625. if (keepSubMeshes) {
  63626. // Sort Polygons, since subMeshes are indices range
  63627. polygons.sort(function (a, b) {
  63628. if (a.shared.meshId === b.shared.meshId) {
  63629. return a.shared.subMeshId - b.shared.subMeshId;
  63630. }
  63631. else {
  63632. return a.shared.meshId - b.shared.meshId;
  63633. }
  63634. });
  63635. }
  63636. for (var i = 0, il = polygons.length; i < il; i++) {
  63637. polygon = polygons[i];
  63638. // Building SubMeshes
  63639. if (!subMesh_dict[polygon.shared.meshId]) {
  63640. subMesh_dict[polygon.shared.meshId] = {};
  63641. }
  63642. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  63643. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  63644. indexStart: +Infinity,
  63645. indexEnd: -Infinity,
  63646. materialIndex: polygon.shared.materialIndex
  63647. };
  63648. }
  63649. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  63650. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  63651. polygonIndices[0] = 0;
  63652. polygonIndices[1] = j - 1;
  63653. polygonIndices[2] = j;
  63654. for (var k = 0; k < 3; k++) {
  63655. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  63656. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  63657. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  63658. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  63659. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  63660. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  63661. // Check if 2 points can be merged
  63662. if (!(typeof vertex_idx !== 'undefined' &&
  63663. normals[vertex_idx * 3] === localNormal.x &&
  63664. normals[vertex_idx * 3 + 1] === localNormal.y &&
  63665. normals[vertex_idx * 3 + 2] === localNormal.z &&
  63666. uvs[vertex_idx * 2] === uv.x &&
  63667. uvs[vertex_idx * 2 + 1] === uv.y)) {
  63668. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  63669. uvs.push(uv.x, uv.y);
  63670. normals.push(normal.x, normal.y, normal.z);
  63671. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  63672. }
  63673. indices.push(vertex_idx);
  63674. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  63675. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  63676. currentIndex++;
  63677. }
  63678. }
  63679. }
  63680. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  63681. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  63682. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  63683. mesh.setIndices(indices, null);
  63684. if (keepSubMeshes) {
  63685. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  63686. var materialIndexOffset = 0, materialMaxIndex;
  63687. mesh.subMeshes = new Array();
  63688. for (var m in subMesh_dict) {
  63689. materialMaxIndex = -1;
  63690. for (var sm in subMesh_dict[m]) {
  63691. subMesh_obj = subMesh_dict[m][sm];
  63692. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  63693. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  63694. }
  63695. materialIndexOffset += ++materialMaxIndex;
  63696. }
  63697. }
  63698. return mesh;
  63699. };
  63700. // Build Mesh from CSG taking material and transforms into account
  63701. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  63702. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  63703. mesh.material = material;
  63704. mesh.position.copyFrom(this.position);
  63705. mesh.rotation.copyFrom(this.rotation);
  63706. if (this.rotationQuaternion) {
  63707. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  63708. }
  63709. mesh.scaling.copyFrom(this.scaling);
  63710. mesh.computeWorldMatrix(true);
  63711. return mesh;
  63712. };
  63713. return CSG;
  63714. }());
  63715. BABYLON.CSG = CSG;
  63716. })(BABYLON || (BABYLON = {}));
  63717. //# sourceMappingURL=babylon.csg.js.map
  63718. var BABYLON;
  63719. (function (BABYLON) {
  63720. var LensFlare = /** @class */ (function () {
  63721. function LensFlare(size, position, color, imgUrl, system) {
  63722. this.size = size;
  63723. this.position = position;
  63724. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  63725. this.color = color || new BABYLON.Color3(1, 1, 1);
  63726. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  63727. this._system = system;
  63728. system.lensFlares.push(this);
  63729. }
  63730. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  63731. return new LensFlare(size, position, color, imgUrl, system);
  63732. };
  63733. LensFlare.prototype.dispose = function () {
  63734. if (this.texture) {
  63735. this.texture.dispose();
  63736. }
  63737. // Remove from scene
  63738. var index = this._system.lensFlares.indexOf(this);
  63739. this._system.lensFlares.splice(index, 1);
  63740. };
  63741. ;
  63742. return LensFlare;
  63743. }());
  63744. BABYLON.LensFlare = LensFlare;
  63745. })(BABYLON || (BABYLON = {}));
  63746. //# sourceMappingURL=babylon.lensFlare.js.map
  63747. var BABYLON;
  63748. (function (BABYLON) {
  63749. var LensFlareSystem = /** @class */ (function () {
  63750. function LensFlareSystem(name, emitter, scene) {
  63751. this.name = name;
  63752. this.lensFlares = new Array();
  63753. this.borderLimit = 300;
  63754. this.viewportBorder = 0;
  63755. this.layerMask = 0x0FFFFFFF;
  63756. this._vertexBuffers = {};
  63757. this._isEnabled = true;
  63758. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  63759. this._emitter = emitter;
  63760. this.id = name;
  63761. scene.lensFlareSystems.push(this);
  63762. this.meshesSelectionPredicate = function (m) { return scene.activeCamera !== null && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  63763. var engine = scene.getEngine();
  63764. // VBO
  63765. var vertices = [];
  63766. vertices.push(1, 1);
  63767. vertices.push(-1, 1);
  63768. vertices.push(-1, -1);
  63769. vertices.push(1, -1);
  63770. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  63771. // Indices
  63772. var indices = [];
  63773. indices.push(0);
  63774. indices.push(1);
  63775. indices.push(2);
  63776. indices.push(0);
  63777. indices.push(2);
  63778. indices.push(3);
  63779. this._indexBuffer = engine.createIndexBuffer(indices);
  63780. // Effects
  63781. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  63782. }
  63783. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  63784. get: function () {
  63785. return this._isEnabled;
  63786. },
  63787. set: function (value) {
  63788. this._isEnabled = value;
  63789. },
  63790. enumerable: true,
  63791. configurable: true
  63792. });
  63793. LensFlareSystem.prototype.getScene = function () {
  63794. return this._scene;
  63795. };
  63796. LensFlareSystem.prototype.getEmitter = function () {
  63797. return this._emitter;
  63798. };
  63799. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  63800. this._emitter = newEmitter;
  63801. };
  63802. LensFlareSystem.prototype.getEmitterPosition = function () {
  63803. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  63804. };
  63805. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  63806. var position = this.getEmitterPosition();
  63807. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  63808. this._positionX = position.x;
  63809. this._positionY = position.y;
  63810. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  63811. if (this.viewportBorder > 0) {
  63812. globalViewport.x -= this.viewportBorder;
  63813. globalViewport.y -= this.viewportBorder;
  63814. globalViewport.width += this.viewportBorder * 2;
  63815. globalViewport.height += this.viewportBorder * 2;
  63816. position.x += this.viewportBorder;
  63817. position.y += this.viewportBorder;
  63818. this._positionX += this.viewportBorder;
  63819. this._positionY += this.viewportBorder;
  63820. }
  63821. if (position.z > 0) {
  63822. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  63823. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  63824. return true;
  63825. }
  63826. return true;
  63827. }
  63828. return false;
  63829. };
  63830. LensFlareSystem.prototype._isVisible = function () {
  63831. if (!this._isEnabled || !this._scene.activeCamera) {
  63832. return false;
  63833. }
  63834. var emitterPosition = this.getEmitterPosition();
  63835. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  63836. var distance = direction.length();
  63837. direction.normalize();
  63838. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  63839. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  63840. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  63841. };
  63842. LensFlareSystem.prototype.render = function () {
  63843. if (!this._effect.isReady() || !this._scene.activeCamera)
  63844. return false;
  63845. var engine = this._scene.getEngine();
  63846. var viewport = this._scene.activeCamera.viewport;
  63847. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  63848. // Position
  63849. if (!this.computeEffectivePosition(globalViewport)) {
  63850. return false;
  63851. }
  63852. // Visibility
  63853. if (!this._isVisible()) {
  63854. return false;
  63855. }
  63856. // Intensity
  63857. var awayX;
  63858. var awayY;
  63859. if (this._positionX < this.borderLimit + globalViewport.x) {
  63860. awayX = this.borderLimit + globalViewport.x - this._positionX;
  63861. }
  63862. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  63863. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  63864. }
  63865. else {
  63866. awayX = 0;
  63867. }
  63868. if (this._positionY < this.borderLimit + globalViewport.y) {
  63869. awayY = this.borderLimit + globalViewport.y - this._positionY;
  63870. }
  63871. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  63872. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  63873. }
  63874. else {
  63875. awayY = 0;
  63876. }
  63877. var away = (awayX > awayY) ? awayX : awayY;
  63878. away -= this.viewportBorder;
  63879. if (away > this.borderLimit) {
  63880. away = this.borderLimit;
  63881. }
  63882. var intensity = 1.0 - (away / this.borderLimit);
  63883. if (intensity < 0) {
  63884. return false;
  63885. }
  63886. if (intensity > 1.0) {
  63887. intensity = 1.0;
  63888. }
  63889. if (this.viewportBorder > 0) {
  63890. globalViewport.x += this.viewportBorder;
  63891. globalViewport.y += this.viewportBorder;
  63892. globalViewport.width -= this.viewportBorder * 2;
  63893. globalViewport.height -= this.viewportBorder * 2;
  63894. this._positionX -= this.viewportBorder;
  63895. this._positionY -= this.viewportBorder;
  63896. }
  63897. // Position
  63898. var centerX = globalViewport.x + globalViewport.width / 2;
  63899. var centerY = globalViewport.y + globalViewport.height / 2;
  63900. var distX = centerX - this._positionX;
  63901. var distY = centerY - this._positionY;
  63902. // Effects
  63903. engine.enableEffect(this._effect);
  63904. engine.setState(false);
  63905. engine.setDepthBuffer(false);
  63906. // VBOs
  63907. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  63908. // Flares
  63909. for (var index = 0; index < this.lensFlares.length; index++) {
  63910. var flare = this.lensFlares[index];
  63911. engine.setAlphaMode(flare.alphaMode);
  63912. var x = centerX - (distX * flare.position);
  63913. var y = centerY - (distY * flare.position);
  63914. var cw = flare.size;
  63915. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  63916. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  63917. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  63918. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  63919. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  63920. // Texture
  63921. this._effect.setTexture("textureSampler", flare.texture);
  63922. // Color
  63923. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  63924. // Draw order
  63925. engine.draw(true, 0, 6);
  63926. }
  63927. engine.setDepthBuffer(true);
  63928. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  63929. return true;
  63930. };
  63931. LensFlareSystem.prototype.dispose = function () {
  63932. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63933. if (vertexBuffer) {
  63934. vertexBuffer.dispose();
  63935. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  63936. }
  63937. if (this._indexBuffer) {
  63938. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  63939. this._indexBuffer = null;
  63940. }
  63941. while (this.lensFlares.length) {
  63942. this.lensFlares[0].dispose();
  63943. }
  63944. // Remove from scene
  63945. var index = this._scene.lensFlareSystems.indexOf(this);
  63946. this._scene.lensFlareSystems.splice(index, 1);
  63947. };
  63948. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  63949. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  63950. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  63951. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  63952. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  63953. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  63954. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  63955. var parsedFlare = parsedLensFlareSystem.flares[index];
  63956. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  63957. }
  63958. return lensFlareSystem;
  63959. };
  63960. LensFlareSystem.prototype.serialize = function () {
  63961. var serializationObject = {};
  63962. serializationObject.id = this.id;
  63963. serializationObject.name = this.name;
  63964. serializationObject.emitterId = this.getEmitter().id;
  63965. serializationObject.borderLimit = this.borderLimit;
  63966. serializationObject.flares = [];
  63967. for (var index = 0; index < this.lensFlares.length; index++) {
  63968. var flare = this.lensFlares[index];
  63969. serializationObject.flares.push({
  63970. size: flare.size,
  63971. position: flare.position,
  63972. color: flare.color.asArray(),
  63973. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  63974. });
  63975. }
  63976. return serializationObject;
  63977. };
  63978. return LensFlareSystem;
  63979. }());
  63980. BABYLON.LensFlareSystem = LensFlareSystem;
  63981. })(BABYLON || (BABYLON = {}));
  63982. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  63983. var BABYLON;
  63984. (function (BABYLON) {
  63985. /**
  63986. * This is a holder class for the physics joint created by the physics plugin.
  63987. * It holds a set of functions to control the underlying joint.
  63988. */
  63989. var PhysicsJoint = /** @class */ (function () {
  63990. function PhysicsJoint(type, jointData) {
  63991. this.type = type;
  63992. this.jointData = jointData;
  63993. jointData.nativeParams = jointData.nativeParams || {};
  63994. }
  63995. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  63996. get: function () {
  63997. return this._physicsJoint;
  63998. },
  63999. set: function (newJoint) {
  64000. if (this._physicsJoint) {
  64001. //remove from the wolrd
  64002. }
  64003. this._physicsJoint = newJoint;
  64004. },
  64005. enumerable: true,
  64006. configurable: true
  64007. });
  64008. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  64009. set: function (physicsPlugin) {
  64010. this._physicsPlugin = physicsPlugin;
  64011. },
  64012. enumerable: true,
  64013. configurable: true
  64014. });
  64015. /**
  64016. * Execute a function that is physics-plugin specific.
  64017. * @param {Function} func the function that will be executed.
  64018. * It accepts two parameters: the physics world and the physics joint.
  64019. */
  64020. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  64021. func(this._physicsPlugin.world, this._physicsJoint);
  64022. };
  64023. //TODO check if the native joints are the same
  64024. //Joint Types
  64025. PhysicsJoint.DistanceJoint = 0;
  64026. PhysicsJoint.HingeJoint = 1;
  64027. PhysicsJoint.BallAndSocketJoint = 2;
  64028. PhysicsJoint.WheelJoint = 3;
  64029. PhysicsJoint.SliderJoint = 4;
  64030. //OIMO
  64031. PhysicsJoint.PrismaticJoint = 5;
  64032. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  64033. PhysicsJoint.UniversalJoint = 6;
  64034. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  64035. //Cannon
  64036. //Similar to a Ball-Joint. Different in params
  64037. PhysicsJoint.PointToPointJoint = 8;
  64038. //Cannon only at the moment
  64039. PhysicsJoint.SpringJoint = 9;
  64040. PhysicsJoint.LockJoint = 10;
  64041. return PhysicsJoint;
  64042. }());
  64043. BABYLON.PhysicsJoint = PhysicsJoint;
  64044. /**
  64045. * A class representing a physics distance joint.
  64046. */
  64047. var DistanceJoint = /** @class */ (function (_super) {
  64048. __extends(DistanceJoint, _super);
  64049. function DistanceJoint(jointData) {
  64050. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  64051. }
  64052. /**
  64053. * Update the predefined distance.
  64054. */
  64055. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  64056. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  64057. };
  64058. return DistanceJoint;
  64059. }(PhysicsJoint));
  64060. BABYLON.DistanceJoint = DistanceJoint;
  64061. var MotorEnabledJoint = /** @class */ (function (_super) {
  64062. __extends(MotorEnabledJoint, _super);
  64063. function MotorEnabledJoint(type, jointData) {
  64064. return _super.call(this, type, jointData) || this;
  64065. }
  64066. /**
  64067. * Set the motor values.
  64068. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64069. * @param {number} force the force to apply
  64070. * @param {number} maxForce max force for this motor.
  64071. */
  64072. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  64073. this._physicsPlugin.setMotor(this, force, maxForce);
  64074. };
  64075. /**
  64076. * Set the motor's limits.
  64077. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64078. */
  64079. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  64080. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  64081. };
  64082. return MotorEnabledJoint;
  64083. }(PhysicsJoint));
  64084. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  64085. /**
  64086. * This class represents a single hinge physics joint
  64087. */
  64088. var HingeJoint = /** @class */ (function (_super) {
  64089. __extends(HingeJoint, _super);
  64090. function HingeJoint(jointData) {
  64091. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  64092. }
  64093. /**
  64094. * Set the motor values.
  64095. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64096. * @param {number} force the force to apply
  64097. * @param {number} maxForce max force for this motor.
  64098. */
  64099. HingeJoint.prototype.setMotor = function (force, maxForce) {
  64100. this._physicsPlugin.setMotor(this, force, maxForce);
  64101. };
  64102. /**
  64103. * Set the motor's limits.
  64104. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64105. */
  64106. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  64107. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  64108. };
  64109. return HingeJoint;
  64110. }(MotorEnabledJoint));
  64111. BABYLON.HingeJoint = HingeJoint;
  64112. /**
  64113. * This class represents a dual hinge physics joint (same as wheel joint)
  64114. */
  64115. var Hinge2Joint = /** @class */ (function (_super) {
  64116. __extends(Hinge2Joint, _super);
  64117. function Hinge2Joint(jointData) {
  64118. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  64119. }
  64120. /**
  64121. * Set the motor values.
  64122. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64123. * @param {number} force the force to apply
  64124. * @param {number} maxForce max force for this motor.
  64125. * @param {motorIndex} the motor's index, 0 or 1.
  64126. */
  64127. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  64128. if (motorIndex === void 0) { motorIndex = 0; }
  64129. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  64130. };
  64131. /**
  64132. * Set the motor limits.
  64133. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64134. * @param {number} upperLimit the upper limit
  64135. * @param {number} lowerLimit lower limit
  64136. * @param {motorIndex} the motor's index, 0 or 1.
  64137. */
  64138. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  64139. if (motorIndex === void 0) { motorIndex = 0; }
  64140. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  64141. };
  64142. return Hinge2Joint;
  64143. }(MotorEnabledJoint));
  64144. BABYLON.Hinge2Joint = Hinge2Joint;
  64145. })(BABYLON || (BABYLON = {}));
  64146. //# sourceMappingURL=babylon.physicsJoint.js.map
  64147. var BABYLON;
  64148. (function (BABYLON) {
  64149. var PhysicsImpostor = /** @class */ (function () {
  64150. function PhysicsImpostor(object, type, _options, _scene) {
  64151. if (_options === void 0) { _options = { mass: 0 }; }
  64152. var _this = this;
  64153. this.object = object;
  64154. this.type = type;
  64155. this._options = _options;
  64156. this._scene = _scene;
  64157. this._bodyUpdateRequired = false;
  64158. this._onBeforePhysicsStepCallbacks = new Array();
  64159. this._onAfterPhysicsStepCallbacks = new Array();
  64160. this._onPhysicsCollideCallbacks = [];
  64161. this._deltaPosition = BABYLON.Vector3.Zero();
  64162. this._isDisposed = false;
  64163. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  64164. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  64165. /**
  64166. * this function is executed by the physics engine.
  64167. */
  64168. this.beforeStep = function () {
  64169. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  64170. //conjugate deltaRotation
  64171. if (_this._deltaRotationConjugated) {
  64172. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  64173. }
  64174. else {
  64175. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  64176. }
  64177. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  64178. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  64179. func(_this);
  64180. });
  64181. };
  64182. /**
  64183. * this function is executed by the physics engine.
  64184. */
  64185. this.afterStep = function () {
  64186. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  64187. func(_this);
  64188. });
  64189. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  64190. _this.object.position.addInPlace(_this._deltaPosition);
  64191. if (_this._deltaRotation) {
  64192. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  64193. }
  64194. };
  64195. /**
  64196. * Legacy collision detection event support
  64197. */
  64198. this.onCollideEvent = null;
  64199. //event and body object due to cannon's event-based architecture.
  64200. this.onCollide = function (e) {
  64201. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  64202. return;
  64203. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  64204. if (otherImpostor) {
  64205. // Legacy collision detection event support
  64206. if (_this.onCollideEvent) {
  64207. _this.onCollideEvent(_this, otherImpostor);
  64208. }
  64209. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  64210. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  64211. }).forEach(function (obj) {
  64212. obj.callback(_this, otherImpostor);
  64213. });
  64214. }
  64215. };
  64216. //sanity check!
  64217. if (!this.object) {
  64218. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  64219. return;
  64220. }
  64221. //legacy support for old syntax.
  64222. if (!this._scene && object.getScene) {
  64223. this._scene = object.getScene();
  64224. }
  64225. this._physicsEngine = this._scene.getPhysicsEngine();
  64226. if (!this._physicsEngine) {
  64227. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  64228. }
  64229. else {
  64230. //set the object's quaternion, if not set
  64231. if (!this.object.rotationQuaternion) {
  64232. if (this.object.rotation) {
  64233. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  64234. }
  64235. else {
  64236. this.object.rotationQuaternion = new BABYLON.Quaternion();
  64237. }
  64238. }
  64239. //default options params
  64240. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  64241. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  64242. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  64243. this._joints = [];
  64244. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  64245. if (!this.object.parent) {
  64246. this._init();
  64247. }
  64248. else if (this.object.parent.physicsImpostor) {
  64249. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  64250. }
  64251. }
  64252. }
  64253. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  64254. get: function () {
  64255. return this._isDisposed;
  64256. },
  64257. enumerable: true,
  64258. configurable: true
  64259. });
  64260. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  64261. get: function () {
  64262. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  64263. },
  64264. set: function (value) {
  64265. this.setMass(value);
  64266. },
  64267. enumerable: true,
  64268. configurable: true
  64269. });
  64270. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  64271. get: function () {
  64272. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  64273. },
  64274. set: function (value) {
  64275. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  64276. },
  64277. enumerable: true,
  64278. configurable: true
  64279. });
  64280. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  64281. get: function () {
  64282. return this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this);
  64283. },
  64284. set: function (value) {
  64285. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  64286. },
  64287. enumerable: true,
  64288. configurable: true
  64289. });
  64290. /**
  64291. * This function will completly initialize this impostor.
  64292. * It will create a new body - but only if this mesh has no parent.
  64293. * If it has, this impostor will not be used other than to define the impostor
  64294. * of the child mesh.
  64295. */
  64296. PhysicsImpostor.prototype._init = function () {
  64297. this._physicsEngine.removeImpostor(this);
  64298. this.physicsBody = null;
  64299. this._parent = this._parent || this._getPhysicsParent();
  64300. if (!this.parent) {
  64301. this._physicsEngine.addImpostor(this);
  64302. }
  64303. };
  64304. PhysicsImpostor.prototype._getPhysicsParent = function () {
  64305. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  64306. var parentMesh = this.object.parent;
  64307. return parentMesh.physicsImpostor;
  64308. }
  64309. return null;
  64310. };
  64311. /**
  64312. * Should a new body be generated.
  64313. */
  64314. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  64315. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  64316. };
  64317. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  64318. this.forceUpdate();
  64319. };
  64320. /**
  64321. * Force a regeneration of this or the parent's impostor's body.
  64322. * Use under cautious - This will remove all joints already implemented.
  64323. */
  64324. PhysicsImpostor.prototype.forceUpdate = function () {
  64325. this._init();
  64326. if (this.parent) {
  64327. this.parent.forceUpdate();
  64328. }
  64329. };
  64330. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  64331. /*public get mesh(): AbstractMesh {
  64332. return this._mesh;
  64333. }*/
  64334. /**
  64335. * Gets the body that holds this impostor. Either its own, or its parent.
  64336. */
  64337. get: function () {
  64338. return this._parent ? this._parent.physicsBody : this._physicsBody;
  64339. },
  64340. /**
  64341. * Set the physics body. Used mainly by the physics engine/plugin
  64342. */
  64343. set: function (physicsBody) {
  64344. if (this._physicsBody) {
  64345. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  64346. }
  64347. this._physicsBody = physicsBody;
  64348. this.resetUpdateFlags();
  64349. },
  64350. enumerable: true,
  64351. configurable: true
  64352. });
  64353. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  64354. get: function () {
  64355. return this._parent;
  64356. },
  64357. set: function (value) {
  64358. this._parent = value;
  64359. },
  64360. enumerable: true,
  64361. configurable: true
  64362. });
  64363. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  64364. this._bodyUpdateRequired = false;
  64365. };
  64366. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  64367. if (this.object.getBoundingInfo) {
  64368. var q = this.object.rotationQuaternion;
  64369. //reset rotation
  64370. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  64371. //calculate the world matrix with no rotation
  64372. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  64373. var size = this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2);
  64374. //bring back the rotation
  64375. this.object.rotationQuaternion = q;
  64376. //calculate the world matrix with the new rotation
  64377. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  64378. return size;
  64379. }
  64380. else {
  64381. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  64382. }
  64383. };
  64384. PhysicsImpostor.prototype.getObjectCenter = function () {
  64385. if (this.object.getBoundingInfo) {
  64386. return this.object.getBoundingInfo().boundingBox.centerWorld;
  64387. }
  64388. else {
  64389. return this.object.position;
  64390. }
  64391. };
  64392. /**
  64393. * Get a specific parametes from the options parameter.
  64394. */
  64395. PhysicsImpostor.prototype.getParam = function (paramName) {
  64396. return this._options[paramName];
  64397. };
  64398. /**
  64399. * Sets a specific parameter in the options given to the physics plugin
  64400. */
  64401. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  64402. this._options[paramName] = value;
  64403. this._bodyUpdateRequired = true;
  64404. };
  64405. /**
  64406. * Specifically change the body's mass option. Won't recreate the physics body object
  64407. */
  64408. PhysicsImpostor.prototype.setMass = function (mass) {
  64409. if (this.getParam("mass") !== mass) {
  64410. this.setParam("mass", mass);
  64411. }
  64412. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  64413. };
  64414. PhysicsImpostor.prototype.getLinearVelocity = function () {
  64415. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  64416. };
  64417. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  64418. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  64419. };
  64420. PhysicsImpostor.prototype.getAngularVelocity = function () {
  64421. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  64422. };
  64423. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  64424. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  64425. };
  64426. /**
  64427. * Execute a function with the physics plugin native code.
  64428. * Provide a function the will have two variables - the world object and the physics body object.
  64429. */
  64430. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  64431. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  64432. };
  64433. /**
  64434. * Register a function that will be executed before the physics world is stepping forward.
  64435. */
  64436. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  64437. this._onBeforePhysicsStepCallbacks.push(func);
  64438. };
  64439. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  64440. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  64441. if (index > -1) {
  64442. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  64443. }
  64444. else {
  64445. BABYLON.Tools.Warn("Function to remove was not found");
  64446. }
  64447. };
  64448. /**
  64449. * Register a function that will be executed after the physics step
  64450. */
  64451. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  64452. this._onAfterPhysicsStepCallbacks.push(func);
  64453. };
  64454. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  64455. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  64456. if (index > -1) {
  64457. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  64458. }
  64459. else {
  64460. BABYLON.Tools.Warn("Function to remove was not found");
  64461. }
  64462. };
  64463. /**
  64464. * register a function that will be executed when this impostor collides against a different body.
  64465. */
  64466. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  64467. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  64468. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  64469. };
  64470. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  64471. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  64472. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  64473. if (index > -1) {
  64474. this._onPhysicsCollideCallbacks.splice(index, 1);
  64475. }
  64476. else {
  64477. BABYLON.Tools.Warn("Function to remove was not found");
  64478. }
  64479. };
  64480. /**
  64481. * Apply a force
  64482. */
  64483. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  64484. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  64485. };
  64486. /**
  64487. * Apply an impulse
  64488. */
  64489. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  64490. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  64491. };
  64492. /**
  64493. * A help function to create a joint.
  64494. */
  64495. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  64496. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  64497. this.addJoint(otherImpostor, joint);
  64498. };
  64499. /**
  64500. * Add a joint to this impostor with a different impostor.
  64501. */
  64502. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  64503. this._joints.push({
  64504. otherImpostor: otherImpostor,
  64505. joint: joint
  64506. });
  64507. this._physicsEngine.addJoint(this, otherImpostor, joint);
  64508. };
  64509. /**
  64510. * Will keep this body still, in a sleep mode.
  64511. */
  64512. PhysicsImpostor.prototype.sleep = function () {
  64513. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  64514. };
  64515. /**
  64516. * Wake the body up.
  64517. */
  64518. PhysicsImpostor.prototype.wakeUp = function () {
  64519. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  64520. };
  64521. PhysicsImpostor.prototype.clone = function (newObject) {
  64522. if (!newObject)
  64523. return null;
  64524. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  64525. };
  64526. PhysicsImpostor.prototype.dispose = function () {
  64527. var _this = this;
  64528. //no dispose if no physics engine is available.
  64529. if (!this._physicsEngine) {
  64530. return;
  64531. }
  64532. this._joints.forEach(function (j) {
  64533. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  64534. });
  64535. //dispose the physics body
  64536. this._physicsEngine.removeImpostor(this);
  64537. if (this.parent) {
  64538. this.parent.forceUpdate();
  64539. }
  64540. else {
  64541. /*this._object.getChildMeshes().forEach(function(mesh) {
  64542. if (mesh.physicsImpostor) {
  64543. if (disposeChildren) {
  64544. mesh.physicsImpostor.dispose();
  64545. mesh.physicsImpostor = null;
  64546. }
  64547. }
  64548. })*/
  64549. }
  64550. this._isDisposed = true;
  64551. };
  64552. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  64553. this._deltaPosition.copyFrom(position);
  64554. };
  64555. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  64556. if (!this._deltaRotation) {
  64557. this._deltaRotation = new BABYLON.Quaternion();
  64558. }
  64559. this._deltaRotation.copyFrom(rotation);
  64560. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  64561. };
  64562. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  64563. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  64564. };
  64565. PhysicsImpostor.prototype.getRadius = function () {
  64566. return this._physicsEngine.getPhysicsPlugin().getRadius(this);
  64567. };
  64568. /**
  64569. * Sync a bone with this impostor
  64570. * @param bone The bone to sync to the impostor.
  64571. * @param boneMesh The mesh that the bone is influencing.
  64572. * @param jointPivot The pivot of the joint / bone in local space.
  64573. * @param distToJoint Optional distance from the impostor to the joint.
  64574. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  64575. */
  64576. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  64577. var tempVec = PhysicsImpostor._tmpVecs[0];
  64578. var mesh = this.object;
  64579. if (adjustRotation) {
  64580. var tempQuat = PhysicsImpostor._tmpQuat;
  64581. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  64582. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  64583. }
  64584. else {
  64585. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  64586. }
  64587. tempVec.x = 0;
  64588. tempVec.y = 0;
  64589. tempVec.z = 0;
  64590. if (jointPivot) {
  64591. tempVec.x = jointPivot.x;
  64592. tempVec.y = jointPivot.y;
  64593. tempVec.z = jointPivot.z;
  64594. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  64595. if (distToJoint === undefined || distToJoint === null) {
  64596. distToJoint = jointPivot.length();
  64597. }
  64598. tempVec.x *= distToJoint;
  64599. tempVec.y *= distToJoint;
  64600. tempVec.z *= distToJoint;
  64601. }
  64602. if (bone.getParent()) {
  64603. tempVec.addInPlace(mesh.getAbsolutePosition());
  64604. bone.setAbsolutePosition(tempVec, boneMesh);
  64605. }
  64606. else {
  64607. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  64608. boneMesh.position.x -= tempVec.x;
  64609. boneMesh.position.y -= tempVec.y;
  64610. boneMesh.position.z -= tempVec.z;
  64611. }
  64612. };
  64613. /**
  64614. * Sync impostor to a bone
  64615. * @param bone The bone that the impostor will be synced to.
  64616. * @param boneMesh The mesh that the bone is influencing.
  64617. * @param jointPivot The pivot of the joint / bone in local space.
  64618. * @param distToJoint Optional distance from the impostor to the joint.
  64619. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  64620. * @param boneAxis Optional vector3 axis the bone is aligned with
  64621. */
  64622. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  64623. var mesh = this.object;
  64624. if (adjustRotation) {
  64625. var tempQuat = PhysicsImpostor._tmpQuat;
  64626. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  64627. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  64628. }
  64629. else {
  64630. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  64631. }
  64632. var pos = PhysicsImpostor._tmpVecs[0];
  64633. var boneDir = PhysicsImpostor._tmpVecs[1];
  64634. if (!boneAxis) {
  64635. boneAxis = PhysicsImpostor._tmpVecs[2];
  64636. boneAxis.x = 0;
  64637. boneAxis.y = 1;
  64638. boneAxis.z = 0;
  64639. }
  64640. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  64641. bone.getAbsolutePositionToRef(boneMesh, pos);
  64642. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  64643. distToJoint = jointPivot.length();
  64644. }
  64645. if (distToJoint !== undefined && distToJoint !== null) {
  64646. pos.x += boneDir.x * distToJoint;
  64647. pos.y += boneDir.y * distToJoint;
  64648. pos.z += boneDir.z * distToJoint;
  64649. }
  64650. mesh.setAbsolutePosition(pos);
  64651. };
  64652. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  64653. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  64654. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64655. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  64656. //Impostor types
  64657. PhysicsImpostor.NoImpostor = 0;
  64658. PhysicsImpostor.SphereImpostor = 1;
  64659. PhysicsImpostor.BoxImpostor = 2;
  64660. PhysicsImpostor.PlaneImpostor = 3;
  64661. PhysicsImpostor.MeshImpostor = 4;
  64662. PhysicsImpostor.CylinderImpostor = 7;
  64663. PhysicsImpostor.ParticleImpostor = 8;
  64664. PhysicsImpostor.HeightmapImpostor = 9;
  64665. return PhysicsImpostor;
  64666. }());
  64667. BABYLON.PhysicsImpostor = PhysicsImpostor;
  64668. })(BABYLON || (BABYLON = {}));
  64669. //# sourceMappingURL=babylon.physicsImpostor.js.map
  64670. var BABYLON;
  64671. (function (BABYLON) {
  64672. var PhysicsEngine = /** @class */ (function () {
  64673. function PhysicsEngine(gravity, _physicsPlugin) {
  64674. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  64675. this._physicsPlugin = _physicsPlugin;
  64676. //new methods and parameters
  64677. this._impostors = [];
  64678. this._joints = [];
  64679. if (!this._physicsPlugin.isSupported()) {
  64680. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  64681. + "Please make sure it is included.");
  64682. }
  64683. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  64684. this.setGravity(gravity);
  64685. this.setTimeStep();
  64686. }
  64687. PhysicsEngine.prototype.setGravity = function (gravity) {
  64688. this.gravity = gravity;
  64689. this._physicsPlugin.setGravity(this.gravity);
  64690. };
  64691. /**
  64692. * Set the time step of the physics engine.
  64693. * default is 1/60.
  64694. * To slow it down, enter 1/600 for example.
  64695. * To speed it up, 1/30
  64696. * @param {number} newTimeStep the new timestep to apply to this world.
  64697. */
  64698. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  64699. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  64700. this._physicsPlugin.setTimeStep(newTimeStep);
  64701. };
  64702. /**
  64703. * Get the time step of the physics engine.
  64704. */
  64705. PhysicsEngine.prototype.getTimeStep = function () {
  64706. return this._physicsPlugin.getTimeStep();
  64707. };
  64708. PhysicsEngine.prototype.dispose = function () {
  64709. this._impostors.forEach(function (impostor) {
  64710. impostor.dispose();
  64711. });
  64712. this._physicsPlugin.dispose();
  64713. };
  64714. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  64715. return this._physicsPlugin.name;
  64716. };
  64717. /**
  64718. * Adding a new impostor for the impostor tracking.
  64719. * This will be done by the impostor itself.
  64720. * @param {PhysicsImpostor} impostor the impostor to add
  64721. */
  64722. PhysicsEngine.prototype.addImpostor = function (impostor) {
  64723. impostor.uniqueId = this._impostors.push(impostor);
  64724. //if no parent, generate the body
  64725. if (!impostor.parent) {
  64726. this._physicsPlugin.generatePhysicsBody(impostor);
  64727. }
  64728. };
  64729. /**
  64730. * Remove an impostor from the engine.
  64731. * This impostor and its mesh will not longer be updated by the physics engine.
  64732. * @param {PhysicsImpostor} impostor the impostor to remove
  64733. */
  64734. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  64735. var index = this._impostors.indexOf(impostor);
  64736. if (index > -1) {
  64737. var removed = this._impostors.splice(index, 1);
  64738. //Is it needed?
  64739. if (removed.length) {
  64740. //this will also remove it from the world.
  64741. removed[0].physicsBody = null;
  64742. }
  64743. }
  64744. };
  64745. /**
  64746. * Add a joint to the physics engine
  64747. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  64748. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  64749. * @param {PhysicsJoint} the joint that will connect both impostors.
  64750. */
  64751. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  64752. var impostorJoint = {
  64753. mainImpostor: mainImpostor,
  64754. connectedImpostor: connectedImpostor,
  64755. joint: joint
  64756. };
  64757. joint.physicsPlugin = this._physicsPlugin;
  64758. this._joints.push(impostorJoint);
  64759. this._physicsPlugin.generateJoint(impostorJoint);
  64760. };
  64761. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  64762. var matchingJoints = this._joints.filter(function (impostorJoint) {
  64763. return (impostorJoint.connectedImpostor === connectedImpostor
  64764. && impostorJoint.joint === joint
  64765. && impostorJoint.mainImpostor === mainImpostor);
  64766. });
  64767. if (matchingJoints.length) {
  64768. this._physicsPlugin.removeJoint(matchingJoints[0]);
  64769. //TODO remove it from the list as well
  64770. }
  64771. };
  64772. /**
  64773. * Called by the scene. no need to call it.
  64774. */
  64775. PhysicsEngine.prototype._step = function (delta) {
  64776. var _this = this;
  64777. //check if any mesh has no body / requires an update
  64778. this._impostors.forEach(function (impostor) {
  64779. if (impostor.isBodyInitRequired()) {
  64780. _this._physicsPlugin.generatePhysicsBody(impostor);
  64781. }
  64782. });
  64783. if (delta > 0.1) {
  64784. delta = 0.1;
  64785. }
  64786. else if (delta <= 0) {
  64787. delta = 1.0 / 60.0;
  64788. }
  64789. this._physicsPlugin.executeStep(delta, this._impostors);
  64790. };
  64791. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  64792. return this._physicsPlugin;
  64793. };
  64794. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  64795. for (var i = 0; i < this._impostors.length; ++i) {
  64796. if (this._impostors[i].object === object) {
  64797. return this._impostors[i];
  64798. }
  64799. }
  64800. return null;
  64801. };
  64802. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  64803. for (var i = 0; i < this._impostors.length; ++i) {
  64804. if (this._impostors[i].physicsBody === body) {
  64805. return this._impostors[i];
  64806. }
  64807. }
  64808. return null;
  64809. };
  64810. // Statics
  64811. PhysicsEngine.Epsilon = 0.001;
  64812. return PhysicsEngine;
  64813. }());
  64814. BABYLON.PhysicsEngine = PhysicsEngine;
  64815. })(BABYLON || (BABYLON = {}));
  64816. //# sourceMappingURL=babylon.physicsEngine.js.map
  64817. var BABYLON;
  64818. (function (BABYLON) {
  64819. var CannonJSPlugin = /** @class */ (function () {
  64820. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  64821. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  64822. if (iterations === void 0) { iterations = 10; }
  64823. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  64824. this.name = "CannonJSPlugin";
  64825. this._physicsMaterials = new Array();
  64826. this._fixedTimeStep = 1 / 60;
  64827. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  64828. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  64829. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  64830. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  64831. this._tmpPosition = BABYLON.Vector3.Zero();
  64832. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  64833. this._tmpUnityRotation = new BABYLON.Quaternion();
  64834. if (!this.isSupported()) {
  64835. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  64836. return;
  64837. }
  64838. this.world = new this.BJSCANNON.World();
  64839. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  64840. this.world.solver.iterations = iterations;
  64841. }
  64842. CannonJSPlugin.prototype.setGravity = function (gravity) {
  64843. this.world.gravity.copy(gravity);
  64844. };
  64845. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  64846. this._fixedTimeStep = timeStep;
  64847. };
  64848. CannonJSPlugin.prototype.getTimeStep = function () {
  64849. return this._fixedTimeStep;
  64850. };
  64851. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  64852. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  64853. };
  64854. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  64855. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  64856. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  64857. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  64858. };
  64859. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  64860. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  64861. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  64862. impostor.physicsBody.applyForce(impulse, worldPoint);
  64863. };
  64864. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  64865. //parent-child relationship. Does this impostor has a parent impostor?
  64866. if (impostor.parent) {
  64867. if (impostor.physicsBody) {
  64868. this.removePhysicsBody(impostor);
  64869. //TODO is that needed?
  64870. impostor.forceUpdate();
  64871. }
  64872. return;
  64873. }
  64874. //should a new body be created for this impostor?
  64875. if (impostor.isBodyInitRequired()) {
  64876. var shape = this._createShape(impostor);
  64877. //unregister events, if body is being changed
  64878. var oldBody = impostor.physicsBody;
  64879. if (oldBody) {
  64880. this.removePhysicsBody(impostor);
  64881. }
  64882. //create the body and material
  64883. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  64884. var bodyCreationObject = {
  64885. mass: impostor.getParam("mass"),
  64886. material: material
  64887. };
  64888. // A simple extend, in case native options were used.
  64889. var nativeOptions = impostor.getParam("nativeOptions");
  64890. for (var key in nativeOptions) {
  64891. if (nativeOptions.hasOwnProperty(key)) {
  64892. bodyCreationObject[key] = nativeOptions[key];
  64893. }
  64894. }
  64895. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  64896. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  64897. this.world.addEventListener("preStep", impostor.beforeStep);
  64898. this.world.addEventListener("postStep", impostor.afterStep);
  64899. impostor.physicsBody.addShape(shape);
  64900. this.world.add(impostor.physicsBody);
  64901. //try to keep the body moving in the right direction by taking old properties.
  64902. //Should be tested!
  64903. if (oldBody) {
  64904. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  64905. impostor.physicsBody[param].copy(oldBody[param]);
  64906. });
  64907. }
  64908. this._processChildMeshes(impostor);
  64909. }
  64910. //now update the body's transformation
  64911. this._updatePhysicsBodyTransformation(impostor);
  64912. };
  64913. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  64914. var _this = this;
  64915. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  64916. var currentRotation = mainImpostor.object.rotationQuaternion;
  64917. if (meshChildren.length) {
  64918. var processMesh = function (localPosition, mesh) {
  64919. var childImpostor = mesh.getPhysicsImpostor();
  64920. if (childImpostor) {
  64921. var parent = childImpostor.parent;
  64922. if (parent !== mainImpostor) {
  64923. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  64924. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  64925. if (childImpostor.physicsBody) {
  64926. _this.removePhysicsBody(childImpostor);
  64927. childImpostor.physicsBody = null;
  64928. }
  64929. childImpostor.parent = mainImpostor;
  64930. childImpostor.resetUpdateFlags();
  64931. 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));
  64932. //Add the mass of the children.
  64933. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  64934. }
  64935. }
  64936. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  64937. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  64938. };
  64939. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  64940. }
  64941. };
  64942. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  64943. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  64944. this.world.removeEventListener("preStep", impostor.beforeStep);
  64945. this.world.removeEventListener("postStep", impostor.afterStep);
  64946. this.world.remove(impostor.physicsBody);
  64947. };
  64948. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  64949. var mainBody = impostorJoint.mainImpostor.physicsBody;
  64950. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  64951. if (!mainBody || !connectedBody) {
  64952. return;
  64953. }
  64954. var constraint;
  64955. var jointData = impostorJoint.joint.jointData;
  64956. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  64957. var constraintData = {
  64958. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  64959. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  64960. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  64961. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  64962. maxForce: jointData.nativeParams.maxForce,
  64963. collideConnected: !!jointData.collision
  64964. };
  64965. switch (impostorJoint.joint.type) {
  64966. case BABYLON.PhysicsJoint.HingeJoint:
  64967. case BABYLON.PhysicsJoint.Hinge2Joint:
  64968. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  64969. break;
  64970. case BABYLON.PhysicsJoint.DistanceJoint:
  64971. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  64972. break;
  64973. case BABYLON.PhysicsJoint.SpringJoint:
  64974. var springData = jointData;
  64975. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  64976. restLength: springData.length,
  64977. stiffness: springData.stiffness,
  64978. damping: springData.damping,
  64979. localAnchorA: constraintData.pivotA,
  64980. localAnchorB: constraintData.pivotB
  64981. });
  64982. break;
  64983. case BABYLON.PhysicsJoint.LockJoint:
  64984. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  64985. break;
  64986. case BABYLON.PhysicsJoint.PointToPointJoint:
  64987. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  64988. default:
  64989. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  64990. break;
  64991. }
  64992. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  64993. constraint.collideConnected = !!jointData.collision;
  64994. impostorJoint.joint.physicsJoint = constraint;
  64995. //don't add spring as constraint, as it is not one.
  64996. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  64997. this.world.addConstraint(constraint);
  64998. }
  64999. else {
  65000. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  65001. constraint.applyForce();
  65002. });
  65003. }
  65004. };
  65005. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  65006. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  65007. };
  65008. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  65009. var index;
  65010. var mat;
  65011. for (index = 0; index < this._physicsMaterials.length; index++) {
  65012. mat = this._physicsMaterials[index];
  65013. if (mat.friction === friction && mat.restitution === restitution) {
  65014. return mat;
  65015. }
  65016. }
  65017. var currentMat = new this.BJSCANNON.Material(name);
  65018. currentMat.friction = friction;
  65019. currentMat.restitution = restitution;
  65020. this._physicsMaterials.push(currentMat);
  65021. return currentMat;
  65022. };
  65023. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  65024. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  65025. };
  65026. CannonJSPlugin.prototype._createShape = function (impostor) {
  65027. var object = impostor.object;
  65028. var returnValue;
  65029. var extendSize = impostor.getObjectExtendSize();
  65030. switch (impostor.type) {
  65031. case BABYLON.PhysicsImpostor.SphereImpostor:
  65032. var radiusX = extendSize.x;
  65033. var radiusY = extendSize.y;
  65034. var radiusZ = extendSize.z;
  65035. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  65036. break;
  65037. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  65038. case BABYLON.PhysicsImpostor.CylinderImpostor:
  65039. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  65040. break;
  65041. case BABYLON.PhysicsImpostor.BoxImpostor:
  65042. var box = extendSize.scale(0.5);
  65043. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  65044. break;
  65045. case BABYLON.PhysicsImpostor.PlaneImpostor:
  65046. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  65047. returnValue = new this.BJSCANNON.Plane();
  65048. break;
  65049. case BABYLON.PhysicsImpostor.MeshImpostor:
  65050. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  65051. var rawFaces = object.getIndices ? object.getIndices() : [];
  65052. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  65053. returnValue = new this.BJSCANNON.Trimesh(rawVerts, rawFaces);
  65054. break;
  65055. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  65056. returnValue = this._createHeightmap(object);
  65057. break;
  65058. case BABYLON.PhysicsImpostor.ParticleImpostor:
  65059. returnValue = new this.BJSCANNON.Particle();
  65060. break;
  65061. }
  65062. return returnValue;
  65063. };
  65064. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  65065. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65066. var matrix = new Array();
  65067. //For now pointDepth will not be used and will be automatically calculated.
  65068. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  65069. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  65070. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSizeWorld.x, object.getBoundingInfo().boundingBox.extendSizeWorld.z);
  65071. var elementSize = dim * 2 / arraySize;
  65072. var minY = object.getBoundingInfo().boundingBox.extendSizeWorld.y;
  65073. for (var i = 0; i < pos.length; i = i + 3) {
  65074. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  65075. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  65076. var y = pos[i + 1] + minY;
  65077. if (!matrix[x]) {
  65078. matrix[x] = [];
  65079. }
  65080. if (!matrix[x][z]) {
  65081. matrix[x][z] = y;
  65082. }
  65083. matrix[x][z] = Math.max(y, matrix[x][z]);
  65084. }
  65085. for (var x = 0; x <= arraySize; ++x) {
  65086. if (!matrix[x]) {
  65087. var loc = 1;
  65088. while (!matrix[(x + loc) % arraySize]) {
  65089. loc++;
  65090. }
  65091. matrix[x] = matrix[(x + loc) % arraySize].slice();
  65092. //console.log("missing x", x);
  65093. }
  65094. for (var z = 0; z <= arraySize; ++z) {
  65095. if (!matrix[x][z]) {
  65096. var loc = 1;
  65097. var newValue;
  65098. while (newValue === undefined) {
  65099. newValue = matrix[x][(z + loc++) % arraySize];
  65100. }
  65101. matrix[x][z] = newValue;
  65102. }
  65103. }
  65104. }
  65105. var shape = new this.BJSCANNON.Heightfield(matrix, {
  65106. elementSize: elementSize
  65107. });
  65108. //For future reference, needed for body transformation
  65109. shape.minY = minY;
  65110. return shape;
  65111. };
  65112. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  65113. var object = impostor.object;
  65114. //make sure it is updated...
  65115. object.computeWorldMatrix && object.computeWorldMatrix(true);
  65116. // The delta between the mesh position and the mesh bounding box center
  65117. var center = impostor.getObjectCenter();
  65118. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  65119. this._tmpPosition.copyFrom(center);
  65120. var quaternion = object.rotationQuaternion;
  65121. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  65122. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  65123. //-90 DEG in X, precalculated
  65124. quaternion = quaternion.multiply(this._minus90X);
  65125. //Invert! (Precalculated, 90 deg in X)
  65126. //No need to clone. this will never change.
  65127. impostor.setDeltaRotation(this._plus90X);
  65128. }
  65129. //If it is a heightfield, if should be centered.
  65130. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  65131. var mesh = object;
  65132. //calculate the correct body position:
  65133. var rotationQuaternion = mesh.rotationQuaternion;
  65134. mesh.rotationQuaternion = this._tmpUnityRotation;
  65135. mesh.computeWorldMatrix(true);
  65136. //get original center with no rotation
  65137. var c = center.clone();
  65138. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  65139. //rotation is back
  65140. mesh.rotationQuaternion = rotationQuaternion;
  65141. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  65142. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSizeWorld.x, 0, -mesh.getBoundingInfo().boundingBox.extendSizeWorld.z);
  65143. mesh.setPivotMatrix(p);
  65144. mesh.computeWorldMatrix(true);
  65145. //calculate the translation
  65146. var translation = mesh.getBoundingInfo().boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  65147. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSizeWorld.y, translation.z);
  65148. //add it inverted to the delta
  65149. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.centerWorld.subtract(c));
  65150. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSizeWorld.y;
  65151. mesh.setPivotMatrix(oldPivot);
  65152. mesh.computeWorldMatrix(true);
  65153. }
  65154. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  65155. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  65156. this._tmpPosition.copyFrom(object.position);
  65157. }
  65158. impostor.setDeltaPosition(this._tmpDeltaPosition);
  65159. //Now update the impostor object
  65160. impostor.physicsBody.position.copy(this._tmpPosition);
  65161. impostor.physicsBody.quaternion.copy(quaternion);
  65162. };
  65163. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  65164. impostor.object.position.copyFrom(impostor.physicsBody.position);
  65165. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  65166. };
  65167. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  65168. impostor.physicsBody.position.copy(newPosition);
  65169. impostor.physicsBody.quaternion.copy(newRotation);
  65170. };
  65171. CannonJSPlugin.prototype.isSupported = function () {
  65172. return this.BJSCANNON !== undefined;
  65173. };
  65174. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  65175. impostor.physicsBody.velocity.copy(velocity);
  65176. };
  65177. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  65178. impostor.physicsBody.angularVelocity.copy(velocity);
  65179. };
  65180. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  65181. var v = impostor.physicsBody.velocity;
  65182. if (!v)
  65183. return null;
  65184. return new BABYLON.Vector3(v.x, v.y, v.z);
  65185. };
  65186. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  65187. var v = impostor.physicsBody.angularVelocity;
  65188. if (!v)
  65189. return null;
  65190. return new BABYLON.Vector3(v.x, v.y, v.z);
  65191. };
  65192. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  65193. impostor.physicsBody.mass = mass;
  65194. impostor.physicsBody.updateMassProperties();
  65195. };
  65196. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  65197. return impostor.physicsBody.mass;
  65198. };
  65199. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  65200. return impostor.physicsBody.material.friction;
  65201. };
  65202. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  65203. impostor.physicsBody.material.friction = friction;
  65204. };
  65205. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  65206. return impostor.physicsBody.material.restitution;
  65207. };
  65208. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  65209. impostor.physicsBody.material.restitution = restitution;
  65210. };
  65211. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  65212. impostor.physicsBody.sleep();
  65213. };
  65214. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  65215. impostor.physicsBody.wakeUp();
  65216. };
  65217. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  65218. joint.physicsJoint.distance = maxDistance;
  65219. };
  65220. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  65221. // if (!motorIndex) {
  65222. // joint.physicsJoint.enableMotor();
  65223. // }
  65224. // }
  65225. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  65226. // if (!motorIndex) {
  65227. // joint.physicsJoint.disableMotor();
  65228. // }
  65229. // }
  65230. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  65231. if (!motorIndex) {
  65232. joint.physicsJoint.enableMotor();
  65233. joint.physicsJoint.setMotorSpeed(speed);
  65234. if (maxForce) {
  65235. this.setLimit(joint, maxForce);
  65236. }
  65237. }
  65238. };
  65239. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  65240. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  65241. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  65242. };
  65243. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  65244. var body = impostor.physicsBody;
  65245. mesh.position.x = body.position.x;
  65246. mesh.position.y = body.position.y;
  65247. mesh.position.z = body.position.z;
  65248. mesh.rotationQuaternion.x = body.quaternion.x;
  65249. mesh.rotationQuaternion.y = body.quaternion.y;
  65250. mesh.rotationQuaternion.z = body.quaternion.z;
  65251. mesh.rotationQuaternion.w = body.quaternion.w;
  65252. };
  65253. CannonJSPlugin.prototype.getRadius = function (impostor) {
  65254. var shape = impostor.physicsBody.shapes[0];
  65255. return shape.boundingSphereRadius;
  65256. };
  65257. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  65258. var shape = impostor.physicsBody.shapes[0];
  65259. result.x = shape.halfExtents.x * 2;
  65260. result.y = shape.halfExtents.y * 2;
  65261. result.z = shape.halfExtents.z * 2;
  65262. };
  65263. CannonJSPlugin.prototype.dispose = function () {
  65264. };
  65265. return CannonJSPlugin;
  65266. }());
  65267. BABYLON.CannonJSPlugin = CannonJSPlugin;
  65268. })(BABYLON || (BABYLON = {}));
  65269. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  65270. var BABYLON;
  65271. (function (BABYLON) {
  65272. var OimoJSPlugin = /** @class */ (function () {
  65273. function OimoJSPlugin(iterations) {
  65274. this.name = "OimoJSPlugin";
  65275. this._tmpImpostorsArray = [];
  65276. this._tmpPositionVector = BABYLON.Vector3.Zero();
  65277. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  65278. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  65279. this.world.worldscale(1);
  65280. this.world.clear();
  65281. //making sure no stats are calculated
  65282. this.world.isNoStat = true;
  65283. }
  65284. OimoJSPlugin.prototype.setGravity = function (gravity) {
  65285. this.world.gravity.copy(gravity);
  65286. };
  65287. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  65288. this.world.timeStep = timeStep;
  65289. };
  65290. OimoJSPlugin.prototype.getTimeStep = function () {
  65291. return this.world.timeStep;
  65292. };
  65293. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  65294. var _this = this;
  65295. impostors.forEach(function (impostor) {
  65296. impostor.beforeStep();
  65297. });
  65298. this.world.step();
  65299. impostors.forEach(function (impostor) {
  65300. impostor.afterStep();
  65301. //update the ordered impostors array
  65302. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  65303. });
  65304. //check for collisions
  65305. var contact = this.world.contacts;
  65306. while (contact !== null) {
  65307. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  65308. contact = contact.next;
  65309. continue;
  65310. }
  65311. //is this body colliding with any other? get the impostor
  65312. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  65313. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  65314. if (!mainImpostor || !collidingImpostor) {
  65315. contact = contact.next;
  65316. continue;
  65317. }
  65318. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  65319. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  65320. contact = contact.next;
  65321. }
  65322. };
  65323. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  65324. var mass = impostor.physicsBody.massInfo.mass;
  65325. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  65326. };
  65327. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  65328. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  65329. this.applyImpulse(impostor, force, contactPoint);
  65330. };
  65331. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  65332. var _this = this;
  65333. //parent-child relationship. Does this impostor has a parent impostor?
  65334. if (impostor.parent) {
  65335. if (impostor.physicsBody) {
  65336. this.removePhysicsBody(impostor);
  65337. //TODO is that needed?
  65338. impostor.forceUpdate();
  65339. }
  65340. return;
  65341. }
  65342. if (impostor.isBodyInitRequired()) {
  65343. var bodyConfig = {
  65344. name: impostor.uniqueId,
  65345. //Oimo must have mass, also for static objects.
  65346. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  65347. size: [],
  65348. type: [],
  65349. pos: [],
  65350. rot: [],
  65351. move: impostor.getParam("mass") !== 0,
  65352. //Supporting older versions of Oimo
  65353. world: this.world
  65354. };
  65355. var impostors = [impostor];
  65356. var addToArray = function (parent) {
  65357. if (!parent.getChildMeshes)
  65358. return;
  65359. parent.getChildMeshes().forEach(function (m) {
  65360. if (m.physicsImpostor) {
  65361. impostors.push(m.physicsImpostor);
  65362. //m.physicsImpostor._init();
  65363. }
  65364. });
  65365. };
  65366. addToArray(impostor.object);
  65367. var checkWithEpsilon_1 = function (value) {
  65368. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  65369. };
  65370. impostors.forEach(function (i) {
  65371. //get the correct bounding box
  65372. var oldQuaternion = i.object.rotationQuaternion;
  65373. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  65374. x: impostor.object.rotationQuaternion.x,
  65375. y: impostor.object.rotationQuaternion.y,
  65376. z: impostor.object.rotationQuaternion.z,
  65377. s: impostor.object.rotationQuaternion.w
  65378. });
  65379. var extendSize = i.getObjectExtendSize();
  65380. if (i === impostor) {
  65381. var center = impostor.getObjectCenter();
  65382. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  65383. //Can also use Array.prototype.push.apply
  65384. bodyConfig.pos.push(center.x);
  65385. bodyConfig.pos.push(center.y);
  65386. bodyConfig.pos.push(center.z);
  65387. //tmp solution
  65388. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  65389. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  65390. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  65391. }
  65392. else {
  65393. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  65394. bodyConfig.pos.push(localPosition.x);
  65395. bodyConfig.pos.push(localPosition.y);
  65396. bodyConfig.pos.push(localPosition.z);
  65397. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  65398. bodyConfig.rot.push(0);
  65399. bodyConfig.rot.push(0);
  65400. bodyConfig.rot.push(0);
  65401. }
  65402. // register mesh
  65403. switch (i.type) {
  65404. case BABYLON.PhysicsImpostor.ParticleImpostor:
  65405. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  65406. case BABYLON.PhysicsImpostor.SphereImpostor:
  65407. var radiusX = extendSize.x;
  65408. var radiusY = extendSize.y;
  65409. var radiusZ = extendSize.z;
  65410. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  65411. bodyConfig.type.push('sphere');
  65412. //due to the way oimo works with compounds, add 3 times
  65413. bodyConfig.size.push(size);
  65414. bodyConfig.size.push(size);
  65415. bodyConfig.size.push(size);
  65416. break;
  65417. case BABYLON.PhysicsImpostor.CylinderImpostor:
  65418. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  65419. var sizeY = checkWithEpsilon_1(extendSize.y);
  65420. bodyConfig.type.push('cylinder');
  65421. bodyConfig.size.push(sizeX);
  65422. bodyConfig.size.push(sizeY);
  65423. //due to the way oimo works with compounds, add one more value.
  65424. bodyConfig.size.push(sizeY);
  65425. break;
  65426. case BABYLON.PhysicsImpostor.PlaneImpostor:
  65427. case BABYLON.PhysicsImpostor.BoxImpostor:
  65428. default:
  65429. var sizeX = checkWithEpsilon_1(extendSize.x);
  65430. var sizeY = checkWithEpsilon_1(extendSize.y);
  65431. var sizeZ = checkWithEpsilon_1(extendSize.z);
  65432. bodyConfig.type.push('box');
  65433. bodyConfig.size.push(sizeX);
  65434. bodyConfig.size.push(sizeY);
  65435. bodyConfig.size.push(sizeZ);
  65436. break;
  65437. }
  65438. //actually not needed, but hey...
  65439. i.object.rotationQuaternion = oldQuaternion;
  65440. });
  65441. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  65442. }
  65443. else {
  65444. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  65445. }
  65446. impostor.setDeltaPosition(this._tmpPositionVector);
  65447. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  65448. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  65449. };
  65450. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  65451. //impostor.physicsBody.dispose();
  65452. //Same as : (older oimo versions)
  65453. this.world.removeRigidBody(impostor.physicsBody);
  65454. };
  65455. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  65456. var mainBody = impostorJoint.mainImpostor.physicsBody;
  65457. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  65458. if (!mainBody || !connectedBody) {
  65459. return;
  65460. }
  65461. var jointData = impostorJoint.joint.jointData;
  65462. var options = jointData.nativeParams || {};
  65463. var type;
  65464. var nativeJointData = {
  65465. body1: mainBody,
  65466. body2: connectedBody,
  65467. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  65468. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  65469. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  65470. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  65471. min: options.min,
  65472. max: options.max,
  65473. collision: options.collision || jointData.collision,
  65474. spring: options.spring,
  65475. //supporting older version of Oimo
  65476. world: this.world
  65477. };
  65478. switch (impostorJoint.joint.type) {
  65479. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  65480. type = "jointBall";
  65481. break;
  65482. case BABYLON.PhysicsJoint.SpringJoint:
  65483. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  65484. var springData = jointData;
  65485. nativeJointData.min = springData.length || nativeJointData.min;
  65486. //Max should also be set, just make sure it is at least min
  65487. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  65488. case BABYLON.PhysicsJoint.DistanceJoint:
  65489. type = "jointDistance";
  65490. nativeJointData.max = jointData.maxDistance;
  65491. break;
  65492. case BABYLON.PhysicsJoint.PrismaticJoint:
  65493. type = "jointPrisme";
  65494. break;
  65495. case BABYLON.PhysicsJoint.SliderJoint:
  65496. type = "jointSlide";
  65497. break;
  65498. case BABYLON.PhysicsJoint.WheelJoint:
  65499. type = "jointWheel";
  65500. break;
  65501. case BABYLON.PhysicsJoint.HingeJoint:
  65502. default:
  65503. type = "jointHinge";
  65504. break;
  65505. }
  65506. nativeJointData.type = type;
  65507. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  65508. };
  65509. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  65510. //Bug in Oimo prevents us from disposing a joint in the playground
  65511. //joint.joint.physicsJoint.dispose();
  65512. //So we will bruteforce it!
  65513. try {
  65514. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  65515. }
  65516. catch (e) {
  65517. BABYLON.Tools.Warn(e);
  65518. }
  65519. };
  65520. OimoJSPlugin.prototype.isSupported = function () {
  65521. return this.BJSOIMO !== undefined;
  65522. };
  65523. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  65524. if (!impostor.physicsBody.sleeping) {
  65525. //TODO check that
  65526. if (impostor.physicsBody.shapes.next) {
  65527. var parentShape = this._getLastShape(impostor.physicsBody);
  65528. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  65529. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  65530. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  65531. }
  65532. else {
  65533. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  65534. }
  65535. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  65536. impostor.object.rotationQuaternion.normalize();
  65537. }
  65538. };
  65539. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  65540. var body = impostor.physicsBody;
  65541. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  65542. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  65543. body.syncShapes();
  65544. body.awake();
  65545. };
  65546. OimoJSPlugin.prototype._getLastShape = function (body) {
  65547. var lastShape = body.shapes;
  65548. while (lastShape.next) {
  65549. lastShape = lastShape.next;
  65550. }
  65551. return lastShape;
  65552. };
  65553. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  65554. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  65555. };
  65556. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  65557. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  65558. };
  65559. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  65560. var v = impostor.physicsBody.linearVelocity;
  65561. if (!v)
  65562. return null;
  65563. return new BABYLON.Vector3(v.x, v.y, v.z);
  65564. };
  65565. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  65566. var v = impostor.physicsBody.angularVelocity;
  65567. if (!v)
  65568. return null;
  65569. return new BABYLON.Vector3(v.x, v.y, v.z);
  65570. };
  65571. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  65572. var staticBody = mass === 0;
  65573. //this will actually set the body's density and not its mass.
  65574. //But this is how oimo treats the mass variable.
  65575. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  65576. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  65577. };
  65578. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  65579. return impostor.physicsBody.shapes.density;
  65580. };
  65581. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  65582. return impostor.physicsBody.shapes.friction;
  65583. };
  65584. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  65585. impostor.physicsBody.shapes.friction = friction;
  65586. };
  65587. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  65588. return impostor.physicsBody.shapes.restitution;
  65589. };
  65590. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  65591. impostor.physicsBody.shapes.restitution = restitution;
  65592. };
  65593. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  65594. impostor.physicsBody.sleep();
  65595. };
  65596. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  65597. impostor.physicsBody.awake();
  65598. };
  65599. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  65600. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  65601. if (minDistance !== void 0) {
  65602. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  65603. }
  65604. };
  65605. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  65606. //TODO separate rotational and transational motors.
  65607. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  65608. if (motor) {
  65609. motor.setMotor(speed, maxForce);
  65610. }
  65611. };
  65612. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  65613. //TODO separate rotational and transational motors.
  65614. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  65615. if (motor) {
  65616. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  65617. }
  65618. };
  65619. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  65620. var body = impostor.physicsBody;
  65621. mesh.position.x = body.position.x;
  65622. mesh.position.y = body.position.y;
  65623. mesh.position.z = body.position.z;
  65624. mesh.rotationQuaternion.x = body.orientation.x;
  65625. mesh.rotationQuaternion.y = body.orientation.y;
  65626. mesh.rotationQuaternion.z = body.orientation.z;
  65627. mesh.rotationQuaternion.w = body.orientation.s;
  65628. };
  65629. OimoJSPlugin.prototype.getRadius = function (impostor) {
  65630. return impostor.physicsBody.shapes.radius;
  65631. };
  65632. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  65633. var shape = impostor.physicsBody.shapes;
  65634. result.x = shape.halfWidth * 2;
  65635. result.y = shape.halfHeight * 2;
  65636. result.z = shape.halfDepth * 2;
  65637. };
  65638. OimoJSPlugin.prototype.dispose = function () {
  65639. this.world.clear();
  65640. };
  65641. return OimoJSPlugin;
  65642. }());
  65643. BABYLON.OimoJSPlugin = OimoJSPlugin;
  65644. })(BABYLON || (BABYLON = {}));
  65645. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  65646. var BABYLON;
  65647. (function (BABYLON) {
  65648. var Internals;
  65649. (function (Internals) {
  65650. /*
  65651. * Based on jsTGALoader - Javascript loader for TGA file
  65652. * By Vincent Thibault
  65653. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  65654. */
  65655. var TGATools = /** @class */ (function () {
  65656. function TGATools() {
  65657. }
  65658. TGATools.GetTGAHeader = function (data) {
  65659. var offset = 0;
  65660. var header = {
  65661. id_length: data[offset++],
  65662. colormap_type: data[offset++],
  65663. image_type: data[offset++],
  65664. colormap_index: data[offset++] | data[offset++] << 8,
  65665. colormap_length: data[offset++] | data[offset++] << 8,
  65666. colormap_size: data[offset++],
  65667. origin: [
  65668. data[offset++] | data[offset++] << 8,
  65669. data[offset++] | data[offset++] << 8
  65670. ],
  65671. width: data[offset++] | data[offset++] << 8,
  65672. height: data[offset++] | data[offset++] << 8,
  65673. pixel_size: data[offset++],
  65674. flags: data[offset++]
  65675. };
  65676. return header;
  65677. };
  65678. TGATools.UploadContent = function (gl, data) {
  65679. // Not enough data to contain header ?
  65680. if (data.length < 19) {
  65681. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  65682. return;
  65683. }
  65684. // Read Header
  65685. var offset = 18;
  65686. var header = TGATools.GetTGAHeader(data);
  65687. // Assume it's a valid Targa file.
  65688. if (header.id_length + offset > data.length) {
  65689. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  65690. return;
  65691. }
  65692. // Skip not needed data
  65693. offset += header.id_length;
  65694. var use_rle = false;
  65695. var use_pal = false;
  65696. var use_rgb = false;
  65697. var use_grey = false;
  65698. // Get some informations.
  65699. switch (header.image_type) {
  65700. case TGATools._TYPE_RLE_INDEXED:
  65701. use_rle = true;
  65702. case TGATools._TYPE_INDEXED:
  65703. use_pal = true;
  65704. break;
  65705. case TGATools._TYPE_RLE_RGB:
  65706. use_rle = true;
  65707. case TGATools._TYPE_RGB:
  65708. use_rgb = true;
  65709. break;
  65710. case TGATools._TYPE_RLE_GREY:
  65711. use_rle = true;
  65712. case TGATools._TYPE_GREY:
  65713. use_grey = true;
  65714. break;
  65715. }
  65716. var pixel_data;
  65717. // var numAlphaBits = header.flags & 0xf;
  65718. var pixel_size = header.pixel_size >> 3;
  65719. var pixel_total = header.width * header.height * pixel_size;
  65720. // Read palettes
  65721. var palettes;
  65722. if (use_pal) {
  65723. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  65724. }
  65725. // Read LRE
  65726. if (use_rle) {
  65727. pixel_data = new Uint8Array(pixel_total);
  65728. var c, count, i;
  65729. var localOffset = 0;
  65730. var pixels = new Uint8Array(pixel_size);
  65731. while (offset < pixel_total && localOffset < pixel_total) {
  65732. c = data[offset++];
  65733. count = (c & 0x7f) + 1;
  65734. // RLE pixels
  65735. if (c & 0x80) {
  65736. // Bind pixel tmp array
  65737. for (i = 0; i < pixel_size; ++i) {
  65738. pixels[i] = data[offset++];
  65739. }
  65740. // Copy pixel array
  65741. for (i = 0; i < count; ++i) {
  65742. pixel_data.set(pixels, localOffset + i * pixel_size);
  65743. }
  65744. localOffset += pixel_size * count;
  65745. }
  65746. else {
  65747. count *= pixel_size;
  65748. for (i = 0; i < count; ++i) {
  65749. pixel_data[localOffset + i] = data[offset++];
  65750. }
  65751. localOffset += count;
  65752. }
  65753. }
  65754. }
  65755. else {
  65756. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  65757. }
  65758. // Load to texture
  65759. var x_start, y_start, x_step, y_step, y_end, x_end;
  65760. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  65761. default:
  65762. case TGATools._ORIGIN_UL:
  65763. x_start = 0;
  65764. x_step = 1;
  65765. x_end = header.width;
  65766. y_start = 0;
  65767. y_step = 1;
  65768. y_end = header.height;
  65769. break;
  65770. case TGATools._ORIGIN_BL:
  65771. x_start = 0;
  65772. x_step = 1;
  65773. x_end = header.width;
  65774. y_start = header.height - 1;
  65775. y_step = -1;
  65776. y_end = -1;
  65777. break;
  65778. case TGATools._ORIGIN_UR:
  65779. x_start = header.width - 1;
  65780. x_step = -1;
  65781. x_end = -1;
  65782. y_start = 0;
  65783. y_step = 1;
  65784. y_end = header.height;
  65785. break;
  65786. case TGATools._ORIGIN_BR:
  65787. x_start = header.width - 1;
  65788. x_step = -1;
  65789. x_end = -1;
  65790. y_start = header.height - 1;
  65791. y_step = -1;
  65792. y_end = -1;
  65793. break;
  65794. }
  65795. // Load the specify method
  65796. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  65797. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  65798. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  65799. };
  65800. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  65801. var image = pixel_data, colormap = palettes;
  65802. var width = header.width, height = header.height;
  65803. var color, i = 0, x, y;
  65804. var imageData = new Uint8Array(width * height * 4);
  65805. for (y = y_start; y !== y_end; y += y_step) {
  65806. for (x = x_start; x !== x_end; x += x_step, i++) {
  65807. color = image[i];
  65808. imageData[(x + width * y) * 4 + 3] = 255;
  65809. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  65810. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  65811. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  65812. }
  65813. }
  65814. return imageData;
  65815. };
  65816. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  65817. var image = pixel_data;
  65818. var width = header.width, height = header.height;
  65819. var color, i = 0, x, y;
  65820. var imageData = new Uint8Array(width * height * 4);
  65821. for (y = y_start; y !== y_end; y += y_step) {
  65822. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  65823. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  65824. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  65825. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  65826. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  65827. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  65828. }
  65829. }
  65830. return imageData;
  65831. };
  65832. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  65833. var image = pixel_data;
  65834. var width = header.width, height = header.height;
  65835. var i = 0, x, y;
  65836. var imageData = new Uint8Array(width * height * 4);
  65837. for (y = y_start; y !== y_end; y += y_step) {
  65838. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  65839. imageData[(x + width * y) * 4 + 3] = 255;
  65840. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  65841. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  65842. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  65843. }
  65844. }
  65845. return imageData;
  65846. };
  65847. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  65848. var image = pixel_data;
  65849. var width = header.width, height = header.height;
  65850. var i = 0, x, y;
  65851. var imageData = new Uint8Array(width * height * 4);
  65852. for (y = y_start; y !== y_end; y += y_step) {
  65853. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  65854. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  65855. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  65856. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  65857. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  65858. }
  65859. }
  65860. return imageData;
  65861. };
  65862. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  65863. var image = pixel_data;
  65864. var width = header.width, height = header.height;
  65865. var color, i = 0, x, y;
  65866. var imageData = new Uint8Array(width * height * 4);
  65867. for (y = y_start; y !== y_end; y += y_step) {
  65868. for (x = x_start; x !== x_end; x += x_step, i++) {
  65869. color = image[i];
  65870. imageData[(x + width * y) * 4 + 0] = color;
  65871. imageData[(x + width * y) * 4 + 1] = color;
  65872. imageData[(x + width * y) * 4 + 2] = color;
  65873. imageData[(x + width * y) * 4 + 3] = 255;
  65874. }
  65875. }
  65876. return imageData;
  65877. };
  65878. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  65879. var image = pixel_data;
  65880. var width = header.width, height = header.height;
  65881. var i = 0, x, y;
  65882. var imageData = new Uint8Array(width * height * 4);
  65883. for (y = y_start; y !== y_end; y += y_step) {
  65884. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  65885. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  65886. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  65887. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  65888. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  65889. }
  65890. }
  65891. return imageData;
  65892. };
  65893. //private static _TYPE_NO_DATA = 0;
  65894. TGATools._TYPE_INDEXED = 1;
  65895. TGATools._TYPE_RGB = 2;
  65896. TGATools._TYPE_GREY = 3;
  65897. TGATools._TYPE_RLE_INDEXED = 9;
  65898. TGATools._TYPE_RLE_RGB = 10;
  65899. TGATools._TYPE_RLE_GREY = 11;
  65900. TGATools._ORIGIN_MASK = 0x30;
  65901. TGATools._ORIGIN_SHIFT = 0x04;
  65902. TGATools._ORIGIN_BL = 0x00;
  65903. TGATools._ORIGIN_BR = 0x01;
  65904. TGATools._ORIGIN_UL = 0x02;
  65905. TGATools._ORIGIN_UR = 0x03;
  65906. return TGATools;
  65907. }());
  65908. Internals.TGATools = TGATools;
  65909. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  65910. })(BABYLON || (BABYLON = {}));
  65911. //# sourceMappingURL=babylon.tga.js.map
  65912. var BABYLON;
  65913. (function (BABYLON) {
  65914. var Internals;
  65915. (function (Internals) {
  65916. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  65917. // All values and structures referenced from:
  65918. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  65919. var DDS_MAGIC = 0x20534444;
  65920. var
  65921. //DDSD_CAPS = 0x1,
  65922. //DDSD_HEIGHT = 0x2,
  65923. //DDSD_WIDTH = 0x4,
  65924. //DDSD_PITCH = 0x8,
  65925. //DDSD_PIXELFORMAT = 0x1000,
  65926. DDSD_MIPMAPCOUNT = 0x20000;
  65927. //DDSD_LINEARSIZE = 0x80000,
  65928. //DDSD_DEPTH = 0x800000;
  65929. // var DDSCAPS_COMPLEX = 0x8,
  65930. // DDSCAPS_MIPMAP = 0x400000,
  65931. // DDSCAPS_TEXTURE = 0x1000;
  65932. var DDSCAPS2_CUBEMAP = 0x200;
  65933. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  65934. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  65935. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  65936. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  65937. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  65938. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  65939. // DDSCAPS2_VOLUME = 0x200000;
  65940. var
  65941. //DDPF_ALPHAPIXELS = 0x1,
  65942. //DDPF_ALPHA = 0x2,
  65943. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  65944. //DDPF_YUV = 0x200,
  65945. DDPF_LUMINANCE = 0x20000;
  65946. function FourCCToInt32(value) {
  65947. return value.charCodeAt(0) +
  65948. (value.charCodeAt(1) << 8) +
  65949. (value.charCodeAt(2) << 16) +
  65950. (value.charCodeAt(3) << 24);
  65951. }
  65952. function Int32ToFourCC(value) {
  65953. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  65954. }
  65955. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  65956. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  65957. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  65958. var FOURCC_DX10 = FourCCToInt32("DX10");
  65959. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  65960. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  65961. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  65962. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  65963. var headerLengthInt = 31; // The header length in 32 bit ints
  65964. // Offsets into the header array
  65965. var off_magic = 0;
  65966. var off_size = 1;
  65967. var off_flags = 2;
  65968. var off_height = 3;
  65969. var off_width = 4;
  65970. var off_mipmapCount = 7;
  65971. var off_pfFlags = 20;
  65972. var off_pfFourCC = 21;
  65973. var off_RGBbpp = 22;
  65974. // var off_RMask = 23;
  65975. // var off_GMask = 24;
  65976. // var off_BMask = 25;
  65977. // var off_AMask = 26;
  65978. // var off_caps1 = 27;
  65979. var off_caps2 = 28;
  65980. // var off_caps3 = 29;
  65981. // var off_caps4 = 30;
  65982. var off_dxgiFormat = 32;
  65983. ;
  65984. var DDSTools = /** @class */ (function () {
  65985. function DDSTools() {
  65986. }
  65987. DDSTools.GetDDSInfo = function (arrayBuffer) {
  65988. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  65989. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  65990. var mipmapCount = 1;
  65991. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  65992. mipmapCount = Math.max(1, header[off_mipmapCount]);
  65993. }
  65994. var fourCC = header[off_pfFourCC];
  65995. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  65996. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65997. switch (fourCC) {
  65998. case FOURCC_D3DFMT_R16G16B16A16F:
  65999. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66000. break;
  66001. case FOURCC_D3DFMT_R32G32B32A32F:
  66002. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66003. break;
  66004. case FOURCC_DX10:
  66005. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  66006. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66007. break;
  66008. }
  66009. }
  66010. return {
  66011. width: header[off_width],
  66012. height: header[off_height],
  66013. mipmapCount: mipmapCount,
  66014. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  66015. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  66016. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  66017. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  66018. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  66019. dxgiFormat: dxgiFormat,
  66020. textureType: textureType
  66021. };
  66022. };
  66023. DDSTools._ToHalfFloat = function (value) {
  66024. if (!DDSTools._FloatView) {
  66025. DDSTools._FloatView = new Float32Array(1);
  66026. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  66027. }
  66028. DDSTools._FloatView[0] = value;
  66029. var x = DDSTools._Int32View[0];
  66030. var bits = (x >> 16) & 0x8000; /* Get the sign */
  66031. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  66032. var e = (x >> 23) & 0xff; /* Using int is faster here */
  66033. /* If zero, or denormal, or exponent underflows too much for a denormal
  66034. * half, return signed zero. */
  66035. if (e < 103) {
  66036. return bits;
  66037. }
  66038. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  66039. if (e > 142) {
  66040. bits |= 0x7c00;
  66041. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  66042. * not Inf, so make sure we set one mantissa bit too. */
  66043. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  66044. return bits;
  66045. }
  66046. /* If exponent underflows but not too much, return a denormal */
  66047. if (e < 113) {
  66048. m |= 0x0800;
  66049. /* Extra rounding may overflow and set mantissa to 0 and exponent
  66050. * to 1, which is OK. */
  66051. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  66052. return bits;
  66053. }
  66054. bits |= ((e - 112) << 10) | (m >> 1);
  66055. bits += m & 1;
  66056. return bits;
  66057. };
  66058. DDSTools._FromHalfFloat = function (value) {
  66059. var s = (value & 0x8000) >> 15;
  66060. var e = (value & 0x7C00) >> 10;
  66061. var f = value & 0x03FF;
  66062. if (e === 0) {
  66063. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  66064. }
  66065. else if (e == 0x1F) {
  66066. return f ? NaN : ((s ? -1 : 1) * Infinity);
  66067. }
  66068. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  66069. };
  66070. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  66071. var destArray = new Float32Array(dataLength);
  66072. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  66073. var index = 0;
  66074. for (var y = 0; y < height; y++) {
  66075. for (var x = 0; x < width; x++) {
  66076. var srcPos = (x + y * width) * 4;
  66077. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  66078. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  66079. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  66080. if (DDSTools.StoreLODInAlphaChannel) {
  66081. destArray[index + 3] = lod;
  66082. }
  66083. else {
  66084. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  66085. }
  66086. index += 4;
  66087. }
  66088. }
  66089. return destArray;
  66090. };
  66091. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  66092. if (DDSTools.StoreLODInAlphaChannel) {
  66093. var destArray = new Uint16Array(dataLength);
  66094. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  66095. var index = 0;
  66096. for (var y = 0; y < height; y++) {
  66097. for (var x = 0; x < width; x++) {
  66098. var srcPos = (x + y * width) * 4;
  66099. destArray[index] = srcData[srcPos];
  66100. destArray[index + 1] = srcData[srcPos + 1];
  66101. destArray[index + 2] = srcData[srcPos + 2];
  66102. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  66103. index += 4;
  66104. }
  66105. }
  66106. return destArray;
  66107. }
  66108. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  66109. };
  66110. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  66111. if (DDSTools.StoreLODInAlphaChannel) {
  66112. var destArray = new Float32Array(dataLength);
  66113. var srcData = new Float32Array(arrayBuffer, dataOffset);
  66114. var index = 0;
  66115. for (var y = 0; y < height; y++) {
  66116. for (var x = 0; x < width; x++) {
  66117. var srcPos = (x + y * width) * 4;
  66118. destArray[index] = srcData[srcPos];
  66119. destArray[index + 1] = srcData[srcPos + 1];
  66120. destArray[index + 2] = srcData[srcPos + 2];
  66121. destArray[index + 3] = lod;
  66122. index += 4;
  66123. }
  66124. }
  66125. return destArray;
  66126. }
  66127. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  66128. };
  66129. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  66130. var destArray = new Uint8Array(dataLength);
  66131. var srcData = new Float32Array(arrayBuffer, dataOffset);
  66132. var index = 0;
  66133. for (var y = 0; y < height; y++) {
  66134. for (var x = 0; x < width; x++) {
  66135. var srcPos = (x + y * width) * 4;
  66136. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  66137. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  66138. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  66139. if (DDSTools.StoreLODInAlphaChannel) {
  66140. destArray[index + 3] = lod;
  66141. }
  66142. else {
  66143. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  66144. }
  66145. index += 4;
  66146. }
  66147. }
  66148. return destArray;
  66149. };
  66150. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  66151. var destArray = new Uint8Array(dataLength);
  66152. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  66153. var index = 0;
  66154. for (var y = 0; y < height; y++) {
  66155. for (var x = 0; x < width; x++) {
  66156. var srcPos = (x + y * width) * 4;
  66157. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  66158. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  66159. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  66160. if (DDSTools.StoreLODInAlphaChannel) {
  66161. destArray[index + 3] = lod;
  66162. }
  66163. else {
  66164. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  66165. }
  66166. index += 4;
  66167. }
  66168. }
  66169. return destArray;
  66170. };
  66171. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  66172. var byteArray = new Uint8Array(dataLength);
  66173. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  66174. var index = 0;
  66175. for (var y = 0; y < height; y++) {
  66176. for (var x = 0; x < width; x++) {
  66177. var srcPos = (x + y * width) * 4;
  66178. byteArray[index] = srcData[srcPos + 2];
  66179. byteArray[index + 1] = srcData[srcPos + 1];
  66180. byteArray[index + 2] = srcData[srcPos];
  66181. byteArray[index + 3] = srcData[srcPos + 3];
  66182. index += 4;
  66183. }
  66184. }
  66185. return byteArray;
  66186. };
  66187. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  66188. var byteArray = new Uint8Array(dataLength);
  66189. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  66190. var index = 0;
  66191. for (var y = 0; y < height; y++) {
  66192. for (var x = 0; x < width; x++) {
  66193. var srcPos = (x + y * width) * 3;
  66194. byteArray[index] = srcData[srcPos + 2];
  66195. byteArray[index + 1] = srcData[srcPos + 1];
  66196. byteArray[index + 2] = srcData[srcPos];
  66197. index += 3;
  66198. }
  66199. }
  66200. return byteArray;
  66201. };
  66202. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  66203. var byteArray = new Uint8Array(dataLength);
  66204. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  66205. var index = 0;
  66206. for (var y = 0; y < height; y++) {
  66207. for (var x = 0; x < width; x++) {
  66208. var srcPos = (x + y * width);
  66209. byteArray[index] = srcData[srcPos];
  66210. index++;
  66211. }
  66212. }
  66213. return byteArray;
  66214. };
  66215. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  66216. if (lodIndex === void 0) { lodIndex = -1; }
  66217. var ext = engine.getCaps().s3tc;
  66218. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  66219. var internalFormat = 0;
  66220. var format = 0;
  66221. var blockBytes = 1;
  66222. if (header[off_magic] != DDS_MAGIC) {
  66223. BABYLON.Tools.Error("Invalid magic number in DDS header");
  66224. return;
  66225. }
  66226. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  66227. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  66228. return;
  66229. }
  66230. if (info.isCompressed && !ext) {
  66231. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  66232. return;
  66233. }
  66234. var bpp = header[off_RGBbpp];
  66235. dataOffset = header[off_size] + 4;
  66236. var computeFormats = false;
  66237. if (info.isFourCC && ext) {
  66238. fourCC = header[off_pfFourCC];
  66239. switch (fourCC) {
  66240. case FOURCC_DXT1:
  66241. blockBytes = 8;
  66242. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  66243. break;
  66244. case FOURCC_DXT3:
  66245. blockBytes = 16;
  66246. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  66247. break;
  66248. case FOURCC_DXT5:
  66249. blockBytes = 16;
  66250. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  66251. break;
  66252. case FOURCC_D3DFMT_R16G16B16A16F:
  66253. computeFormats = true;
  66254. break;
  66255. case FOURCC_D3DFMT_R32G32B32A32F:
  66256. computeFormats = true;
  66257. break;
  66258. case FOURCC_DX10:
  66259. // There is an additionnal header so dataOffset need to be changed
  66260. dataOffset += 5 * 4; // 5 uints
  66261. var supported = false;
  66262. switch (info.dxgiFormat) {
  66263. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  66264. computeFormats = true;
  66265. supported = true;
  66266. break;
  66267. case DXGI_FORMAT_B8G8R8X8_UNORM:
  66268. info.isRGB = true;
  66269. info.isFourCC = false;
  66270. bpp = 32;
  66271. supported = true;
  66272. break;
  66273. }
  66274. if (supported) {
  66275. break;
  66276. }
  66277. default:
  66278. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  66279. return;
  66280. }
  66281. }
  66282. if (computeFormats) {
  66283. format = engine._getWebGLTextureType(info.textureType);
  66284. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  66285. }
  66286. mipmapCount = 1;
  66287. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  66288. mipmapCount = Math.max(1, header[off_mipmapCount]);
  66289. }
  66290. for (var face = 0; face < faces; face++) {
  66291. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  66292. width = header[off_width];
  66293. height = header[off_height];
  66294. for (mip = 0; mip < mipmapCount; ++mip) {
  66295. if (lodIndex === -1 || lodIndex === mip) {
  66296. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  66297. var i = (lodIndex === -1) ? mip : 0;
  66298. if (!info.isCompressed && info.isFourCC) {
  66299. dataLength = width * height * 4;
  66300. var floatArray = null;
  66301. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  66302. if (bpp === 128) {
  66303. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  66304. }
  66305. else if (bpp === 64) {
  66306. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  66307. }
  66308. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66309. format = engine._getWebGLTextureType(info.textureType);
  66310. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  66311. }
  66312. else {
  66313. if (bpp === 128) {
  66314. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  66315. }
  66316. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  66317. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  66318. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66319. format = engine._getWebGLTextureType(info.textureType);
  66320. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  66321. }
  66322. else {
  66323. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  66324. }
  66325. }
  66326. if (floatArray) {
  66327. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  66328. }
  66329. }
  66330. else if (info.isRGB) {
  66331. if (bpp === 24) {
  66332. dataLength = width * height * 3;
  66333. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  66334. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  66335. }
  66336. else {
  66337. dataLength = width * height * 4;
  66338. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  66339. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  66340. }
  66341. }
  66342. else if (info.isLuminance) {
  66343. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  66344. var unpaddedRowSize = width;
  66345. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  66346. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  66347. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  66348. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  66349. }
  66350. else {
  66351. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  66352. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  66353. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  66354. }
  66355. }
  66356. dataOffset += width * height * (bpp / 8);
  66357. width *= 0.5;
  66358. height *= 0.5;
  66359. width = Math.max(1.0, width);
  66360. height = Math.max(1.0, height);
  66361. }
  66362. }
  66363. };
  66364. DDSTools.StoreLODInAlphaChannel = false;
  66365. return DDSTools;
  66366. }());
  66367. Internals.DDSTools = DDSTools;
  66368. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  66369. })(BABYLON || (BABYLON = {}));
  66370. //# sourceMappingURL=babylon.dds.js.map
  66371. var BABYLON;
  66372. (function (BABYLON) {
  66373. var Internals;
  66374. (function (Internals) {
  66375. /**
  66376. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  66377. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  66378. */
  66379. var KhronosTextureContainer = /** @class */ (function () {
  66380. /**
  66381. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  66382. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  66383. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  66384. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  66385. */
  66386. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  66387. this.arrayBuffer = arrayBuffer;
  66388. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  66389. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  66390. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  66391. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  66392. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  66393. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  66394. BABYLON.Tools.Error("texture missing KTX identifier");
  66395. return;
  66396. }
  66397. // load the reset of the header in native 32 bit int
  66398. var header = new Int32Array(this.arrayBuffer, 12, 13);
  66399. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  66400. var oppositeEndianess = header[0] === 0x01020304;
  66401. // read all the header elements in order they exist in the file, without modification (sans endainness)
  66402. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  66403. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  66404. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  66405. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  66406. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  66407. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  66408. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  66409. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  66410. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  66411. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  66412. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  66413. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  66414. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  66415. if (this.glType !== 0) {
  66416. BABYLON.Tools.Error("only compressed formats currently supported");
  66417. return;
  66418. }
  66419. else {
  66420. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  66421. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  66422. }
  66423. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  66424. BABYLON.Tools.Error("only 2D textures currently supported");
  66425. return;
  66426. }
  66427. if (this.numberOfArrayElements !== 0) {
  66428. BABYLON.Tools.Error("texture arrays not currently supported");
  66429. return;
  66430. }
  66431. if (this.numberOfFaces !== facesExpected) {
  66432. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  66433. return;
  66434. }
  66435. // we now have a completely validated file, so could use existence of loadType as success
  66436. // would need to make this more elaborate & adjust checks above to support more than one load type
  66437. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  66438. }
  66439. // not as fast hardware based, but will probably never need to use
  66440. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  66441. return ((val & 0xFF) << 24)
  66442. | ((val & 0xFF00) << 8)
  66443. | ((val >> 8) & 0xFF00)
  66444. | ((val >> 24) & 0xFF);
  66445. };
  66446. /**
  66447. * It is assumed that the texture has already been created & is currently bound
  66448. */
  66449. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  66450. switch (this.loadType) {
  66451. case KhronosTextureContainer.COMPRESSED_2D:
  66452. this._upload2DCompressedLevels(gl, loadMipmaps);
  66453. break;
  66454. case KhronosTextureContainer.TEX_2D:
  66455. case KhronosTextureContainer.COMPRESSED_3D:
  66456. case KhronosTextureContainer.TEX_3D:
  66457. }
  66458. };
  66459. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  66460. // initialize width & height for level 1
  66461. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  66462. var width = this.pixelWidth;
  66463. var height = this.pixelHeight;
  66464. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  66465. for (var level = 0; level < mipmapCount; level++) {
  66466. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  66467. for (var face = 0; face < this.numberOfFaces; face++) {
  66468. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  66469. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  66470. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  66471. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  66472. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  66473. }
  66474. width = Math.max(1.0, width * 0.5);
  66475. height = Math.max(1.0, height * 0.5);
  66476. }
  66477. };
  66478. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  66479. // load types
  66480. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  66481. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  66482. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  66483. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  66484. return KhronosTextureContainer;
  66485. }());
  66486. Internals.KhronosTextureContainer = KhronosTextureContainer;
  66487. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  66488. })(BABYLON || (BABYLON = {}));
  66489. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  66490. var BABYLON;
  66491. (function (BABYLON) {
  66492. var Debug;
  66493. (function (Debug) {
  66494. /**
  66495. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  66496. */
  66497. var SkeletonViewer = /** @class */ (function () {
  66498. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  66499. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  66500. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  66501. this.skeleton = skeleton;
  66502. this.mesh = mesh;
  66503. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  66504. this.renderingGroupId = renderingGroupId;
  66505. this.color = BABYLON.Color3.White();
  66506. this._debugLines = new Array();
  66507. this._isEnabled = false;
  66508. this._scene = scene;
  66509. this.update();
  66510. this._renderFunction = this.update.bind(this);
  66511. }
  66512. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  66513. get: function () {
  66514. return this._isEnabled;
  66515. },
  66516. set: function (value) {
  66517. if (this._isEnabled === value) {
  66518. return;
  66519. }
  66520. this._isEnabled = value;
  66521. if (value) {
  66522. this._scene.registerBeforeRender(this._renderFunction);
  66523. }
  66524. else {
  66525. this._scene.unregisterBeforeRender(this._renderFunction);
  66526. }
  66527. },
  66528. enumerable: true,
  66529. configurable: true
  66530. });
  66531. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  66532. if (x === void 0) { x = 0; }
  66533. if (y === void 0) { y = 0; }
  66534. if (z === void 0) { z = 0; }
  66535. var tmat = BABYLON.Tmp.Matrix[0];
  66536. var parentBone = bone.getParent();
  66537. tmat.copyFrom(bone.getLocalMatrix());
  66538. if (x !== 0 || y !== 0 || z !== 0) {
  66539. var tmat2 = BABYLON.Tmp.Matrix[1];
  66540. BABYLON.Matrix.IdentityToRef(tmat2);
  66541. tmat2.m[12] = x;
  66542. tmat2.m[13] = y;
  66543. tmat2.m[14] = z;
  66544. tmat2.multiplyToRef(tmat, tmat);
  66545. }
  66546. if (parentBone) {
  66547. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  66548. }
  66549. tmat.multiplyToRef(meshMat, tmat);
  66550. position.x = tmat.m[12];
  66551. position.y = tmat.m[13];
  66552. position.z = tmat.m[14];
  66553. };
  66554. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  66555. var len = bones.length;
  66556. var meshPos = this.mesh.position;
  66557. for (var i = 0; i < len; i++) {
  66558. var bone = bones[i];
  66559. var points = this._debugLines[i];
  66560. if (!points) {
  66561. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  66562. this._debugLines[i] = points;
  66563. }
  66564. this._getBonePosition(points[0], bone, meshMat);
  66565. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  66566. points[0].subtractInPlace(meshPos);
  66567. points[1].subtractInPlace(meshPos);
  66568. }
  66569. };
  66570. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  66571. var len = bones.length;
  66572. var boneNum = 0;
  66573. var meshPos = this.mesh.position;
  66574. for (var i = len - 1; i >= 0; i--) {
  66575. var childBone = bones[i];
  66576. var parentBone = childBone.getParent();
  66577. if (!parentBone) {
  66578. continue;
  66579. }
  66580. var points = this._debugLines[boneNum];
  66581. if (!points) {
  66582. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  66583. this._debugLines[boneNum] = points;
  66584. }
  66585. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  66586. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  66587. points[0].subtractInPlace(meshPos);
  66588. points[1].subtractInPlace(meshPos);
  66589. boneNum++;
  66590. }
  66591. };
  66592. SkeletonViewer.prototype.update = function () {
  66593. if (this.autoUpdateBonesMatrices) {
  66594. this.skeleton.computeAbsoluteTransforms();
  66595. }
  66596. if (this.skeleton.bones[0].length === undefined) {
  66597. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  66598. }
  66599. else {
  66600. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  66601. }
  66602. if (!this._debugMesh) {
  66603. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true }, this._scene);
  66604. this._debugMesh.renderingGroupId = this.renderingGroupId;
  66605. }
  66606. else {
  66607. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  66608. }
  66609. this._debugMesh.position.copyFrom(this.mesh.position);
  66610. this._debugMesh.color = this.color;
  66611. };
  66612. SkeletonViewer.prototype.dispose = function () {
  66613. if (this._debugMesh) {
  66614. this.isEnabled = false;
  66615. this._debugMesh.dispose();
  66616. this._debugMesh = null;
  66617. }
  66618. };
  66619. return SkeletonViewer;
  66620. }());
  66621. Debug.SkeletonViewer = SkeletonViewer;
  66622. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  66623. })(BABYLON || (BABYLON = {}));
  66624. //# sourceMappingURL=babylon.skeletonViewer.js.map
  66625. var BABYLON;
  66626. (function (BABYLON) {
  66627. var Debug;
  66628. (function (Debug) {
  66629. var AxesViewer = /** @class */ (function () {
  66630. function AxesViewer(scene, scaleLines) {
  66631. if (scaleLines === void 0) { scaleLines = 1; }
  66632. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  66633. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  66634. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  66635. this.scaleLines = 1;
  66636. this.scaleLines = scaleLines;
  66637. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  66638. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  66639. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  66640. this._xmesh.renderingGroupId = 2;
  66641. this._ymesh.renderingGroupId = 2;
  66642. this._zmesh.renderingGroupId = 2;
  66643. this._xmesh.material.checkReadyOnlyOnce = true;
  66644. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  66645. this._ymesh.material.checkReadyOnlyOnce = true;
  66646. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  66647. this._zmesh.material.checkReadyOnlyOnce = true;
  66648. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  66649. this.scene = scene;
  66650. }
  66651. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  66652. var scaleLines = this.scaleLines;
  66653. if (this._xmesh) {
  66654. this._xmesh.position.copyFrom(position);
  66655. }
  66656. if (this._ymesh) {
  66657. this._ymesh.position.copyFrom(position);
  66658. }
  66659. if (this._zmesh) {
  66660. this._zmesh.position.copyFrom(position);
  66661. }
  66662. var point2 = this._xline[1];
  66663. point2.x = xaxis.x * scaleLines;
  66664. point2.y = xaxis.y * scaleLines;
  66665. point2.z = xaxis.z * scaleLines;
  66666. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  66667. point2 = this._yline[1];
  66668. point2.x = yaxis.x * scaleLines;
  66669. point2.y = yaxis.y * scaleLines;
  66670. point2.z = yaxis.z * scaleLines;
  66671. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  66672. point2 = this._zline[1];
  66673. point2.x = zaxis.x * scaleLines;
  66674. point2.y = zaxis.y * scaleLines;
  66675. point2.z = zaxis.z * scaleLines;
  66676. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  66677. };
  66678. AxesViewer.prototype.dispose = function () {
  66679. if (this._xmesh) {
  66680. this._xmesh.dispose();
  66681. }
  66682. if (this._ymesh) {
  66683. this._ymesh.dispose();
  66684. }
  66685. if (this._zmesh) {
  66686. this._zmesh.dispose();
  66687. }
  66688. this._xmesh = null;
  66689. this._ymesh = null;
  66690. this._zmesh = null;
  66691. this.scene = null;
  66692. };
  66693. return AxesViewer;
  66694. }());
  66695. Debug.AxesViewer = AxesViewer;
  66696. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  66697. })(BABYLON || (BABYLON = {}));
  66698. //# sourceMappingURL=babylon.axesViewer.js.map
  66699. var BABYLON;
  66700. (function (BABYLON) {
  66701. var Debug;
  66702. (function (Debug) {
  66703. var BoneAxesViewer = /** @class */ (function (_super) {
  66704. __extends(BoneAxesViewer, _super);
  66705. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  66706. if (scaleLines === void 0) { scaleLines = 1; }
  66707. var _this = _super.call(this, scene, scaleLines) || this;
  66708. _this.pos = BABYLON.Vector3.Zero();
  66709. _this.xaxis = BABYLON.Vector3.Zero();
  66710. _this.yaxis = BABYLON.Vector3.Zero();
  66711. _this.zaxis = BABYLON.Vector3.Zero();
  66712. _this.mesh = mesh;
  66713. _this.bone = bone;
  66714. return _this;
  66715. }
  66716. BoneAxesViewer.prototype.update = function () {
  66717. if (!this.mesh || !this.bone) {
  66718. return;
  66719. }
  66720. var bone = this.bone;
  66721. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  66722. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  66723. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  66724. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  66725. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  66726. };
  66727. BoneAxesViewer.prototype.dispose = function () {
  66728. if (this.mesh) {
  66729. this.mesh = null;
  66730. this.bone = null;
  66731. _super.prototype.dispose.call(this);
  66732. }
  66733. };
  66734. return BoneAxesViewer;
  66735. }(Debug.AxesViewer));
  66736. Debug.BoneAxesViewer = BoneAxesViewer;
  66737. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  66738. })(BABYLON || (BABYLON = {}));
  66739. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  66740. var BABYLON;
  66741. (function (BABYLON) {
  66742. var RayHelper = /** @class */ (function () {
  66743. function RayHelper(ray) {
  66744. this.ray = ray;
  66745. }
  66746. RayHelper.CreateAndShow = function (ray, scene, color) {
  66747. var helper = new RayHelper(ray);
  66748. helper.show(scene, color);
  66749. return helper;
  66750. };
  66751. RayHelper.prototype.show = function (scene, color) {
  66752. if (!this._renderFunction && this.ray) {
  66753. var ray = this.ray;
  66754. this._renderFunction = this._render.bind(this);
  66755. this._scene = scene;
  66756. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  66757. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  66758. if (this._renderFunction) {
  66759. this._scene.registerBeforeRender(this._renderFunction);
  66760. }
  66761. }
  66762. if (color && this._renderLine) {
  66763. this._renderLine.color.copyFrom(color);
  66764. }
  66765. };
  66766. RayHelper.prototype.hide = function () {
  66767. if (this._renderFunction && this._scene) {
  66768. this._scene.unregisterBeforeRender(this._renderFunction);
  66769. this._scene = null;
  66770. this._renderFunction = null;
  66771. if (this._renderLine) {
  66772. this._renderLine.dispose();
  66773. this._renderLine = null;
  66774. }
  66775. this._renderPoints = [];
  66776. }
  66777. };
  66778. RayHelper.prototype._render = function () {
  66779. var ray = this.ray;
  66780. if (!ray) {
  66781. return;
  66782. }
  66783. var point = this._renderPoints[1];
  66784. var len = Math.min(ray.length, 1000000);
  66785. point.copyFrom(ray.direction);
  66786. point.scaleInPlace(len);
  66787. point.addInPlace(ray.origin);
  66788. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  66789. };
  66790. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  66791. this._attachedToMesh = mesh;
  66792. var ray = this.ray;
  66793. if (!ray) {
  66794. return;
  66795. }
  66796. if (!ray.direction) {
  66797. ray.direction = BABYLON.Vector3.Zero();
  66798. }
  66799. if (!ray.origin) {
  66800. ray.origin = BABYLON.Vector3.Zero();
  66801. }
  66802. if (length) {
  66803. ray.length = length;
  66804. }
  66805. if (!meshSpaceOrigin) {
  66806. meshSpaceOrigin = BABYLON.Vector3.Zero();
  66807. }
  66808. if (!meshSpaceDirection) {
  66809. // -1 so that this will work with Mesh.lookAt
  66810. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  66811. }
  66812. if (!this._meshSpaceDirection) {
  66813. this._meshSpaceDirection = meshSpaceDirection.clone();
  66814. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  66815. }
  66816. else {
  66817. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  66818. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  66819. }
  66820. if (!this._updateToMeshFunction) {
  66821. this._updateToMeshFunction = this._updateToMesh.bind(this);
  66822. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  66823. }
  66824. this._updateToMesh();
  66825. };
  66826. RayHelper.prototype.detachFromMesh = function () {
  66827. if (this._attachedToMesh) {
  66828. if (this._updateToMeshFunction) {
  66829. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  66830. }
  66831. this._attachedToMesh = null;
  66832. this._updateToMeshFunction = null;
  66833. }
  66834. };
  66835. RayHelper.prototype._updateToMesh = function () {
  66836. var ray = this.ray;
  66837. if (!this._attachedToMesh || !ray) {
  66838. return;
  66839. }
  66840. if (this._attachedToMesh._isDisposed) {
  66841. this.detachFromMesh();
  66842. return;
  66843. }
  66844. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  66845. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  66846. };
  66847. RayHelper.prototype.dispose = function () {
  66848. this.hide();
  66849. this.detachFromMesh();
  66850. this.ray = null;
  66851. };
  66852. return RayHelper;
  66853. }());
  66854. BABYLON.RayHelper = RayHelper;
  66855. })(BABYLON || (BABYLON = {}));
  66856. //# sourceMappingURL=babylon.rayHelper.js.map
  66857. var BABYLON;
  66858. (function (BABYLON) {
  66859. var DebugLayer = /** @class */ (function () {
  66860. function DebugLayer(scene) {
  66861. this._scene = scene;
  66862. }
  66863. /** Creates the inspector window. */
  66864. DebugLayer.prototype._createInspector = function (config) {
  66865. if (config === void 0) { config = {}; }
  66866. var popup = config.popup || false;
  66867. var initialTab = config.initialTab || 0;
  66868. var parentElement = config.parentElement || null;
  66869. if (!this._inspector) {
  66870. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  66871. } // else nothing to do,; instance is already existing
  66872. };
  66873. DebugLayer.prototype.isVisible = function () {
  66874. if (!this._inspector) {
  66875. return false;
  66876. }
  66877. return true;
  66878. };
  66879. DebugLayer.prototype.hide = function () {
  66880. if (this._inspector) {
  66881. try {
  66882. this._inspector.dispose();
  66883. }
  66884. catch (e) {
  66885. // If the inspector has been removed directly from the inspector tool
  66886. }
  66887. this._inspector = null;
  66888. }
  66889. };
  66890. DebugLayer.prototype.show = function (config) {
  66891. if (config === void 0) { config = {}; }
  66892. if (typeof INSPECTOR == 'undefined') {
  66893. // Load inspector and add it to the DOM
  66894. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  66895. }
  66896. else {
  66897. // Otherwise creates the inspector
  66898. this._createInspector(config);
  66899. }
  66900. };
  66901. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  66902. return DebugLayer;
  66903. }());
  66904. BABYLON.DebugLayer = DebugLayer;
  66905. })(BABYLON || (BABYLON = {}));
  66906. //# sourceMappingURL=babylon.debugLayer.js.map
  66907. var BABYLON;
  66908. (function (BABYLON) {
  66909. var Debug;
  66910. (function (Debug) {
  66911. var PhysicsViewer = /** @class */ (function () {
  66912. function PhysicsViewer(scene) {
  66913. this._impostors = [];
  66914. this._meshes = [];
  66915. this._numMeshes = 0;
  66916. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  66917. var physicEngine = this._scene.getPhysicsEngine();
  66918. if (physicEngine) {
  66919. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  66920. }
  66921. }
  66922. PhysicsViewer.prototype._updateDebugMeshes = function () {
  66923. var plugin = this._physicsEnginePlugin;
  66924. for (var i = 0; i < this._numMeshes; i++) {
  66925. var impostor = this._impostors[i];
  66926. if (!impostor) {
  66927. continue;
  66928. }
  66929. if (impostor.isDisposed) {
  66930. this.hideImpostor(this._impostors[i--]);
  66931. }
  66932. else {
  66933. var mesh = this._meshes[i];
  66934. if (mesh && plugin) {
  66935. plugin.syncMeshWithImpostor(mesh, impostor);
  66936. }
  66937. }
  66938. }
  66939. };
  66940. PhysicsViewer.prototype.showImpostor = function (impostor) {
  66941. if (!this._scene) {
  66942. return;
  66943. }
  66944. for (var i = 0; i < this._numMeshes; i++) {
  66945. if (this._impostors[i] == impostor) {
  66946. return;
  66947. }
  66948. }
  66949. var debugMesh = this._getDebugMesh(impostor, this._scene);
  66950. if (debugMesh) {
  66951. this._impostors[this._numMeshes] = impostor;
  66952. this._meshes[this._numMeshes] = debugMesh;
  66953. if (this._numMeshes === 0) {
  66954. this._renderFunction = this._updateDebugMeshes.bind(this);
  66955. this._scene.registerBeforeRender(this._renderFunction);
  66956. }
  66957. this._numMeshes++;
  66958. }
  66959. };
  66960. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  66961. if (!impostor || !this._scene) {
  66962. return;
  66963. }
  66964. var removed = false;
  66965. for (var i = 0; i < this._numMeshes; i++) {
  66966. if (this._impostors[i] == impostor) {
  66967. var mesh = this._meshes[i];
  66968. if (!mesh) {
  66969. continue;
  66970. }
  66971. this._scene.removeMesh(mesh);
  66972. mesh.dispose();
  66973. this._numMeshes--;
  66974. if (this._numMeshes > 0) {
  66975. this._meshes[i] = this._meshes[this._numMeshes];
  66976. this._impostors[i] = this._impostors[this._numMeshes];
  66977. this._meshes[this._numMeshes] = null;
  66978. this._impostors[this._numMeshes] = null;
  66979. }
  66980. else {
  66981. this._meshes[0] = null;
  66982. this._impostors[0] = null;
  66983. }
  66984. removed = true;
  66985. break;
  66986. }
  66987. }
  66988. if (removed && this._numMeshes === 0) {
  66989. this._scene.unregisterBeforeRender(this._renderFunction);
  66990. }
  66991. };
  66992. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  66993. if (!this._debugMaterial) {
  66994. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  66995. this._debugMaterial.wireframe = true;
  66996. }
  66997. return this._debugMaterial;
  66998. };
  66999. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  67000. if (!this._debugBoxMesh) {
  67001. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  67002. this._debugBoxMesh.renderingGroupId = 1;
  67003. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  67004. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  67005. scene.removeMesh(this._debugBoxMesh);
  67006. }
  67007. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  67008. };
  67009. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  67010. if (!this._debugSphereMesh) {
  67011. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  67012. this._debugSphereMesh.renderingGroupId = 1;
  67013. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  67014. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  67015. scene.removeMesh(this._debugSphereMesh);
  67016. }
  67017. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  67018. };
  67019. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  67020. var mesh = null;
  67021. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  67022. mesh = this._getDebugBoxMesh(scene);
  67023. impostor.getBoxSizeToRef(mesh.scaling);
  67024. }
  67025. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  67026. mesh = this._getDebugSphereMesh(scene);
  67027. var radius = impostor.getRadius();
  67028. mesh.scaling.x = radius * 2;
  67029. mesh.scaling.y = radius * 2;
  67030. mesh.scaling.z = radius * 2;
  67031. }
  67032. return mesh;
  67033. };
  67034. PhysicsViewer.prototype.dispose = function () {
  67035. for (var i = 0; i < this._numMeshes; i++) {
  67036. this.hideImpostor(this._impostors[i]);
  67037. }
  67038. if (this._debugBoxMesh) {
  67039. this._debugBoxMesh.dispose();
  67040. }
  67041. if (this._debugSphereMesh) {
  67042. this._debugSphereMesh.dispose();
  67043. }
  67044. if (this._debugMaterial) {
  67045. this._debugMaterial.dispose();
  67046. }
  67047. this._impostors.length = 0;
  67048. this._scene = null;
  67049. this._physicsEnginePlugin = null;
  67050. };
  67051. return PhysicsViewer;
  67052. }());
  67053. Debug.PhysicsViewer = PhysicsViewer;
  67054. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67055. })(BABYLON || (BABYLON = {}));
  67056. //# sourceMappingURL=babylon.physicsViewer.js.map
  67057. var BABYLON;
  67058. (function (BABYLON) {
  67059. var BoundingBoxRenderer = /** @class */ (function () {
  67060. function BoundingBoxRenderer(scene) {
  67061. this.frontColor = new BABYLON.Color3(1, 1, 1);
  67062. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  67063. this.showBackLines = true;
  67064. this.renderList = new BABYLON.SmartArray(32);
  67065. this._vertexBuffers = {};
  67066. this._scene = scene;
  67067. }
  67068. BoundingBoxRenderer.prototype._prepareRessources = function () {
  67069. if (this._colorShader) {
  67070. return;
  67071. }
  67072. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  67073. attributes: [BABYLON.VertexBuffer.PositionKind],
  67074. uniforms: ["world", "viewProjection", "color"]
  67075. });
  67076. var engine = this._scene.getEngine();
  67077. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  67078. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  67079. this._createIndexBuffer();
  67080. };
  67081. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  67082. var engine = this._scene.getEngine();
  67083. 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]);
  67084. };
  67085. BoundingBoxRenderer.prototype._rebuild = function () {
  67086. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  67087. this._createIndexBuffer();
  67088. };
  67089. BoundingBoxRenderer.prototype.reset = function () {
  67090. this.renderList.reset();
  67091. };
  67092. BoundingBoxRenderer.prototype.render = function () {
  67093. if (this.renderList.length === 0) {
  67094. return;
  67095. }
  67096. this._prepareRessources();
  67097. if (!this._colorShader.isReady()) {
  67098. return;
  67099. }
  67100. var engine = this._scene.getEngine();
  67101. engine.setDepthWrite(false);
  67102. this._colorShader._preBind();
  67103. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  67104. var boundingBox = this.renderList.data[boundingBoxIndex];
  67105. var min = boundingBox.minimum;
  67106. var max = boundingBox.maximum;
  67107. var diff = max.subtract(min);
  67108. var median = min.add(diff.scale(0.5));
  67109. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  67110. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  67111. .multiply(boundingBox.getWorldMatrix());
  67112. // VBOs
  67113. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  67114. if (this.showBackLines) {
  67115. // Back
  67116. engine.setDepthFunctionToGreaterOrEqual();
  67117. this._scene.resetCachedMaterial();
  67118. this._colorShader.setColor4("color", this.backColor.toColor4());
  67119. this._colorShader.bind(worldMatrix);
  67120. // Draw order
  67121. engine.draw(false, 0, 24);
  67122. }
  67123. // Front
  67124. engine.setDepthFunctionToLess();
  67125. this._scene.resetCachedMaterial();
  67126. this._colorShader.setColor4("color", this.frontColor.toColor4());
  67127. this._colorShader.bind(worldMatrix);
  67128. // Draw order
  67129. engine.draw(false, 0, 24);
  67130. }
  67131. this._colorShader.unbind();
  67132. engine.setDepthFunctionToLessOrEqual();
  67133. engine.setDepthWrite(true);
  67134. };
  67135. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  67136. this._prepareRessources();
  67137. if (!this._colorShader.isReady()) {
  67138. return;
  67139. }
  67140. var engine = this._scene.getEngine();
  67141. engine.setDepthWrite(false);
  67142. engine.setColorWrite(false);
  67143. this._colorShader._preBind();
  67144. var boundingBox = mesh._boundingInfo.boundingBox;
  67145. var min = boundingBox.minimum;
  67146. var max = boundingBox.maximum;
  67147. var diff = max.subtract(min);
  67148. var median = min.add(diff.scale(0.5));
  67149. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  67150. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  67151. .multiply(boundingBox.getWorldMatrix());
  67152. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  67153. engine.setDepthFunctionToLess();
  67154. this._scene.resetCachedMaterial();
  67155. this._colorShader.bind(worldMatrix);
  67156. engine.draw(false, 0, 24);
  67157. this._colorShader.unbind();
  67158. engine.setDepthFunctionToLessOrEqual();
  67159. engine.setDepthWrite(true);
  67160. engine.setColorWrite(true);
  67161. };
  67162. BoundingBoxRenderer.prototype.dispose = function () {
  67163. if (!this._colorShader) {
  67164. return;
  67165. }
  67166. this.renderList.dispose();
  67167. this._colorShader.dispose();
  67168. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67169. if (buffer) {
  67170. buffer.dispose();
  67171. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  67172. }
  67173. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  67174. };
  67175. return BoundingBoxRenderer;
  67176. }());
  67177. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  67178. })(BABYLON || (BABYLON = {}));
  67179. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  67180. var BABYLON;
  67181. (function (BABYLON) {
  67182. var MorphTarget = /** @class */ (function () {
  67183. function MorphTarget(name, influence) {
  67184. if (influence === void 0) { influence = 0; }
  67185. this.name = name;
  67186. this.animations = new Array();
  67187. this.onInfluenceChanged = new BABYLON.Observable();
  67188. this.influence = influence;
  67189. }
  67190. Object.defineProperty(MorphTarget.prototype, "influence", {
  67191. get: function () {
  67192. return this._influence;
  67193. },
  67194. set: function (influence) {
  67195. if (this._influence === influence) {
  67196. return;
  67197. }
  67198. var previous = this._influence;
  67199. this._influence = influence;
  67200. if (this.onInfluenceChanged.hasObservers) {
  67201. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  67202. }
  67203. },
  67204. enumerable: true,
  67205. configurable: true
  67206. });
  67207. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  67208. get: function () {
  67209. return this._normals !== undefined;
  67210. },
  67211. enumerable: true,
  67212. configurable: true
  67213. });
  67214. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  67215. get: function () {
  67216. return this._tangents !== undefined;
  67217. },
  67218. enumerable: true,
  67219. configurable: true
  67220. });
  67221. MorphTarget.prototype.setPositions = function (data) {
  67222. this._positions = new Float32Array(data);
  67223. };
  67224. MorphTarget.prototype.getPositions = function () {
  67225. return this._positions;
  67226. };
  67227. MorphTarget.prototype.setNormals = function (data) {
  67228. this._normals = new Float32Array(data);
  67229. };
  67230. MorphTarget.prototype.getNormals = function () {
  67231. return this._normals;
  67232. };
  67233. MorphTarget.prototype.setTangents = function (data) {
  67234. this._tangents = new Float32Array(data);
  67235. };
  67236. MorphTarget.prototype.getTangents = function () {
  67237. return this._tangents;
  67238. };
  67239. /**
  67240. * Serializes the current target into a Serialization object.
  67241. * Returns the serialized object.
  67242. */
  67243. MorphTarget.prototype.serialize = function () {
  67244. var serializationObject = {};
  67245. serializationObject.name = this.name;
  67246. serializationObject.influence = this.influence;
  67247. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  67248. if (this.hasNormals) {
  67249. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  67250. }
  67251. if (this.hasTangents) {
  67252. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  67253. }
  67254. // Animations
  67255. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  67256. return serializationObject;
  67257. };
  67258. // Statics
  67259. MorphTarget.Parse = function (serializationObject) {
  67260. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  67261. result.setPositions(serializationObject.positions);
  67262. if (serializationObject.normals) {
  67263. result.setNormals(serializationObject.normals);
  67264. }
  67265. if (serializationObject.tangents) {
  67266. result.setTangents(serializationObject.tangents);
  67267. }
  67268. // Animations
  67269. if (serializationObject.animations) {
  67270. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  67271. var parsedAnimation = serializationObject.animations[animationIndex];
  67272. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  67273. }
  67274. }
  67275. return result;
  67276. };
  67277. MorphTarget.FromMesh = function (mesh, name, influence) {
  67278. if (!name) {
  67279. name = mesh.name;
  67280. }
  67281. var result = new MorphTarget(name, influence);
  67282. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  67283. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  67284. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  67285. }
  67286. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  67287. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  67288. }
  67289. return result;
  67290. };
  67291. return MorphTarget;
  67292. }());
  67293. BABYLON.MorphTarget = MorphTarget;
  67294. })(BABYLON || (BABYLON = {}));
  67295. //# sourceMappingURL=babylon.morphTarget.js.map
  67296. var BABYLON;
  67297. (function (BABYLON) {
  67298. var MorphTargetManager = /** @class */ (function () {
  67299. function MorphTargetManager(scene) {
  67300. this._targets = new Array();
  67301. this._targetObservable = new Array();
  67302. this._activeTargets = new BABYLON.SmartArray(16);
  67303. this._supportsNormals = false;
  67304. this._supportsTangents = false;
  67305. this._vertexCount = 0;
  67306. this._uniqueId = 0;
  67307. this._tempInfluences = new Array();
  67308. if (!scene) {
  67309. scene = BABYLON.Engine.LastCreatedScene;
  67310. }
  67311. this._scene = scene;
  67312. this._scene.morphTargetManagers.push(this);
  67313. this._uniqueId = scene.getUniqueId();
  67314. }
  67315. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  67316. get: function () {
  67317. return this._uniqueId;
  67318. },
  67319. enumerable: true,
  67320. configurable: true
  67321. });
  67322. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  67323. get: function () {
  67324. return this._vertexCount;
  67325. },
  67326. enumerable: true,
  67327. configurable: true
  67328. });
  67329. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  67330. get: function () {
  67331. return this._supportsNormals;
  67332. },
  67333. enumerable: true,
  67334. configurable: true
  67335. });
  67336. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  67337. get: function () {
  67338. return this._supportsTangents;
  67339. },
  67340. enumerable: true,
  67341. configurable: true
  67342. });
  67343. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  67344. get: function () {
  67345. return this._targets.length;
  67346. },
  67347. enumerable: true,
  67348. configurable: true
  67349. });
  67350. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  67351. get: function () {
  67352. return this._activeTargets.length;
  67353. },
  67354. enumerable: true,
  67355. configurable: true
  67356. });
  67357. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  67358. get: function () {
  67359. return this._influences;
  67360. },
  67361. enumerable: true,
  67362. configurable: true
  67363. });
  67364. MorphTargetManager.prototype.getActiveTarget = function (index) {
  67365. return this._activeTargets.data[index];
  67366. };
  67367. MorphTargetManager.prototype.getTarget = function (index) {
  67368. return this._targets[index];
  67369. };
  67370. MorphTargetManager.prototype.addTarget = function (target) {
  67371. var _this = this;
  67372. if (this._vertexCount) {
  67373. if (this._vertexCount !== target.getPositions().length / 3) {
  67374. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  67375. return;
  67376. }
  67377. }
  67378. this._targets.push(target);
  67379. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  67380. _this._syncActiveTargets(needUpdate);
  67381. }));
  67382. this._syncActiveTargets(true);
  67383. };
  67384. MorphTargetManager.prototype.removeTarget = function (target) {
  67385. var index = this._targets.indexOf(target);
  67386. if (index >= 0) {
  67387. this._targets.splice(index, 1);
  67388. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  67389. this._vertexCount = 0;
  67390. this._syncActiveTargets(true);
  67391. }
  67392. };
  67393. /**
  67394. * Serializes the current manager into a Serialization object.
  67395. * Returns the serialized object.
  67396. */
  67397. MorphTargetManager.prototype.serialize = function () {
  67398. var serializationObject = {};
  67399. serializationObject.id = this.uniqueId;
  67400. serializationObject.targets = [];
  67401. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  67402. var target = _a[_i];
  67403. serializationObject.targets.push(target.serialize());
  67404. }
  67405. return serializationObject;
  67406. };
  67407. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  67408. var influenceCount = 0;
  67409. this._activeTargets.reset();
  67410. this._supportsNormals = true;
  67411. this._supportsTangents = true;
  67412. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  67413. var target = _a[_i];
  67414. if (target.influence > 0) {
  67415. this._activeTargets.push(target);
  67416. this._tempInfluences[influenceCount++] = target.influence;
  67417. this._supportsNormals = this._supportsNormals && target.hasNormals;
  67418. this._supportsTangents = this._supportsTangents && target.hasTangents;
  67419. if (this._vertexCount === 0) {
  67420. this._vertexCount = target.getPositions().length / 3;
  67421. }
  67422. }
  67423. }
  67424. if (!this._influences || this._influences.length !== influenceCount) {
  67425. this._influences = new Float32Array(influenceCount);
  67426. }
  67427. for (var index = 0; index < influenceCount; index++) {
  67428. this._influences[index] = this._tempInfluences[index];
  67429. }
  67430. if (needUpdate) {
  67431. // Flag meshes as dirty to resync with the active targets
  67432. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  67433. var mesh = _c[_b];
  67434. if (mesh.morphTargetManager === this) {
  67435. mesh._syncGeometryWithMorphTargetManager();
  67436. }
  67437. }
  67438. }
  67439. };
  67440. // Statics
  67441. MorphTargetManager.Parse = function (serializationObject, scene) {
  67442. var result = new MorphTargetManager(scene);
  67443. result._uniqueId = serializationObject.id;
  67444. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  67445. var targetData = _a[_i];
  67446. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  67447. }
  67448. return result;
  67449. };
  67450. return MorphTargetManager;
  67451. }());
  67452. BABYLON.MorphTargetManager = MorphTargetManager;
  67453. })(BABYLON || (BABYLON = {}));
  67454. //# sourceMappingURL=babylon.morphTargetManager.js.map
  67455. var BABYLON;
  67456. (function (BABYLON) {
  67457. var Octree = /** @class */ (function () {
  67458. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  67459. if (maxDepth === void 0) { maxDepth = 2; }
  67460. this.maxDepth = maxDepth;
  67461. this.dynamicContent = new Array();
  67462. this._maxBlockCapacity = maxBlockCapacity || 64;
  67463. this._selectionContent = new BABYLON.SmartArray(1024);
  67464. this._creationFunc = creationFunc;
  67465. }
  67466. // Methods
  67467. Octree.prototype.update = function (worldMin, worldMax, entries) {
  67468. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  67469. };
  67470. Octree.prototype.addMesh = function (entry) {
  67471. for (var index = 0; index < this.blocks.length; index++) {
  67472. var block = this.blocks[index];
  67473. block.addEntry(entry);
  67474. }
  67475. };
  67476. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  67477. this._selectionContent.reset();
  67478. for (var index = 0; index < this.blocks.length; index++) {
  67479. var block = this.blocks[index];
  67480. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  67481. }
  67482. if (allowDuplicate) {
  67483. this._selectionContent.concat(this.dynamicContent);
  67484. }
  67485. else {
  67486. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  67487. }
  67488. return this._selectionContent;
  67489. };
  67490. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  67491. this._selectionContent.reset();
  67492. for (var index = 0; index < this.blocks.length; index++) {
  67493. var block = this.blocks[index];
  67494. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  67495. }
  67496. if (allowDuplicate) {
  67497. this._selectionContent.concat(this.dynamicContent);
  67498. }
  67499. else {
  67500. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  67501. }
  67502. return this._selectionContent;
  67503. };
  67504. Octree.prototype.intersectsRay = function (ray) {
  67505. this._selectionContent.reset();
  67506. for (var index = 0; index < this.blocks.length; index++) {
  67507. var block = this.blocks[index];
  67508. block.intersectsRay(ray, this._selectionContent);
  67509. }
  67510. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  67511. return this._selectionContent;
  67512. };
  67513. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  67514. target.blocks = new Array();
  67515. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  67516. // Segmenting space
  67517. for (var x = 0; x < 2; x++) {
  67518. for (var y = 0; y < 2; y++) {
  67519. for (var z = 0; z < 2; z++) {
  67520. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  67521. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  67522. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  67523. block.addEntries(entries);
  67524. target.blocks.push(block);
  67525. }
  67526. }
  67527. }
  67528. };
  67529. Octree.CreationFuncForMeshes = function (entry, block) {
  67530. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  67531. block.entries.push(entry);
  67532. }
  67533. };
  67534. Octree.CreationFuncForSubMeshes = function (entry, block) {
  67535. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  67536. block.entries.push(entry);
  67537. }
  67538. };
  67539. return Octree;
  67540. }());
  67541. BABYLON.Octree = Octree;
  67542. })(BABYLON || (BABYLON = {}));
  67543. //# sourceMappingURL=babylon.octree.js.map
  67544. var BABYLON;
  67545. (function (BABYLON) {
  67546. var OctreeBlock = /** @class */ (function () {
  67547. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  67548. this.entries = new Array();
  67549. this._boundingVectors = new Array();
  67550. this._capacity = capacity;
  67551. this._depth = depth;
  67552. this._maxDepth = maxDepth;
  67553. this._creationFunc = creationFunc;
  67554. this._minPoint = minPoint;
  67555. this._maxPoint = maxPoint;
  67556. this._boundingVectors.push(minPoint.clone());
  67557. this._boundingVectors.push(maxPoint.clone());
  67558. this._boundingVectors.push(minPoint.clone());
  67559. this._boundingVectors[2].x = maxPoint.x;
  67560. this._boundingVectors.push(minPoint.clone());
  67561. this._boundingVectors[3].y = maxPoint.y;
  67562. this._boundingVectors.push(minPoint.clone());
  67563. this._boundingVectors[4].z = maxPoint.z;
  67564. this._boundingVectors.push(maxPoint.clone());
  67565. this._boundingVectors[5].z = minPoint.z;
  67566. this._boundingVectors.push(maxPoint.clone());
  67567. this._boundingVectors[6].x = minPoint.x;
  67568. this._boundingVectors.push(maxPoint.clone());
  67569. this._boundingVectors[7].y = minPoint.y;
  67570. }
  67571. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  67572. // Property
  67573. get: function () {
  67574. return this._capacity;
  67575. },
  67576. enumerable: true,
  67577. configurable: true
  67578. });
  67579. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  67580. get: function () {
  67581. return this._minPoint;
  67582. },
  67583. enumerable: true,
  67584. configurable: true
  67585. });
  67586. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  67587. get: function () {
  67588. return this._maxPoint;
  67589. },
  67590. enumerable: true,
  67591. configurable: true
  67592. });
  67593. // Methods
  67594. OctreeBlock.prototype.addEntry = function (entry) {
  67595. if (this.blocks) {
  67596. for (var index = 0; index < this.blocks.length; index++) {
  67597. var block = this.blocks[index];
  67598. block.addEntry(entry);
  67599. }
  67600. return;
  67601. }
  67602. this._creationFunc(entry, this);
  67603. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  67604. this.createInnerBlocks();
  67605. }
  67606. };
  67607. OctreeBlock.prototype.addEntries = function (entries) {
  67608. for (var index = 0; index < entries.length; index++) {
  67609. var mesh = entries[index];
  67610. this.addEntry(mesh);
  67611. }
  67612. };
  67613. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  67614. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  67615. if (this.blocks) {
  67616. for (var index = 0; index < this.blocks.length; index++) {
  67617. var block = this.blocks[index];
  67618. block.select(frustumPlanes, selection, allowDuplicate);
  67619. }
  67620. return;
  67621. }
  67622. if (allowDuplicate) {
  67623. selection.concat(this.entries);
  67624. }
  67625. else {
  67626. selection.concatWithNoDuplicate(this.entries);
  67627. }
  67628. }
  67629. };
  67630. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  67631. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  67632. if (this.blocks) {
  67633. for (var index = 0; index < this.blocks.length; index++) {
  67634. var block = this.blocks[index];
  67635. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  67636. }
  67637. return;
  67638. }
  67639. if (allowDuplicate) {
  67640. selection.concat(this.entries);
  67641. }
  67642. else {
  67643. selection.concatWithNoDuplicate(this.entries);
  67644. }
  67645. }
  67646. };
  67647. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  67648. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  67649. if (this.blocks) {
  67650. for (var index = 0; index < this.blocks.length; index++) {
  67651. var block = this.blocks[index];
  67652. block.intersectsRay(ray, selection);
  67653. }
  67654. return;
  67655. }
  67656. selection.concatWithNoDuplicate(this.entries);
  67657. }
  67658. };
  67659. OctreeBlock.prototype.createInnerBlocks = function () {
  67660. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  67661. };
  67662. return OctreeBlock;
  67663. }());
  67664. BABYLON.OctreeBlock = OctreeBlock;
  67665. })(BABYLON || (BABYLON = {}));
  67666. //# sourceMappingURL=babylon.octreeBlock.js.map
  67667. var BABYLON;
  67668. (function (BABYLON) {
  67669. var SIMDVector3 = /** @class */ (function () {
  67670. function SIMDVector3() {
  67671. }
  67672. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  67673. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  67674. };
  67675. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  67676. var m = transformation.m;
  67677. var m0 = SIMD.Float32x4.load(m, 0);
  67678. var m1 = SIMD.Float32x4.load(m, 4);
  67679. var m2 = SIMD.Float32x4.load(m, 8);
  67680. var m3 = SIMD.Float32x4.load(m, 12);
  67681. 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));
  67682. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  67683. result.x = SIMD.Float32x4.extractLane(r, 0);
  67684. result.y = SIMD.Float32x4.extractLane(r, 1);
  67685. result.z = SIMD.Float32x4.extractLane(r, 2);
  67686. };
  67687. return SIMDVector3;
  67688. }());
  67689. var SIMDMatrix = /** @class */ (function () {
  67690. function SIMDMatrix() {
  67691. }
  67692. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  67693. var tm = this.m;
  67694. var om = other.m;
  67695. var m0 = SIMD.Float32x4.load(om, 0);
  67696. var m1 = SIMD.Float32x4.load(om, 4);
  67697. var m2 = SIMD.Float32x4.load(om, 8);
  67698. var m3 = SIMD.Float32x4.load(om, 12);
  67699. for (var i = 0; i < 16; i += 4) {
  67700. 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)))));
  67701. }
  67702. return this;
  67703. };
  67704. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  67705. var src = this.m;
  67706. var dest = other.m;
  67707. // Load the 4 rows
  67708. var src0 = SIMD.Float32x4.load(src, 0);
  67709. var src1 = SIMD.Float32x4.load(src, 4);
  67710. var src2 = SIMD.Float32x4.load(src, 8);
  67711. var src3 = SIMD.Float32x4.load(src, 12);
  67712. // Transpose the source matrix. Sort of. Not a true transpose operation
  67713. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  67714. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  67715. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  67716. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  67717. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  67718. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  67719. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  67720. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  67721. // This is a true transposition, but it will lead to an incorrect result
  67722. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  67723. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  67724. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  67725. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  67726. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  67727. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  67728. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  67729. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  67730. // ----
  67731. tmp1 = SIMD.Float32x4.mul(row2, row3);
  67732. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  67733. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  67734. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  67735. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  67736. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  67737. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  67738. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  67739. // ----
  67740. tmp1 = SIMD.Float32x4.mul(row1, row2);
  67741. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  67742. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  67743. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  67744. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  67745. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  67746. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  67747. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  67748. // ----
  67749. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  67750. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  67751. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  67752. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  67753. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  67754. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  67755. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  67756. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  67757. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  67758. // ----
  67759. tmp1 = SIMD.Float32x4.mul(row0, row1);
  67760. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  67761. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  67762. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  67763. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  67764. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  67765. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  67766. // ----
  67767. tmp1 = SIMD.Float32x4.mul(row0, row3);
  67768. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  67769. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  67770. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  67771. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  67772. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  67773. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  67774. // ----
  67775. tmp1 = SIMD.Float32x4.mul(row0, row2);
  67776. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  67777. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  67778. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  67779. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  67780. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  67781. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  67782. // Compute determinant
  67783. var det = SIMD.Float32x4.mul(row0, minor0);
  67784. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  67785. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  67786. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  67787. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  67788. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  67789. // These shuffles aren't necessary if the faulty transposition is done
  67790. // up at the top of this function.
  67791. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  67792. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  67793. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  67794. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  67795. // Compute final values by multiplying with 1/det
  67796. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  67797. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  67798. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  67799. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  67800. return this;
  67801. };
  67802. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  67803. var out = result.m;
  67804. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  67805. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  67806. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  67807. // cc.kmVec3Subtract(f, pCenter, pEye);
  67808. var f = SIMD.Float32x4.sub(center, eye);
  67809. // cc.kmVec3Normalize(f, f);
  67810. var tmp = SIMD.Float32x4.mul(f, f);
  67811. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  67812. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  67813. // cc.kmVec3Assign(up, pUp);
  67814. // cc.kmVec3Normalize(up, up);
  67815. tmp = SIMD.Float32x4.mul(up, up);
  67816. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  67817. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  67818. // cc.kmVec3Cross(s, f, up);
  67819. 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)));
  67820. // cc.kmVec3Normalize(s, s);
  67821. tmp = SIMD.Float32x4.mul(s, s);
  67822. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  67823. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  67824. // cc.kmVec3Cross(u, s, f);
  67825. 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)));
  67826. // cc.kmVec3Normalize(s, s);
  67827. tmp = SIMD.Float32x4.mul(s, s);
  67828. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  67829. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  67830. var zero = SIMD.Float32x4.splat(0.0);
  67831. s = SIMD.Float32x4.neg(s);
  67832. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  67833. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  67834. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  67835. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  67836. 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);
  67837. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  67838. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  67839. 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)))));
  67840. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  67841. 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)))));
  67842. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  67843. 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)))));
  67844. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  67845. 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)))));
  67846. };
  67847. return SIMDMatrix;
  67848. }());
  67849. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  67850. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  67851. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  67852. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  67853. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  67854. var SIMDHelper = /** @class */ (function () {
  67855. function SIMDHelper() {
  67856. }
  67857. Object.defineProperty(SIMDHelper, "IsEnabled", {
  67858. get: function () {
  67859. return SIMDHelper._isEnabled;
  67860. },
  67861. enumerable: true,
  67862. configurable: true
  67863. });
  67864. SIMDHelper.DisableSIMD = function () {
  67865. // Replace functions
  67866. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  67867. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  67868. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  67869. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  67870. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  67871. SIMDHelper._isEnabled = false;
  67872. };
  67873. SIMDHelper.EnableSIMD = function () {
  67874. if (self.SIMD === undefined) {
  67875. return;
  67876. }
  67877. // check if polyfills needed
  67878. if (!self.Math.fround) {
  67879. self.Math.fround = (function (array) { return function (x) {
  67880. return array[0] = x, array[0];
  67881. }; })(new Float32Array(1));
  67882. }
  67883. if (!self.Math.imul) {
  67884. self.Math.imul = function (a, b) {
  67885. var ah = (a >>> 16) & 0xffff;
  67886. var al = a & 0xffff;
  67887. var bh = (b >>> 16) & 0xffff;
  67888. var bl = b & 0xffff;
  67889. // the shift by 0 fixes the sign on the high part
  67890. // the final |0 converts the unsigned value into a signed value
  67891. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  67892. };
  67893. }
  67894. // Replace functions
  67895. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  67896. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  67897. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  67898. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  67899. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  67900. SIMDHelper._isEnabled = true;
  67901. };
  67902. SIMDHelper._isEnabled = false;
  67903. return SIMDHelper;
  67904. }());
  67905. BABYLON.SIMDHelper = SIMDHelper;
  67906. })(BABYLON || (BABYLON = {}));
  67907. //# sourceMappingURL=babylon.math.SIMD.js.map
  67908. var BABYLON;
  67909. (function (BABYLON) {
  67910. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  67911. __extends(VRDistortionCorrectionPostProcess, _super);
  67912. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  67913. var _this = _super.call(this, name, "vrDistortionCorrection", [
  67914. 'LensCenter',
  67915. 'Scale',
  67916. 'ScaleIn',
  67917. 'HmdWarpParam'
  67918. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  67919. _this._isRightEye = isRightEye;
  67920. _this._distortionFactors = vrMetrics.distortionK;
  67921. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  67922. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  67923. _this.adaptScaleToCurrentViewport = true;
  67924. _this.onSizeChangedObservable.add(function () {
  67925. _this.aspectRatio = _this.width * .5 / _this.height;
  67926. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  67927. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  67928. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  67929. });
  67930. _this.onApplyObservable.add(function (effect) {
  67931. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  67932. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  67933. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  67934. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  67935. });
  67936. return _this;
  67937. }
  67938. return VRDistortionCorrectionPostProcess;
  67939. }(BABYLON.PostProcess));
  67940. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  67941. })(BABYLON || (BABYLON = {}));
  67942. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  67943. var BABYLON;
  67944. (function (BABYLON) {
  67945. var AnaglyphPostProcess = /** @class */ (function (_super) {
  67946. __extends(AnaglyphPostProcess, _super);
  67947. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  67948. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  67949. _this._passedProcess = rigCameras[0]._rigPostProcess;
  67950. _this.onApplyObservable.add(function (effect) {
  67951. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  67952. });
  67953. return _this;
  67954. }
  67955. return AnaglyphPostProcess;
  67956. }(BABYLON.PostProcess));
  67957. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  67958. })(BABYLON || (BABYLON = {}));
  67959. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  67960. var BABYLON;
  67961. (function (BABYLON) {
  67962. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  67963. __extends(StereoscopicInterlacePostProcess, _super);
  67964. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  67965. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  67966. _this._passedProcess = rigCameras[0]._rigPostProcess;
  67967. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  67968. _this.onSizeChangedObservable.add(function () {
  67969. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  67970. });
  67971. _this.onApplyObservable.add(function (effect) {
  67972. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  67973. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  67974. });
  67975. return _this;
  67976. }
  67977. return StereoscopicInterlacePostProcess;
  67978. }(BABYLON.PostProcess));
  67979. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  67980. })(BABYLON || (BABYLON = {}));
  67981. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  67982. var BABYLON;
  67983. (function (BABYLON) {
  67984. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  67985. function FreeCameraDeviceOrientationInput() {
  67986. var _this = this;
  67987. this._screenOrientationAngle = 0;
  67988. this._screenQuaternion = new BABYLON.Quaternion();
  67989. this._alpha = 0;
  67990. this._beta = 0;
  67991. this._gamma = 0;
  67992. this._orientationChanged = function () {
  67993. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  67994. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  67995. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  67996. };
  67997. this._deviceOrientation = function (evt) {
  67998. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  67999. _this._beta = evt.beta !== null ? evt.beta : 0;
  68000. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  68001. };
  68002. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  68003. this._orientationChanged();
  68004. }
  68005. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  68006. get: function () {
  68007. return this._camera;
  68008. },
  68009. set: function (camera) {
  68010. this._camera = camera;
  68011. if (this._camera != null && !this._camera.rotationQuaternion) {
  68012. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  68013. }
  68014. },
  68015. enumerable: true,
  68016. configurable: true
  68017. });
  68018. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  68019. window.addEventListener("orientationchange", this._orientationChanged);
  68020. window.addEventListener("deviceorientation", this._deviceOrientation);
  68021. //In certain cases, the attach control is called AFTER orientation was changed,
  68022. //So this is needed.
  68023. this._orientationChanged();
  68024. };
  68025. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  68026. window.removeEventListener("orientationchange", this._orientationChanged);
  68027. window.removeEventListener("deviceorientation", this._deviceOrientation);
  68028. };
  68029. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  68030. //if no device orientation provided, don't update the rotation.
  68031. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  68032. if (!this._alpha)
  68033. return;
  68034. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  68035. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  68036. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  68037. //Mirror on XY Plane
  68038. this._camera.rotationQuaternion.z *= -1;
  68039. this._camera.rotationQuaternion.w *= -1;
  68040. };
  68041. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  68042. return "FreeCameraDeviceOrientationInput";
  68043. };
  68044. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  68045. return "deviceOrientation";
  68046. };
  68047. return FreeCameraDeviceOrientationInput;
  68048. }());
  68049. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  68050. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  68051. })(BABYLON || (BABYLON = {}));
  68052. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  68053. var BABYLON;
  68054. (function (BABYLON) {
  68055. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  68056. function ArcRotateCameraVRDeviceOrientationInput() {
  68057. this.alphaCorrection = 1;
  68058. this.betaCorrection = 1;
  68059. this.gammaCorrection = 1;
  68060. this._alpha = 0;
  68061. this._beta = 0;
  68062. this._gamma = 0;
  68063. this._dirty = false;
  68064. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  68065. }
  68066. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  68067. this.camera.attachControl(element, noPreventDefault);
  68068. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  68069. };
  68070. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  68071. if (evt.alpha !== null) {
  68072. this._alpha = +evt.alpha | 0;
  68073. }
  68074. if (evt.beta !== null) {
  68075. this._beta = +evt.beta | 0;
  68076. }
  68077. if (evt.gamma !== null) {
  68078. this._gamma = +evt.gamma | 0;
  68079. }
  68080. this._dirty = true;
  68081. };
  68082. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  68083. if (this._dirty) {
  68084. this._dirty = false;
  68085. if (this._gamma < 0) {
  68086. this._gamma = 180 + this._gamma;
  68087. }
  68088. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  68089. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  68090. }
  68091. };
  68092. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  68093. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  68094. };
  68095. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  68096. return "ArcRotateCameraVRDeviceOrientationInput";
  68097. };
  68098. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  68099. return "VRDeviceOrientation";
  68100. };
  68101. return ArcRotateCameraVRDeviceOrientationInput;
  68102. }());
  68103. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  68104. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  68105. })(BABYLON || (BABYLON = {}));
  68106. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  68107. var BABYLON;
  68108. (function (BABYLON) {
  68109. var VRCameraMetrics = /** @class */ (function () {
  68110. function VRCameraMetrics() {
  68111. this.compensateDistortion = true;
  68112. }
  68113. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  68114. get: function () {
  68115. return this.hResolution / (2 * this.vResolution);
  68116. },
  68117. enumerable: true,
  68118. configurable: true
  68119. });
  68120. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  68121. get: function () {
  68122. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  68123. },
  68124. enumerable: true,
  68125. configurable: true
  68126. });
  68127. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  68128. get: function () {
  68129. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  68130. var h = (4 * meters) / this.hScreenSize;
  68131. return BABYLON.Matrix.Translation(h, 0, 0);
  68132. },
  68133. enumerable: true,
  68134. configurable: true
  68135. });
  68136. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  68137. get: function () {
  68138. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  68139. var h = (4 * meters) / this.hScreenSize;
  68140. return BABYLON.Matrix.Translation(-h, 0, 0);
  68141. },
  68142. enumerable: true,
  68143. configurable: true
  68144. });
  68145. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  68146. get: function () {
  68147. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  68148. },
  68149. enumerable: true,
  68150. configurable: true
  68151. });
  68152. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  68153. get: function () {
  68154. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  68155. },
  68156. enumerable: true,
  68157. configurable: true
  68158. });
  68159. VRCameraMetrics.GetDefault = function () {
  68160. var result = new VRCameraMetrics();
  68161. result.hResolution = 1280;
  68162. result.vResolution = 800;
  68163. result.hScreenSize = 0.149759993;
  68164. result.vScreenSize = 0.0935999975;
  68165. result.vScreenCenter = 0.0467999987;
  68166. result.eyeToScreenDistance = 0.0410000011;
  68167. result.lensSeparationDistance = 0.0635000020;
  68168. result.interpupillaryDistance = 0.0640000030;
  68169. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  68170. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  68171. result.postProcessScaleFactor = 1.714605507808412;
  68172. result.lensCenterOffset = 0.151976421;
  68173. return result;
  68174. };
  68175. return VRCameraMetrics;
  68176. }());
  68177. BABYLON.VRCameraMetrics = VRCameraMetrics;
  68178. })(BABYLON || (BABYLON = {}));
  68179. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  68180. var BABYLON;
  68181. (function (BABYLON) {
  68182. var WebVRFreeCamera = /** @class */ (function (_super) {
  68183. __extends(WebVRFreeCamera, _super);
  68184. function WebVRFreeCamera(name, position, scene, webVROptions) {
  68185. if (webVROptions === void 0) { webVROptions = {}; }
  68186. var _this = _super.call(this, name, position, scene) || this;
  68187. _this.webVROptions = webVROptions;
  68188. _this._vrDevice = null;
  68189. _this.rawPose = null;
  68190. _this._specsVersion = "1.1";
  68191. _this._attached = false;
  68192. _this._descendants = [];
  68193. _this.devicePosition = BABYLON.Vector3.Zero();
  68194. _this.deviceScaleFactor = 1;
  68195. _this.controllers = [];
  68196. _this.onControllersAttachedObservable = new BABYLON.Observable();
  68197. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  68198. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  68199. _this.minZ = 0.1;
  68200. //legacy support - the compensation boolean was removed.
  68201. if (arguments.length === 5) {
  68202. _this.webVROptions = arguments[4];
  68203. }
  68204. // default webVR options
  68205. if (_this.webVROptions.trackPosition == undefined) {
  68206. _this.webVROptions.trackPosition = true;
  68207. }
  68208. if (_this.webVROptions.controllerMeshes == undefined) {
  68209. _this.webVROptions.controllerMeshes = true;
  68210. }
  68211. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  68212. _this.webVROptions.defaultLightingOnControllers = true;
  68213. }
  68214. _this.rotationQuaternion = new BABYLON.Quaternion();
  68215. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  68216. if (_this.webVROptions && _this.webVROptions.positionScale) {
  68217. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  68218. }
  68219. //enable VR
  68220. var engine = _this.getEngine();
  68221. _this._onVREnabled = function (success) { if (success) {
  68222. _this.initControllers();
  68223. } };
  68224. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  68225. engine.initWebVR().add(function (event) {
  68226. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  68227. return;
  68228. }
  68229. _this._vrDevice = event.vrDisplay;
  68230. //reset the rig parameters.
  68231. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  68232. if (_this._attached) {
  68233. _this.getEngine().enableVR();
  68234. }
  68235. });
  68236. if (typeof (VRFrameData) !== "undefined")
  68237. _this._frameData = new VRFrameData();
  68238. /**
  68239. * The idea behind the following lines:
  68240. * objects that have the camera as parent should actually have the rig cameras as a parent.
  68241. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  68242. * the second will not show it correctly.
  68243. *
  68244. * To solve this - each object that has the camera as parent will be added to a protected array.
  68245. * When the rig camera renders, it will take this array and set all of those to be its children.
  68246. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  68247. * Amazing!
  68248. */
  68249. scene.onBeforeCameraRenderObservable.add(function (camera) {
  68250. if (camera.parent === _this && _this.rigParenting) {
  68251. _this._descendants = _this.getDescendants(true, function (n) {
  68252. // don't take the cameras or the controllers!
  68253. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  68254. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  68255. return !isController && !isRigCamera;
  68256. });
  68257. _this._descendants.forEach(function (node) {
  68258. node.parent = camera;
  68259. });
  68260. }
  68261. });
  68262. scene.onAfterCameraRenderObservable.add(function (camera) {
  68263. if (camera.parent === _this && _this.rigParenting) {
  68264. _this._descendants.forEach(function (node) {
  68265. node.parent = _this;
  68266. });
  68267. }
  68268. });
  68269. return _this;
  68270. }
  68271. WebVRFreeCamera.prototype.dispose = function () {
  68272. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  68273. _super.prototype.dispose.call(this);
  68274. };
  68275. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  68276. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  68277. var gp = _a[_i];
  68278. if (gp.hand === name) {
  68279. return gp;
  68280. }
  68281. }
  68282. return null;
  68283. };
  68284. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  68285. get: function () {
  68286. if (!this._leftController) {
  68287. this._leftController = this.getControllerByName("left");
  68288. }
  68289. return this._leftController;
  68290. },
  68291. enumerable: true,
  68292. configurable: true
  68293. });
  68294. ;
  68295. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  68296. get: function () {
  68297. if (!this._rightController) {
  68298. this._rightController = this.getControllerByName("right");
  68299. }
  68300. return this._rightController;
  68301. },
  68302. enumerable: true,
  68303. configurable: true
  68304. });
  68305. ;
  68306. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  68307. if (length === void 0) { length = 100; }
  68308. if (this.leftCamera) {
  68309. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  68310. }
  68311. else {
  68312. return _super.prototype.getForwardRay.call(this, length);
  68313. }
  68314. };
  68315. WebVRFreeCamera.prototype._checkInputs = function () {
  68316. if (this._vrDevice && this._vrDevice.isPresenting) {
  68317. this._vrDevice.getFrameData(this._frameData);
  68318. this.updateFromDevice(this._frameData.pose);
  68319. }
  68320. _super.prototype._checkInputs.call(this);
  68321. };
  68322. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  68323. if (poseData && poseData.orientation) {
  68324. this.rawPose = poseData;
  68325. this.deviceRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  68326. if (this.getScene().useRightHandedSystem) {
  68327. this.deviceRotationQuaternion.z *= -1;
  68328. this.deviceRotationQuaternion.w *= -1;
  68329. }
  68330. if (this.webVROptions.trackPosition && this.rawPose.position) {
  68331. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  68332. if (this.getScene().useRightHandedSystem) {
  68333. this.devicePosition.z *= -1;
  68334. }
  68335. }
  68336. }
  68337. };
  68338. /**
  68339. * WebVR's attach control will start broadcasting frames to the device.
  68340. * Note that in certain browsers (chrome for example) this function must be called
  68341. * within a user-interaction callback. Example:
  68342. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  68343. *
  68344. * @param {HTMLElement} element
  68345. * @param {boolean} [noPreventDefault]
  68346. *
  68347. * @memberOf WebVRFreeCamera
  68348. */
  68349. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  68350. _super.prototype.attachControl.call(this, element, noPreventDefault);
  68351. this._attached = true;
  68352. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  68353. if (this._vrDevice) {
  68354. this.getEngine().enableVR();
  68355. }
  68356. };
  68357. WebVRFreeCamera.prototype.detachControl = function (element) {
  68358. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  68359. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  68360. _super.prototype.detachControl.call(this, element);
  68361. this._attached = false;
  68362. this.getEngine().disableVR();
  68363. };
  68364. WebVRFreeCamera.prototype.getClassName = function () {
  68365. return "WebVRFreeCamera";
  68366. };
  68367. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  68368. //uses the vrDisplay's "resetPose()".
  68369. //pitch and roll won't be affected.
  68370. this._vrDevice.resetPose();
  68371. };
  68372. WebVRFreeCamera.prototype._updateRigCameras = function () {
  68373. var camLeft = this._rigCameras[0];
  68374. var camRight = this._rigCameras[1];
  68375. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  68376. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  68377. camLeft.position.copyFrom(this.devicePosition);
  68378. camRight.position.copyFrom(this.devicePosition);
  68379. };
  68380. /**
  68381. * This function is called by the two RIG cameras.
  68382. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  68383. */
  68384. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  68385. var _this = this;
  68386. //WebVR 1.1
  68387. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  68388. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  68389. if (!this.getScene().useRightHandedSystem) {
  68390. [2, 6, 8, 9, 14].forEach(function (num) {
  68391. _this._webvrViewMatrix.m[num] *= -1;
  68392. });
  68393. }
  68394. // update the camera rotation matrix
  68395. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  68396. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  68397. // Computing target and final matrix
  68398. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  68399. var parentCamera = this._cameraRigParams["parentCamera"];
  68400. // should the view matrix be updated with scale and position offset?
  68401. if (parentCamera.deviceScaleFactor !== 1) {
  68402. this._webvrViewMatrix.invert();
  68403. // scale the position, if set
  68404. if (parentCamera.deviceScaleFactor) {
  68405. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  68406. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  68407. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  68408. }
  68409. this._webvrViewMatrix.invert();
  68410. }
  68411. return this._webvrViewMatrix;
  68412. };
  68413. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  68414. var _this = this;
  68415. var parentCamera = this.parent;
  68416. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  68417. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  68418. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  68419. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  68420. //babylon compatible matrix
  68421. if (!this.getScene().useRightHandedSystem) {
  68422. [8, 9, 10, 11].forEach(function (num) {
  68423. _this._projectionMatrix.m[num] *= -1;
  68424. });
  68425. }
  68426. return this._projectionMatrix;
  68427. };
  68428. WebVRFreeCamera.prototype.initControllers = function () {
  68429. var _this = this;
  68430. this.controllers = [];
  68431. var manager = this.getScene().gamepadManager;
  68432. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  68433. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  68434. var webVrController = gamepad;
  68435. if (webVrController.defaultModel) {
  68436. webVrController.defaultModel.setEnabled(false);
  68437. }
  68438. }
  68439. });
  68440. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  68441. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  68442. var webVrController_1 = gamepad;
  68443. if (_this.webVROptions.controllerMeshes) {
  68444. if (webVrController_1.defaultModel) {
  68445. webVrController_1.defaultModel.setEnabled(true);
  68446. }
  68447. else {
  68448. // Load the meshes
  68449. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  68450. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  68451. if (_this.webVROptions.defaultLightingOnControllers) {
  68452. if (!_this._lightOnControllers) {
  68453. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  68454. }
  68455. var activateLightOnSubMeshes_1 = function (mesh, light) {
  68456. var children = mesh.getChildren();
  68457. if (children.length !== 0) {
  68458. children.forEach(function (mesh) {
  68459. light.includedOnlyMeshes.push(mesh);
  68460. activateLightOnSubMeshes_1(mesh, light);
  68461. });
  68462. }
  68463. };
  68464. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  68465. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  68466. }
  68467. });
  68468. }
  68469. }
  68470. webVrController_1.attachToPoseControlledCamera(_this);
  68471. // since this is async - sanity check. Is the controller already stored?
  68472. if (_this.controllers.indexOf(webVrController_1) === -1) {
  68473. //add to the controllers array
  68474. _this.controllers.push(webVrController_1);
  68475. //did we find enough controllers? Great! let the developer know.
  68476. if (_this.controllers.length >= 2) {
  68477. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  68478. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  68479. // So we're overriding setting left & right manually to be sure
  68480. var firstViveWandDetected = false;
  68481. for (var i = 0; i < _this.controllers.length; i++) {
  68482. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  68483. if (!firstViveWandDetected) {
  68484. firstViveWandDetected = true;
  68485. _this.controllers[i].hand = "left";
  68486. }
  68487. else {
  68488. _this.controllers[i].hand = "right";
  68489. }
  68490. }
  68491. }
  68492. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  68493. }
  68494. }
  68495. }
  68496. });
  68497. };
  68498. return WebVRFreeCamera;
  68499. }(BABYLON.FreeCamera));
  68500. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  68501. })(BABYLON || (BABYLON = {}));
  68502. //# sourceMappingURL=babylon.webVRCamera.js.map
  68503. /// <reference path="babylon.freeCamera.ts" />
  68504. var BABYLON;
  68505. (function (BABYLON) {
  68506. // We're mainly based on the logic defined into the FreeCamera code
  68507. var DeviceOrientationCamera = /** @class */ (function (_super) {
  68508. __extends(DeviceOrientationCamera, _super);
  68509. function DeviceOrientationCamera(name, position, scene) {
  68510. var _this = _super.call(this, name, position, scene) || this;
  68511. _this._quaternionCache = new BABYLON.Quaternion();
  68512. _this.inputs.addDeviceOrientation();
  68513. return _this;
  68514. }
  68515. DeviceOrientationCamera.prototype.getClassName = function () {
  68516. return "DeviceOrientationCamera";
  68517. };
  68518. DeviceOrientationCamera.prototype._checkInputs = function () {
  68519. _super.prototype._checkInputs.call(this);
  68520. this._quaternionCache.copyFrom(this.rotationQuaternion);
  68521. if (this._initialQuaternion) {
  68522. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  68523. }
  68524. };
  68525. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  68526. var _this = this;
  68527. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  68528. //can only work if this camera has a rotation quaternion already.
  68529. if (!this.rotationQuaternion)
  68530. return;
  68531. if (!this._initialQuaternion) {
  68532. this._initialQuaternion = new BABYLON.Quaternion();
  68533. }
  68534. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  68535. ['x', 'y', 'z'].forEach(function (axisName) {
  68536. if (!axis[axisName]) {
  68537. _this._initialQuaternion[axisName] = 0;
  68538. }
  68539. else {
  68540. _this._initialQuaternion[axisName] *= -1;
  68541. }
  68542. });
  68543. this._initialQuaternion.normalize();
  68544. //force rotation update
  68545. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  68546. };
  68547. return DeviceOrientationCamera;
  68548. }(BABYLON.FreeCamera));
  68549. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  68550. })(BABYLON || (BABYLON = {}));
  68551. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  68552. var BABYLON;
  68553. (function (BABYLON) {
  68554. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  68555. __extends(VRDeviceOrientationFreeCamera, _super);
  68556. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  68557. if (compensateDistortion === void 0) { compensateDistortion = true; }
  68558. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  68559. var _this = _super.call(this, name, position, scene) || this;
  68560. vrCameraMetrics.compensateDistortion = compensateDistortion;
  68561. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  68562. return _this;
  68563. }
  68564. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  68565. return "VRDeviceOrientationFreeCamera";
  68566. };
  68567. return VRDeviceOrientationFreeCamera;
  68568. }(BABYLON.DeviceOrientationCamera));
  68569. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  68570. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  68571. __extends(VRDeviceOrientationGamepadCamera, _super);
  68572. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  68573. if (compensateDistortion === void 0) { compensateDistortion = true; }
  68574. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  68575. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  68576. _this.inputs.addGamepad();
  68577. return _this;
  68578. }
  68579. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  68580. return "VRDeviceOrientationGamepadCamera";
  68581. };
  68582. return VRDeviceOrientationGamepadCamera;
  68583. }(VRDeviceOrientationFreeCamera));
  68584. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  68585. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  68586. __extends(VRDeviceOrientationArcRotateCamera, _super);
  68587. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  68588. if (compensateDistortion === void 0) { compensateDistortion = true; }
  68589. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  68590. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  68591. vrCameraMetrics.compensateDistortion = compensateDistortion;
  68592. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  68593. _this.inputs.addVRDeviceOrientation();
  68594. return _this;
  68595. }
  68596. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  68597. return "VRDeviceOrientationArcRotateCamera";
  68598. };
  68599. return VRDeviceOrientationArcRotateCamera;
  68600. }(BABYLON.ArcRotateCamera));
  68601. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  68602. })(BABYLON || (BABYLON = {}));
  68603. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  68604. /// <reference path="babylon.freeCamera.ts" />
  68605. /// <reference path="babylon.arcRotateCamera.ts" />
  68606. /// <reference path="babylon.gamepadCamera.ts" />
  68607. /// <reference path="babylon.universalCamera.ts" />
  68608. var BABYLON;
  68609. (function (BABYLON) {
  68610. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  68611. __extends(AnaglyphFreeCamera, _super);
  68612. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  68613. var _this = _super.call(this, name, position, scene) || this;
  68614. _this.interaxialDistance = interaxialDistance;
  68615. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  68616. return _this;
  68617. }
  68618. AnaglyphFreeCamera.prototype.getClassName = function () {
  68619. return "AnaglyphFreeCamera";
  68620. };
  68621. return AnaglyphFreeCamera;
  68622. }(BABYLON.FreeCamera));
  68623. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  68624. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  68625. __extends(AnaglyphArcRotateCamera, _super);
  68626. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  68627. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  68628. _this.interaxialDistance = interaxialDistance;
  68629. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  68630. return _this;
  68631. }
  68632. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  68633. return "AnaglyphArcRotateCamera";
  68634. };
  68635. return AnaglyphArcRotateCamera;
  68636. }(BABYLON.ArcRotateCamera));
  68637. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  68638. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  68639. __extends(AnaglyphGamepadCamera, _super);
  68640. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  68641. var _this = _super.call(this, name, position, scene) || this;
  68642. _this.interaxialDistance = interaxialDistance;
  68643. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  68644. return _this;
  68645. }
  68646. AnaglyphGamepadCamera.prototype.getClassName = function () {
  68647. return "AnaglyphGamepadCamera";
  68648. };
  68649. return AnaglyphGamepadCamera;
  68650. }(BABYLON.GamepadCamera));
  68651. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  68652. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  68653. __extends(AnaglyphUniversalCamera, _super);
  68654. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  68655. var _this = _super.call(this, name, position, scene) || this;
  68656. _this.interaxialDistance = interaxialDistance;
  68657. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  68658. return _this;
  68659. }
  68660. AnaglyphUniversalCamera.prototype.getClassName = function () {
  68661. return "AnaglyphUniversalCamera";
  68662. };
  68663. return AnaglyphUniversalCamera;
  68664. }(BABYLON.UniversalCamera));
  68665. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  68666. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  68667. __extends(StereoscopicFreeCamera, _super);
  68668. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  68669. var _this = _super.call(this, name, position, scene) || this;
  68670. _this.interaxialDistance = interaxialDistance;
  68671. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  68672. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  68673. return _this;
  68674. }
  68675. StereoscopicFreeCamera.prototype.getClassName = function () {
  68676. return "StereoscopicFreeCamera";
  68677. };
  68678. return StereoscopicFreeCamera;
  68679. }(BABYLON.FreeCamera));
  68680. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  68681. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  68682. __extends(StereoscopicArcRotateCamera, _super);
  68683. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  68684. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  68685. _this.interaxialDistance = interaxialDistance;
  68686. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  68687. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  68688. return _this;
  68689. }
  68690. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  68691. return "StereoscopicArcRotateCamera";
  68692. };
  68693. return StereoscopicArcRotateCamera;
  68694. }(BABYLON.ArcRotateCamera));
  68695. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  68696. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  68697. __extends(StereoscopicGamepadCamera, _super);
  68698. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  68699. var _this = _super.call(this, name, position, scene) || this;
  68700. _this.interaxialDistance = interaxialDistance;
  68701. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  68702. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  68703. return _this;
  68704. }
  68705. StereoscopicGamepadCamera.prototype.getClassName = function () {
  68706. return "StereoscopicGamepadCamera";
  68707. };
  68708. return StereoscopicGamepadCamera;
  68709. }(BABYLON.GamepadCamera));
  68710. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  68711. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  68712. __extends(StereoscopicUniversalCamera, _super);
  68713. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  68714. var _this = _super.call(this, name, position, scene) || this;
  68715. _this.interaxialDistance = interaxialDistance;
  68716. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  68717. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  68718. return _this;
  68719. }
  68720. StereoscopicUniversalCamera.prototype.getClassName = function () {
  68721. return "StereoscopicUniversalCamera";
  68722. };
  68723. return StereoscopicUniversalCamera;
  68724. }(BABYLON.UniversalCamera));
  68725. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  68726. })(BABYLON || (BABYLON = {}));
  68727. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  68728. var BABYLON;
  68729. (function (BABYLON) {
  68730. var VRExperienceHelper = /** @class */ (function () {
  68731. function VRExperienceHelper(scene, webVROptions) {
  68732. if (webVROptions === void 0) { webVROptions = {}; }
  68733. var _this = this;
  68734. this.webVROptions = webVROptions;
  68735. // Can the system support WebVR, even if a headset isn't plugged in?
  68736. this._webVRsupported = false;
  68737. // If WebVR is supported, is a headset plugged in and are we ready to present?
  68738. this._webVRready = false;
  68739. // Are we waiting for the requestPresent callback to complete?
  68740. this._webVRrequesting = false;
  68741. // Are we presenting to the headset right now?
  68742. this._webVRpresenting = false;
  68743. // Are we presenting in the fullscreen fallback?
  68744. this._fullscreenVRpresenting = false;
  68745. this._scene = scene;
  68746. if (!this._scene.activeCamera || isNaN(this._scene.activeCamera.position.x)) {
  68747. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", new BABYLON.Vector3(0, 2, 0), scene);
  68748. }
  68749. else {
  68750. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._scene.activeCamera.position, scene);
  68751. if (scene.activeCamera.rotation) {
  68752. this._deviceOrientationCamera.rotation = scene.activeCamera.rotation.clone();
  68753. }
  68754. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  68755. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  68756. }
  68757. this._scene.activeCamera = this._deviceOrientationCamera;
  68758. this._position = this._scene.activeCamera.position;
  68759. this._canvas = scene.getEngine().getRenderingCanvas();
  68760. if (this._canvas) {
  68761. this._scene.activeCamera.attachControl(this._canvas);
  68762. }
  68763. this._btnVR = document.createElement("BUTTON");
  68764. this._btnVR.className = "babylonVRicon";
  68765. this._btnVR.id = "babylonVRiconbtn";
  68766. this._btnVR.title = "Click to switch to VR";
  68767. 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) }";
  68768. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  68769. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  68770. // css += ".babylonVRicon.vrdisplaysupported { }";
  68771. // css += ".babylonVRicon.vrdisplayready { }";
  68772. // css += ".babylonVRicon.vrdisplayrequesting { }";
  68773. var style = document.createElement('style');
  68774. style.appendChild(document.createTextNode(css));
  68775. document.getElementsByTagName('head')[0].appendChild(style);
  68776. if (this._canvas) {
  68777. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  68778. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  68779. this._btnVR.addEventListener("click", function () {
  68780. _this.enterVR();
  68781. });
  68782. window.addEventListener("resize", function () {
  68783. if (_this._canvas) {
  68784. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  68785. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  68786. }
  68787. if (_this._fullscreenVRpresenting && _this._webVRready) {
  68788. _this.exitVR();
  68789. }
  68790. });
  68791. }
  68792. document.addEventListener("fullscreenchange", function () { _this._onFullscreenChange(); }, false);
  68793. document.addEventListener("mozfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  68794. document.addEventListener("webkitfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  68795. document.addEventListener("msfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  68796. document.body.appendChild(this._btnVR);
  68797. // Exiting VR mode using 'ESC' key on desktop
  68798. this._onKeyDown = function (event) {
  68799. if (event.keyCode === 27 && _this.isInVRMode()) {
  68800. _this.exitVR();
  68801. }
  68802. };
  68803. document.addEventListener("keydown", this._onKeyDown);
  68804. // Exiting VR mode double tapping the touch screen
  68805. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  68806. if (_this.isInVRMode()) {
  68807. _this.exitVR();
  68808. if (_this._fullscreenVRpresenting) {
  68809. _this._scene.getEngine().switchFullscreen(true);
  68810. }
  68811. }
  68812. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  68813. // Listen for WebVR display changes
  68814. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  68815. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  68816. this._onVRRequestPresentStart = function () {
  68817. _this._webVRrequesting = true;
  68818. _this.updateButtonVisibility();
  68819. };
  68820. this._onVRRequestPresentComplete = function (success) {
  68821. _this._webVRrequesting = false;
  68822. _this.updateButtonVisibility();
  68823. };
  68824. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  68825. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  68826. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  68827. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  68828. // Create the cameras
  68829. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  68830. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  68831. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  68832. this.updateButtonVisibility();
  68833. }
  68834. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  68835. if (this.onControllerMeshLoaded) {
  68836. this.onControllerMeshLoaded(webVRController);
  68837. }
  68838. };
  68839. VRExperienceHelper.prototype._onFullscreenChange = function () {
  68840. if (document.fullscreen !== undefined) {
  68841. this._fullscreenVRpresenting = document.fullscreen;
  68842. }
  68843. else if (document.mozFullScreen !== undefined) {
  68844. this._fullscreenVRpresenting = document.mozFullScreen;
  68845. }
  68846. else if (document.webkitIsFullScreen !== undefined) {
  68847. this._fullscreenVRpresenting = document.webkitIsFullScreen;
  68848. }
  68849. else if (document.msIsFullScreen !== undefined) {
  68850. this._fullscreenVRpresenting = document.msIsFullScreen;
  68851. }
  68852. if (!this._fullscreenVRpresenting && this._canvas) {
  68853. this.exitVR();
  68854. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  68855. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  68856. }
  68857. };
  68858. VRExperienceHelper.prototype.isInVRMode = function () {
  68859. return this._webVRpresenting || this._fullscreenVRpresenting;
  68860. };
  68861. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  68862. var vrDisplay = this._scene.getEngine().getVRDevice();
  68863. if (vrDisplay) {
  68864. var wasPresenting = this._webVRpresenting;
  68865. // A VR display is connected
  68866. this._webVRpresenting = vrDisplay.isPresenting;
  68867. if (wasPresenting && !this._webVRpresenting)
  68868. this.exitVR();
  68869. }
  68870. else {
  68871. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  68872. }
  68873. this.updateButtonVisibility();
  68874. };
  68875. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  68876. this._webVRsupported = eventArgs.vrSupported;
  68877. this._webVRready = !!eventArgs.vrDisplay;
  68878. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  68879. this.updateButtonVisibility();
  68880. };
  68881. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  68882. if (!this._btnVR) {
  68883. return;
  68884. }
  68885. this._btnVR.className = "babylonVRicon";
  68886. if (this.isInVRMode()) {
  68887. this._btnVR.className += " vrdisplaypresenting";
  68888. }
  68889. else {
  68890. if (this._webVRready)
  68891. this._btnVR.className += " vrdisplayready";
  68892. if (this._webVRsupported)
  68893. this._btnVR.className += " vrdisplaysupported";
  68894. if (this._webVRrequesting)
  68895. this._btnVR.className += " vrdisplayrequesting";
  68896. }
  68897. };
  68898. /**
  68899. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  68900. * Otherwise, will use the fullscreen API.
  68901. */
  68902. VRExperienceHelper.prototype.enterVR = function () {
  68903. if (this.onEnteringVR) {
  68904. this.onEnteringVR();
  68905. }
  68906. if (this._webVRrequesting)
  68907. return;
  68908. // If WebVR is supported and a headset is connected
  68909. if (this._webVRready) {
  68910. if (!this._webVRpresenting) {
  68911. this._webVRCamera.position = this._position;
  68912. this._scene.activeCamera = this._webVRCamera;
  68913. }
  68914. }
  68915. else {
  68916. this._vrDeviceOrientationCamera.position = this._position;
  68917. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  68918. this._scene.getEngine().switchFullscreen(true);
  68919. this.updateButtonVisibility();
  68920. }
  68921. if (this._scene.activeCamera && this._canvas) {
  68922. this._scene.activeCamera.attachControl(this._canvas);
  68923. }
  68924. };
  68925. /**
  68926. * Attempt to exit VR, or fullscreen.
  68927. */
  68928. VRExperienceHelper.prototype.exitVR = function () {
  68929. if (this.onExitingVR) {
  68930. this.onExitingVR();
  68931. }
  68932. if (this._webVRpresenting) {
  68933. this._scene.getEngine().disableVR();
  68934. }
  68935. if (this._scene.activeCamera) {
  68936. this._position = this._scene.activeCamera.position;
  68937. }
  68938. this._deviceOrientationCamera.position = this._position;
  68939. this._scene.activeCamera = this._deviceOrientationCamera;
  68940. if (this._canvas) {
  68941. this._scene.activeCamera.attachControl(this._canvas);
  68942. }
  68943. this.updateButtonVisibility();
  68944. };
  68945. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  68946. get: function () {
  68947. return this._position;
  68948. },
  68949. set: function (value) {
  68950. this._position = value;
  68951. if (this._scene.activeCamera) {
  68952. this._scene.activeCamera.position = value;
  68953. }
  68954. },
  68955. enumerable: true,
  68956. configurable: true
  68957. });
  68958. VRExperienceHelper.prototype.dispose = function () {
  68959. if (this.isInVRMode()) {
  68960. this.exitVR();
  68961. }
  68962. this._deviceOrientationCamera.dispose();
  68963. if (this._webVRCamera) {
  68964. this._webVRCamera.dispose();
  68965. }
  68966. if (this._vrDeviceOrientationCamera) {
  68967. this._vrDeviceOrientationCamera.dispose();
  68968. }
  68969. document.body.removeChild(this._btnVR);
  68970. document.removeEventListener("keydown", this._onKeyDown);
  68971. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  68972. };
  68973. VRExperienceHelper.prototype.getClassName = function () {
  68974. return "VRExperienceHelper";
  68975. };
  68976. return VRExperienceHelper;
  68977. }());
  68978. BABYLON.VRExperienceHelper = VRExperienceHelper;
  68979. })(BABYLON || (BABYLON = {}));
  68980. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  68981. // Mainly based on these 2 articles :
  68982. // 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
  68983. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  68984. var BABYLON;
  68985. (function (BABYLON) {
  68986. var JoystickAxis;
  68987. (function (JoystickAxis) {
  68988. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  68989. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  68990. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  68991. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  68992. var VirtualJoystick = /** @class */ (function () {
  68993. function VirtualJoystick(leftJoystick) {
  68994. var _this = this;
  68995. if (leftJoystick) {
  68996. this._leftJoystick = true;
  68997. }
  68998. else {
  68999. this._leftJoystick = false;
  69000. }
  69001. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  69002. VirtualJoystick._globalJoystickIndex++;
  69003. // By default left & right arrow keys are moving the X
  69004. // and up & down keys are moving the Y
  69005. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  69006. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  69007. this.reverseLeftRight = false;
  69008. this.reverseUpDown = false;
  69009. // collections of pointers
  69010. this._touches = new BABYLON.StringDictionary();
  69011. this.deltaPosition = BABYLON.Vector3.Zero();
  69012. this._joystickSensibility = 25;
  69013. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  69014. this._rotationSpeed = 25;
  69015. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  69016. this._rotateOnAxisRelativeToMesh = false;
  69017. this._onResize = function (evt) {
  69018. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  69019. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  69020. if (VirtualJoystick.vjCanvas) {
  69021. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  69022. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  69023. }
  69024. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  69025. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  69026. };
  69027. // injecting a canvas element on top of the canvas 3D game
  69028. if (!VirtualJoystick.vjCanvas) {
  69029. window.addEventListener("resize", this._onResize, false);
  69030. VirtualJoystick.vjCanvas = document.createElement("canvas");
  69031. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  69032. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  69033. VirtualJoystick.vjCanvas.width = window.innerWidth;
  69034. VirtualJoystick.vjCanvas.height = window.innerHeight;
  69035. VirtualJoystick.vjCanvas.style.width = "100%";
  69036. VirtualJoystick.vjCanvas.style.height = "100%";
  69037. VirtualJoystick.vjCanvas.style.position = "absolute";
  69038. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  69039. VirtualJoystick.vjCanvas.style.top = "0px";
  69040. VirtualJoystick.vjCanvas.style.left = "0px";
  69041. VirtualJoystick.vjCanvas.style.zIndex = "5";
  69042. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  69043. // Support for jQuery PEP polyfill
  69044. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  69045. var context = VirtualJoystick.vjCanvas.getContext('2d');
  69046. if (!context) {
  69047. throw new Error("Unable to create canvas for virtual joystick");
  69048. }
  69049. VirtualJoystick.vjCanvasContext = context;
  69050. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  69051. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  69052. document.body.appendChild(VirtualJoystick.vjCanvas);
  69053. }
  69054. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  69055. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  69056. this.pressed = false;
  69057. // default joystick color
  69058. this._joystickColor = "cyan";
  69059. this._joystickPointerID = -1;
  69060. // current joystick position
  69061. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  69062. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  69063. // origin joystick position
  69064. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  69065. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  69066. this._onPointerDownHandlerRef = function (evt) {
  69067. _this._onPointerDown(evt);
  69068. };
  69069. this._onPointerMoveHandlerRef = function (evt) {
  69070. _this._onPointerMove(evt);
  69071. };
  69072. this._onPointerOutHandlerRef = function (evt) {
  69073. _this._onPointerUp(evt);
  69074. };
  69075. this._onPointerUpHandlerRef = function (evt) {
  69076. _this._onPointerUp(evt);
  69077. };
  69078. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  69079. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  69080. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  69081. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  69082. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  69083. evt.preventDefault(); // Disables system menu
  69084. }, false);
  69085. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  69086. }
  69087. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  69088. this._joystickSensibility = newJoystickSensibility;
  69089. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  69090. };
  69091. VirtualJoystick.prototype._onPointerDown = function (e) {
  69092. var positionOnScreenCondition;
  69093. e.preventDefault();
  69094. if (this._leftJoystick === true) {
  69095. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  69096. }
  69097. else {
  69098. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  69099. }
  69100. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  69101. // First contact will be dedicated to the virtual joystick
  69102. this._joystickPointerID = e.pointerId;
  69103. this._joystickPointerStartPos.x = e.clientX;
  69104. this._joystickPointerStartPos.y = e.clientY;
  69105. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  69106. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  69107. this._deltaJoystickVector.x = 0;
  69108. this._deltaJoystickVector.y = 0;
  69109. this.pressed = true;
  69110. this._touches.add(e.pointerId.toString(), e);
  69111. }
  69112. else {
  69113. // You can only trigger the action buttons with a joystick declared
  69114. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  69115. this._action();
  69116. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  69117. }
  69118. }
  69119. };
  69120. VirtualJoystick.prototype._onPointerMove = function (e) {
  69121. // If the current pointer is the one associated to the joystick (first touch contact)
  69122. if (this._joystickPointerID == e.pointerId) {
  69123. this._joystickPointerPos.x = e.clientX;
  69124. this._joystickPointerPos.y = e.clientY;
  69125. this._deltaJoystickVector = this._joystickPointerPos.clone();
  69126. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  69127. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  69128. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  69129. switch (this._axisTargetedByLeftAndRight) {
  69130. case JoystickAxis.X:
  69131. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  69132. break;
  69133. case JoystickAxis.Y:
  69134. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  69135. break;
  69136. case JoystickAxis.Z:
  69137. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  69138. break;
  69139. }
  69140. var directionUpDown = this.reverseUpDown ? 1 : -1;
  69141. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  69142. switch (this._axisTargetedByUpAndDown) {
  69143. case JoystickAxis.X:
  69144. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  69145. break;
  69146. case JoystickAxis.Y:
  69147. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  69148. break;
  69149. case JoystickAxis.Z:
  69150. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  69151. break;
  69152. }
  69153. }
  69154. else {
  69155. var data = this._touches.get(e.pointerId.toString());
  69156. if (data) {
  69157. data.x = e.clientX;
  69158. data.y = e.clientY;
  69159. }
  69160. }
  69161. };
  69162. VirtualJoystick.prototype._onPointerUp = function (e) {
  69163. if (this._joystickPointerID == e.pointerId) {
  69164. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  69165. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  69166. this._joystickPointerID = -1;
  69167. this.pressed = false;
  69168. }
  69169. else {
  69170. var touch = this._touches.get(e.pointerId.toString());
  69171. if (touch) {
  69172. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  69173. }
  69174. }
  69175. this._deltaJoystickVector.x = 0;
  69176. this._deltaJoystickVector.y = 0;
  69177. this._touches.remove(e.pointerId.toString());
  69178. };
  69179. /**
  69180. * Change the color of the virtual joystick
  69181. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  69182. */
  69183. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  69184. this._joystickColor = newColor;
  69185. };
  69186. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  69187. this._action = action;
  69188. };
  69189. // Define which axis you'd like to control for left & right
  69190. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  69191. switch (axis) {
  69192. case JoystickAxis.X:
  69193. case JoystickAxis.Y:
  69194. case JoystickAxis.Z:
  69195. this._axisTargetedByLeftAndRight = axis;
  69196. break;
  69197. default:
  69198. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  69199. break;
  69200. }
  69201. };
  69202. // Define which axis you'd like to control for up & down
  69203. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  69204. switch (axis) {
  69205. case JoystickAxis.X:
  69206. case JoystickAxis.Y:
  69207. case JoystickAxis.Z:
  69208. this._axisTargetedByUpAndDown = axis;
  69209. break;
  69210. default:
  69211. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  69212. break;
  69213. }
  69214. };
  69215. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  69216. var _this = this;
  69217. if (this.pressed) {
  69218. this._touches.forEach(function (key, touch) {
  69219. if (touch.pointerId === _this._joystickPointerID) {
  69220. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  69221. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  69222. VirtualJoystick.vjCanvasContext.beginPath();
  69223. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  69224. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  69225. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  69226. VirtualJoystick.vjCanvasContext.stroke();
  69227. VirtualJoystick.vjCanvasContext.closePath();
  69228. VirtualJoystick.vjCanvasContext.beginPath();
  69229. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  69230. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  69231. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  69232. VirtualJoystick.vjCanvasContext.stroke();
  69233. VirtualJoystick.vjCanvasContext.closePath();
  69234. VirtualJoystick.vjCanvasContext.beginPath();
  69235. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  69236. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  69237. VirtualJoystick.vjCanvasContext.stroke();
  69238. VirtualJoystick.vjCanvasContext.closePath();
  69239. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  69240. }
  69241. else {
  69242. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  69243. VirtualJoystick.vjCanvasContext.beginPath();
  69244. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  69245. VirtualJoystick.vjCanvasContext.beginPath();
  69246. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  69247. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  69248. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  69249. VirtualJoystick.vjCanvasContext.stroke();
  69250. VirtualJoystick.vjCanvasContext.closePath();
  69251. touch.prevX = touch.x;
  69252. touch.prevY = touch.y;
  69253. }
  69254. ;
  69255. });
  69256. }
  69257. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  69258. };
  69259. VirtualJoystick.prototype.releaseCanvas = function () {
  69260. if (VirtualJoystick.vjCanvas) {
  69261. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  69262. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  69263. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  69264. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  69265. window.removeEventListener("resize", this._onResize);
  69266. document.body.removeChild(VirtualJoystick.vjCanvas);
  69267. VirtualJoystick.vjCanvas = null;
  69268. }
  69269. };
  69270. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  69271. VirtualJoystick._globalJoystickIndex = 0;
  69272. return VirtualJoystick;
  69273. }());
  69274. BABYLON.VirtualJoystick = VirtualJoystick;
  69275. })(BABYLON || (BABYLON = {}));
  69276. //# sourceMappingURL=babylon.virtualJoystick.js.map
  69277. var BABYLON;
  69278. (function (BABYLON) {
  69279. // We're mainly based on the logic defined into the FreeCamera code
  69280. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  69281. __extends(VirtualJoysticksCamera, _super);
  69282. function VirtualJoysticksCamera(name, position, scene) {
  69283. var _this = _super.call(this, name, position, scene) || this;
  69284. _this.inputs.addVirtualJoystick();
  69285. return _this;
  69286. }
  69287. VirtualJoysticksCamera.prototype.getClassName = function () {
  69288. return "VirtualJoysticksCamera";
  69289. };
  69290. return VirtualJoysticksCamera;
  69291. }(BABYLON.FreeCamera));
  69292. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  69293. })(BABYLON || (BABYLON = {}));
  69294. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  69295. var BABYLON;
  69296. (function (BABYLON) {
  69297. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  69298. function FreeCameraVirtualJoystickInput() {
  69299. }
  69300. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  69301. return this._leftjoystick;
  69302. };
  69303. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  69304. return this._rightjoystick;
  69305. };
  69306. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  69307. if (this._leftjoystick) {
  69308. var camera = this.camera;
  69309. var speed = camera._computeLocalCameraSpeed() * 50;
  69310. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  69311. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  69312. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  69313. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  69314. if (!this._leftjoystick.pressed) {
  69315. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  69316. }
  69317. if (!this._rightjoystick.pressed) {
  69318. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  69319. }
  69320. }
  69321. };
  69322. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  69323. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  69324. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  69325. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  69326. this._leftjoystick.setJoystickSensibility(0.15);
  69327. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  69328. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  69329. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  69330. this._rightjoystick.reverseUpDown = true;
  69331. this._rightjoystick.setJoystickSensibility(0.05);
  69332. this._rightjoystick.setJoystickColor("yellow");
  69333. };
  69334. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  69335. this._leftjoystick.releaseCanvas();
  69336. this._rightjoystick.releaseCanvas();
  69337. };
  69338. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  69339. return "FreeCameraVirtualJoystickInput";
  69340. };
  69341. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  69342. return "virtualJoystick";
  69343. };
  69344. return FreeCameraVirtualJoystickInput;
  69345. }());
  69346. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  69347. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  69348. })(BABYLON || (BABYLON = {}));
  69349. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  69350. var BABYLON;
  69351. (function (BABYLON) {
  69352. var SimplificationSettings = /** @class */ (function () {
  69353. function SimplificationSettings(quality, distance, optimizeMesh) {
  69354. this.quality = quality;
  69355. this.distance = distance;
  69356. this.optimizeMesh = optimizeMesh;
  69357. }
  69358. return SimplificationSettings;
  69359. }());
  69360. BABYLON.SimplificationSettings = SimplificationSettings;
  69361. var SimplificationQueue = /** @class */ (function () {
  69362. function SimplificationQueue() {
  69363. this.running = false;
  69364. this._simplificationArray = [];
  69365. }
  69366. SimplificationQueue.prototype.addTask = function (task) {
  69367. this._simplificationArray.push(task);
  69368. };
  69369. SimplificationQueue.prototype.executeNext = function () {
  69370. var task = this._simplificationArray.pop();
  69371. if (task) {
  69372. this.running = true;
  69373. this.runSimplification(task);
  69374. }
  69375. else {
  69376. this.running = false;
  69377. }
  69378. };
  69379. SimplificationQueue.prototype.runSimplification = function (task) {
  69380. var _this = this;
  69381. if (task.parallelProcessing) {
  69382. //parallel simplifier
  69383. task.settings.forEach(function (setting) {
  69384. var simplifier = _this.getSimplifier(task);
  69385. simplifier.simplify(setting, function (newMesh) {
  69386. task.mesh.addLODLevel(setting.distance, newMesh);
  69387. newMesh.isVisible = true;
  69388. //check if it is the last
  69389. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  69390. //all done, run the success callback.
  69391. task.successCallback();
  69392. }
  69393. _this.executeNext();
  69394. });
  69395. });
  69396. }
  69397. else {
  69398. //single simplifier.
  69399. var simplifier = this.getSimplifier(task);
  69400. var runDecimation = function (setting, callback) {
  69401. simplifier.simplify(setting, function (newMesh) {
  69402. task.mesh.addLODLevel(setting.distance, newMesh);
  69403. newMesh.isVisible = true;
  69404. //run the next quality level
  69405. callback();
  69406. });
  69407. };
  69408. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  69409. runDecimation(task.settings[loop.index], function () {
  69410. loop.executeNext();
  69411. });
  69412. }, function () {
  69413. //execution ended, run the success callback.
  69414. if (task.successCallback) {
  69415. task.successCallback();
  69416. }
  69417. _this.executeNext();
  69418. });
  69419. }
  69420. };
  69421. SimplificationQueue.prototype.getSimplifier = function (task) {
  69422. switch (task.simplificationType) {
  69423. case SimplificationType.QUADRATIC:
  69424. default:
  69425. return new QuadraticErrorSimplification(task.mesh);
  69426. }
  69427. };
  69428. return SimplificationQueue;
  69429. }());
  69430. BABYLON.SimplificationQueue = SimplificationQueue;
  69431. /**
  69432. * The implemented types of simplification.
  69433. * At the moment only Quadratic Error Decimation is implemented.
  69434. */
  69435. var SimplificationType;
  69436. (function (SimplificationType) {
  69437. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  69438. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  69439. var DecimationTriangle = /** @class */ (function () {
  69440. function DecimationTriangle(vertices) {
  69441. this.vertices = vertices;
  69442. this.error = new Array(4);
  69443. this.deleted = false;
  69444. this.isDirty = false;
  69445. this.deletePending = false;
  69446. this.borderFactor = 0;
  69447. }
  69448. return DecimationTriangle;
  69449. }());
  69450. BABYLON.DecimationTriangle = DecimationTriangle;
  69451. var DecimationVertex = /** @class */ (function () {
  69452. function DecimationVertex(position, id) {
  69453. this.position = position;
  69454. this.id = id;
  69455. this.isBorder = true;
  69456. this.q = new QuadraticMatrix();
  69457. this.triangleCount = 0;
  69458. this.triangleStart = 0;
  69459. this.originalOffsets = [];
  69460. }
  69461. DecimationVertex.prototype.updatePosition = function (newPosition) {
  69462. this.position.copyFrom(newPosition);
  69463. };
  69464. return DecimationVertex;
  69465. }());
  69466. BABYLON.DecimationVertex = DecimationVertex;
  69467. var QuadraticMatrix = /** @class */ (function () {
  69468. function QuadraticMatrix(data) {
  69469. this.data = new Array(10);
  69470. for (var i = 0; i < 10; ++i) {
  69471. if (data && data[i]) {
  69472. this.data[i] = data[i];
  69473. }
  69474. else {
  69475. this.data[i] = 0;
  69476. }
  69477. }
  69478. }
  69479. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  69480. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  69481. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  69482. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  69483. return det;
  69484. };
  69485. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  69486. for (var i = 0; i < 10; ++i) {
  69487. this.data[i] += matrix.data[i];
  69488. }
  69489. };
  69490. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  69491. for (var i = 0; i < 10; ++i) {
  69492. this.data[i] += data[i];
  69493. }
  69494. };
  69495. QuadraticMatrix.prototype.add = function (matrix) {
  69496. var m = new QuadraticMatrix();
  69497. for (var i = 0; i < 10; ++i) {
  69498. m.data[i] = this.data[i] + matrix.data[i];
  69499. }
  69500. return m;
  69501. };
  69502. QuadraticMatrix.FromData = function (a, b, c, d) {
  69503. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  69504. };
  69505. //returning an array to avoid garbage collection
  69506. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  69507. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  69508. };
  69509. return QuadraticMatrix;
  69510. }());
  69511. BABYLON.QuadraticMatrix = QuadraticMatrix;
  69512. var Reference = /** @class */ (function () {
  69513. function Reference(vertexId, triangleId) {
  69514. this.vertexId = vertexId;
  69515. this.triangleId = triangleId;
  69516. }
  69517. return Reference;
  69518. }());
  69519. BABYLON.Reference = Reference;
  69520. /**
  69521. * An implementation of the Quadratic Error simplification algorithm.
  69522. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  69523. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  69524. * @author RaananW
  69525. */
  69526. var QuadraticErrorSimplification = /** @class */ (function () {
  69527. function QuadraticErrorSimplification(_mesh) {
  69528. this._mesh = _mesh;
  69529. this.initialized = false;
  69530. this.syncIterations = 5000;
  69531. this.aggressiveness = 7;
  69532. this.decimationIterations = 100;
  69533. this.boundingBoxEpsilon = BABYLON.Epsilon;
  69534. }
  69535. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  69536. var _this = this;
  69537. this.initDecimatedMesh();
  69538. //iterating through the submeshes array, one after the other.
  69539. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  69540. _this.initWithMesh(loop.index, function () {
  69541. _this.runDecimation(settings, loop.index, function () {
  69542. loop.executeNext();
  69543. });
  69544. }, settings.optimizeMesh);
  69545. }, function () {
  69546. setTimeout(function () {
  69547. successCallback(_this._reconstructedMesh);
  69548. }, 0);
  69549. });
  69550. };
  69551. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  69552. var _this = this;
  69553. var targetCount = ~~(this.triangles.length * settings.quality);
  69554. var deletedTriangles = 0;
  69555. var triangleCount = this.triangles.length;
  69556. var iterationFunction = function (iteration, callback) {
  69557. setTimeout(function () {
  69558. if (iteration % 5 === 0) {
  69559. _this.updateMesh(iteration === 0);
  69560. }
  69561. for (var i = 0; i < _this.triangles.length; ++i) {
  69562. _this.triangles[i].isDirty = false;
  69563. }
  69564. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  69565. var trianglesIterator = function (i) {
  69566. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  69567. var t = _this.triangles[tIdx];
  69568. if (!t)
  69569. return;
  69570. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  69571. return;
  69572. }
  69573. for (var j = 0; j < 3; ++j) {
  69574. if (t.error[j] < threshold) {
  69575. var deleted0 = [];
  69576. var deleted1 = [];
  69577. var v0 = t.vertices[j];
  69578. var v1 = t.vertices[(j + 1) % 3];
  69579. if (v0.isBorder || v1.isBorder)
  69580. continue;
  69581. var p = BABYLON.Vector3.Zero();
  69582. var n = BABYLON.Vector3.Zero();
  69583. var uv = BABYLON.Vector2.Zero();
  69584. var color = new BABYLON.Color4(0, 0, 0, 1);
  69585. _this.calculateError(v0, v1, p, n, uv, color);
  69586. var delTr = new Array();
  69587. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  69588. continue;
  69589. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  69590. continue;
  69591. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  69592. continue;
  69593. var uniqueArray = new Array();
  69594. delTr.forEach(function (deletedT) {
  69595. if (uniqueArray.indexOf(deletedT) === -1) {
  69596. deletedT.deletePending = true;
  69597. uniqueArray.push(deletedT);
  69598. }
  69599. });
  69600. if (uniqueArray.length % 2 !== 0) {
  69601. continue;
  69602. }
  69603. v0.q = v1.q.add(v0.q);
  69604. v0.updatePosition(p);
  69605. var tStart = _this.references.length;
  69606. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  69607. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  69608. var tCount = _this.references.length - tStart;
  69609. if (tCount <= v0.triangleCount) {
  69610. if (tCount) {
  69611. for (var c = 0; c < tCount; c++) {
  69612. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  69613. }
  69614. }
  69615. }
  69616. else {
  69617. v0.triangleStart = tStart;
  69618. }
  69619. v0.triangleCount = tCount;
  69620. break;
  69621. }
  69622. }
  69623. };
  69624. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  69625. }, 0);
  69626. };
  69627. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  69628. if (triangleCount - deletedTriangles <= targetCount)
  69629. loop.breakLoop();
  69630. else {
  69631. iterationFunction(loop.index, function () {
  69632. loop.executeNext();
  69633. });
  69634. }
  69635. }, function () {
  69636. setTimeout(function () {
  69637. //reconstruct this part of the mesh
  69638. _this.reconstructMesh(submeshIndex);
  69639. successCallback();
  69640. }, 0);
  69641. });
  69642. };
  69643. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  69644. var _this = this;
  69645. this.vertices = [];
  69646. this.triangles = [];
  69647. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  69648. var indices = this._mesh.getIndices();
  69649. var submesh = this._mesh.subMeshes[submeshIndex];
  69650. var findInVertices = function (positionToSearch) {
  69651. if (optimizeMesh) {
  69652. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  69653. if (_this.vertices[ii].position.equals(positionToSearch)) {
  69654. return _this.vertices[ii];
  69655. }
  69656. }
  69657. }
  69658. return null;
  69659. };
  69660. var vertexReferences = [];
  69661. var vertexInit = function (i) {
  69662. var offset = i + submesh.verticesStart;
  69663. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  69664. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  69665. vertex.originalOffsets.push(offset);
  69666. if (vertex.id === _this.vertices.length) {
  69667. _this.vertices.push(vertex);
  69668. }
  69669. vertexReferences.push(vertex.id);
  69670. };
  69671. //var totalVertices = mesh.getTotalVertices();
  69672. var totalVertices = submesh.verticesCount;
  69673. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  69674. var indicesInit = function (i) {
  69675. var offset = (submesh.indexStart / 3) + i;
  69676. var pos = (offset * 3);
  69677. var i0 = indices[pos + 0];
  69678. var i1 = indices[pos + 1];
  69679. var i2 = indices[pos + 2];
  69680. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  69681. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  69682. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  69683. var triangle = new DecimationTriangle([v0, v1, v2]);
  69684. triangle.originalOffset = pos;
  69685. _this.triangles.push(triangle);
  69686. };
  69687. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  69688. _this.init(callback);
  69689. });
  69690. });
  69691. };
  69692. QuadraticErrorSimplification.prototype.init = function (callback) {
  69693. var _this = this;
  69694. var triangleInit1 = function (i) {
  69695. var t = _this.triangles[i];
  69696. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  69697. for (var j = 0; j < 3; j++) {
  69698. 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))));
  69699. }
  69700. };
  69701. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  69702. var triangleInit2 = function (i) {
  69703. var t = _this.triangles[i];
  69704. for (var j = 0; j < 3; ++j) {
  69705. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  69706. }
  69707. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  69708. };
  69709. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  69710. _this.initialized = true;
  69711. callback();
  69712. });
  69713. });
  69714. };
  69715. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  69716. var newTriangles = [];
  69717. var i;
  69718. for (i = 0; i < this.vertices.length; ++i) {
  69719. this.vertices[i].triangleCount = 0;
  69720. }
  69721. var t;
  69722. var j;
  69723. for (i = 0; i < this.triangles.length; ++i) {
  69724. if (!this.triangles[i].deleted) {
  69725. t = this.triangles[i];
  69726. for (j = 0; j < 3; ++j) {
  69727. t.vertices[j].triangleCount = 1;
  69728. }
  69729. newTriangles.push(t);
  69730. }
  69731. }
  69732. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  69733. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  69734. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  69735. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  69736. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  69737. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  69738. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  69739. var vertexCount = 0;
  69740. for (i = 0; i < this.vertices.length; ++i) {
  69741. var vertex = this.vertices[i];
  69742. vertex.id = vertexCount;
  69743. if (vertex.triangleCount) {
  69744. vertex.originalOffsets.forEach(function (originalOffset) {
  69745. newPositionData.push(vertex.position.x);
  69746. newPositionData.push(vertex.position.y);
  69747. newPositionData.push(vertex.position.z);
  69748. newNormalData.push(normalData[originalOffset * 3]);
  69749. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  69750. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  69751. if (uvs && uvs.length) {
  69752. newUVsData.push(uvs[(originalOffset * 2)]);
  69753. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  69754. }
  69755. else if (colorsData && colorsData.length) {
  69756. newColorsData.push(colorsData[(originalOffset * 4)]);
  69757. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  69758. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  69759. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  69760. }
  69761. ++vertexCount;
  69762. });
  69763. }
  69764. }
  69765. var startingIndex = this._reconstructedMesh.getTotalIndices();
  69766. var startingVertex = this._reconstructedMesh.getTotalVertices();
  69767. var submeshesArray = this._reconstructedMesh.subMeshes;
  69768. this._reconstructedMesh.subMeshes = [];
  69769. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  69770. var originalIndices = this._mesh.getIndices();
  69771. for (i = 0; i < newTriangles.length; ++i) {
  69772. t = newTriangles[i]; //now get the new referencing point for each vertex
  69773. [0, 1, 2].forEach(function (idx) {
  69774. var id = originalIndices[t.originalOffset + idx];
  69775. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  69776. if (offset < 0)
  69777. offset = 0;
  69778. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  69779. });
  69780. }
  69781. //overwriting the old vertex buffers and indices.
  69782. this._reconstructedMesh.setIndices(newIndicesArray);
  69783. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  69784. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  69785. if (newUVsData.length > 0)
  69786. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  69787. if (newColorsData.length > 0)
  69788. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  69789. //create submesh
  69790. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  69791. if (submeshIndex > 0) {
  69792. this._reconstructedMesh.subMeshes = [];
  69793. submeshesArray.forEach(function (submesh) {
  69794. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  69795. });
  69796. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  69797. }
  69798. };
  69799. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  69800. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  69801. this._reconstructedMesh.material = this._mesh.material;
  69802. this._reconstructedMesh.parent = this._mesh.parent;
  69803. this._reconstructedMesh.isVisible = false;
  69804. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  69805. };
  69806. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  69807. for (var i = 0; i < vertex1.triangleCount; ++i) {
  69808. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  69809. if (t.deleted)
  69810. continue;
  69811. var s = this.references[vertex1.triangleStart + i].vertexId;
  69812. var v1 = t.vertices[(s + 1) % 3];
  69813. var v2 = t.vertices[(s + 2) % 3];
  69814. if ((v1 === vertex2 || v2 === vertex2)) {
  69815. deletedArray[i] = true;
  69816. delTr.push(t);
  69817. continue;
  69818. }
  69819. var d1 = v1.position.subtract(point);
  69820. d1 = d1.normalize();
  69821. var d2 = v2.position.subtract(point);
  69822. d2 = d2.normalize();
  69823. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  69824. return true;
  69825. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  69826. deletedArray[i] = false;
  69827. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  69828. return true;
  69829. }
  69830. return false;
  69831. };
  69832. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  69833. var newDeleted = deletedTriangles;
  69834. for (var i = 0; i < vertex.triangleCount; ++i) {
  69835. var ref = this.references[vertex.triangleStart + i];
  69836. var t = this.triangles[ref.triangleId];
  69837. if (t.deleted)
  69838. continue;
  69839. if (deletedArray[i] && t.deletePending) {
  69840. t.deleted = true;
  69841. newDeleted++;
  69842. continue;
  69843. }
  69844. t.vertices[ref.vertexId] = origVertex;
  69845. t.isDirty = true;
  69846. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  69847. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  69848. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  69849. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  69850. this.references.push(ref);
  69851. }
  69852. return newDeleted;
  69853. };
  69854. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  69855. for (var i = 0; i < this.vertices.length; ++i) {
  69856. var vCount = [];
  69857. var vId = [];
  69858. var v = this.vertices[i];
  69859. var j;
  69860. for (j = 0; j < v.triangleCount; ++j) {
  69861. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  69862. for (var ii = 0; ii < 3; ii++) {
  69863. var ofs = 0;
  69864. var vv = triangle.vertices[ii];
  69865. while (ofs < vCount.length) {
  69866. if (vId[ofs] === vv.id)
  69867. break;
  69868. ++ofs;
  69869. }
  69870. if (ofs === vCount.length) {
  69871. vCount.push(1);
  69872. vId.push(vv.id);
  69873. }
  69874. else {
  69875. vCount[ofs]++;
  69876. }
  69877. }
  69878. }
  69879. for (j = 0; j < vCount.length; ++j) {
  69880. if (vCount[j] === 1) {
  69881. this.vertices[vId[j]].isBorder = true;
  69882. }
  69883. else {
  69884. this.vertices[vId[j]].isBorder = false;
  69885. }
  69886. }
  69887. }
  69888. };
  69889. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  69890. if (identifyBorders === void 0) { identifyBorders = false; }
  69891. var i;
  69892. if (!identifyBorders) {
  69893. var newTrianglesVector = [];
  69894. for (i = 0; i < this.triangles.length; ++i) {
  69895. if (!this.triangles[i].deleted) {
  69896. newTrianglesVector.push(this.triangles[i]);
  69897. }
  69898. }
  69899. this.triangles = newTrianglesVector;
  69900. }
  69901. for (i = 0; i < this.vertices.length; ++i) {
  69902. this.vertices[i].triangleCount = 0;
  69903. this.vertices[i].triangleStart = 0;
  69904. }
  69905. var t;
  69906. var j;
  69907. var v;
  69908. for (i = 0; i < this.triangles.length; ++i) {
  69909. t = this.triangles[i];
  69910. for (j = 0; j < 3; ++j) {
  69911. v = t.vertices[j];
  69912. v.triangleCount++;
  69913. }
  69914. }
  69915. var tStart = 0;
  69916. for (i = 0; i < this.vertices.length; ++i) {
  69917. this.vertices[i].triangleStart = tStart;
  69918. tStart += this.vertices[i].triangleCount;
  69919. this.vertices[i].triangleCount = 0;
  69920. }
  69921. var newReferences = new Array(this.triangles.length * 3);
  69922. for (i = 0; i < this.triangles.length; ++i) {
  69923. t = this.triangles[i];
  69924. for (j = 0; j < 3; ++j) {
  69925. v = t.vertices[j];
  69926. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  69927. v.triangleCount++;
  69928. }
  69929. }
  69930. this.references = newReferences;
  69931. if (identifyBorders) {
  69932. this.identifyBorder();
  69933. }
  69934. };
  69935. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  69936. var x = point.x;
  69937. var y = point.y;
  69938. var z = point.z;
  69939. 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
  69940. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  69941. };
  69942. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  69943. var q = vertex1.q.add(vertex2.q);
  69944. var border = vertex1.isBorder && vertex2.isBorder;
  69945. var error = 0;
  69946. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  69947. if (qDet !== 0 && !border) {
  69948. if (!pointResult) {
  69949. pointResult = BABYLON.Vector3.Zero();
  69950. }
  69951. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  69952. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  69953. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  69954. error = this.vertexError(q, pointResult);
  69955. }
  69956. else {
  69957. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  69958. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  69959. var error1 = this.vertexError(q, vertex1.position);
  69960. var error2 = this.vertexError(q, vertex2.position);
  69961. var error3 = this.vertexError(q, p3);
  69962. error = Math.min(error1, error2, error3);
  69963. if (error === error1) {
  69964. if (pointResult) {
  69965. pointResult.copyFrom(vertex1.position);
  69966. }
  69967. }
  69968. else if (error === error2) {
  69969. if (pointResult) {
  69970. pointResult.copyFrom(vertex2.position);
  69971. }
  69972. }
  69973. else {
  69974. if (pointResult) {
  69975. pointResult.copyFrom(p3);
  69976. }
  69977. }
  69978. }
  69979. return error;
  69980. };
  69981. return QuadraticErrorSimplification;
  69982. }());
  69983. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  69984. })(BABYLON || (BABYLON = {}));
  69985. //# sourceMappingURL=babylon.meshSimplification.js.map
  69986. var BABYLON;
  69987. (function (BABYLON) {
  69988. var Internals;
  69989. (function (Internals) {
  69990. var MeshLODLevel = /** @class */ (function () {
  69991. function MeshLODLevel(distance, mesh) {
  69992. this.distance = distance;
  69993. this.mesh = mesh;
  69994. }
  69995. return MeshLODLevel;
  69996. }());
  69997. Internals.MeshLODLevel = MeshLODLevel;
  69998. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  69999. })(BABYLON || (BABYLON = {}));
  70000. //# sourceMappingURL=babylon.meshLODLevel.js.map
  70001. var BABYLON;
  70002. (function (BABYLON) {
  70003. // Standard optimizations
  70004. var SceneOptimization = /** @class */ (function () {
  70005. function SceneOptimization(priority) {
  70006. if (priority === void 0) { priority = 0; }
  70007. this.priority = priority;
  70008. this.apply = function (scene) {
  70009. return true; // Return true if everything that can be done was applied
  70010. };
  70011. }
  70012. return SceneOptimization;
  70013. }());
  70014. BABYLON.SceneOptimization = SceneOptimization;
  70015. var TextureOptimization = /** @class */ (function (_super) {
  70016. __extends(TextureOptimization, _super);
  70017. function TextureOptimization(priority, maximumSize) {
  70018. if (priority === void 0) { priority = 0; }
  70019. if (maximumSize === void 0) { maximumSize = 1024; }
  70020. var _this = _super.call(this, priority) || this;
  70021. _this.priority = priority;
  70022. _this.maximumSize = maximumSize;
  70023. _this.apply = function (scene) {
  70024. var allDone = true;
  70025. for (var index = 0; index < scene.textures.length; index++) {
  70026. var texture = scene.textures[index];
  70027. if (!texture.canRescale || texture.getContext) {
  70028. continue;
  70029. }
  70030. var currentSize = texture.getSize();
  70031. var maxDimension = Math.max(currentSize.width, currentSize.height);
  70032. if (maxDimension > _this.maximumSize) {
  70033. texture.scale(0.5);
  70034. allDone = false;
  70035. }
  70036. }
  70037. return allDone;
  70038. };
  70039. return _this;
  70040. }
  70041. return TextureOptimization;
  70042. }(SceneOptimization));
  70043. BABYLON.TextureOptimization = TextureOptimization;
  70044. var HardwareScalingOptimization = /** @class */ (function (_super) {
  70045. __extends(HardwareScalingOptimization, _super);
  70046. function HardwareScalingOptimization(priority, maximumScale) {
  70047. if (priority === void 0) { priority = 0; }
  70048. if (maximumScale === void 0) { maximumScale = 2; }
  70049. var _this = _super.call(this, priority) || this;
  70050. _this.priority = priority;
  70051. _this.maximumScale = maximumScale;
  70052. _this._currentScale = 1;
  70053. _this.apply = function (scene) {
  70054. _this._currentScale++;
  70055. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  70056. return _this._currentScale >= _this.maximumScale;
  70057. };
  70058. return _this;
  70059. }
  70060. return HardwareScalingOptimization;
  70061. }(SceneOptimization));
  70062. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  70063. var ShadowsOptimization = /** @class */ (function (_super) {
  70064. __extends(ShadowsOptimization, _super);
  70065. function ShadowsOptimization() {
  70066. var _this = _super !== null && _super.apply(this, arguments) || this;
  70067. _this.apply = function (scene) {
  70068. scene.shadowsEnabled = false;
  70069. return true;
  70070. };
  70071. return _this;
  70072. }
  70073. return ShadowsOptimization;
  70074. }(SceneOptimization));
  70075. BABYLON.ShadowsOptimization = ShadowsOptimization;
  70076. var PostProcessesOptimization = /** @class */ (function (_super) {
  70077. __extends(PostProcessesOptimization, _super);
  70078. function PostProcessesOptimization() {
  70079. var _this = _super !== null && _super.apply(this, arguments) || this;
  70080. _this.apply = function (scene) {
  70081. scene.postProcessesEnabled = false;
  70082. return true;
  70083. };
  70084. return _this;
  70085. }
  70086. return PostProcessesOptimization;
  70087. }(SceneOptimization));
  70088. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  70089. var LensFlaresOptimization = /** @class */ (function (_super) {
  70090. __extends(LensFlaresOptimization, _super);
  70091. function LensFlaresOptimization() {
  70092. var _this = _super !== null && _super.apply(this, arguments) || this;
  70093. _this.apply = function (scene) {
  70094. scene.lensFlaresEnabled = false;
  70095. return true;
  70096. };
  70097. return _this;
  70098. }
  70099. return LensFlaresOptimization;
  70100. }(SceneOptimization));
  70101. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  70102. var ParticlesOptimization = /** @class */ (function (_super) {
  70103. __extends(ParticlesOptimization, _super);
  70104. function ParticlesOptimization() {
  70105. var _this = _super !== null && _super.apply(this, arguments) || this;
  70106. _this.apply = function (scene) {
  70107. scene.particlesEnabled = false;
  70108. return true;
  70109. };
  70110. return _this;
  70111. }
  70112. return ParticlesOptimization;
  70113. }(SceneOptimization));
  70114. BABYLON.ParticlesOptimization = ParticlesOptimization;
  70115. var RenderTargetsOptimization = /** @class */ (function (_super) {
  70116. __extends(RenderTargetsOptimization, _super);
  70117. function RenderTargetsOptimization() {
  70118. var _this = _super !== null && _super.apply(this, arguments) || this;
  70119. _this.apply = function (scene) {
  70120. scene.renderTargetsEnabled = false;
  70121. return true;
  70122. };
  70123. return _this;
  70124. }
  70125. return RenderTargetsOptimization;
  70126. }(SceneOptimization));
  70127. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  70128. var MergeMeshesOptimization = /** @class */ (function (_super) {
  70129. __extends(MergeMeshesOptimization, _super);
  70130. function MergeMeshesOptimization() {
  70131. var _this = _super !== null && _super.apply(this, arguments) || this;
  70132. _this._canBeMerged = function (abstractMesh) {
  70133. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  70134. return false;
  70135. }
  70136. var mesh = abstractMesh;
  70137. if (!mesh.isVisible || !mesh.isEnabled()) {
  70138. return false;
  70139. }
  70140. if (mesh.instances.length > 0) {
  70141. return false;
  70142. }
  70143. if (mesh.skeleton || mesh.hasLODLevels) {
  70144. return false;
  70145. }
  70146. if (mesh.parent) {
  70147. return false;
  70148. }
  70149. return true;
  70150. };
  70151. _this.apply = function (scene, updateSelectionTree) {
  70152. var globalPool = scene.meshes.slice(0);
  70153. var globalLength = globalPool.length;
  70154. for (var index = 0; index < globalLength; index++) {
  70155. var currentPool = new Array();
  70156. var current = globalPool[index];
  70157. // Checks
  70158. if (!_this._canBeMerged(current)) {
  70159. continue;
  70160. }
  70161. currentPool.push(current);
  70162. // Find compatible meshes
  70163. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  70164. var otherMesh = globalPool[subIndex];
  70165. if (!_this._canBeMerged(otherMesh)) {
  70166. continue;
  70167. }
  70168. if (otherMesh.material !== current.material) {
  70169. continue;
  70170. }
  70171. if (otherMesh.checkCollisions !== current.checkCollisions) {
  70172. continue;
  70173. }
  70174. currentPool.push(otherMesh);
  70175. globalLength--;
  70176. globalPool.splice(subIndex, 1);
  70177. subIndex--;
  70178. }
  70179. if (currentPool.length < 2) {
  70180. continue;
  70181. }
  70182. // Merge meshes
  70183. BABYLON.Mesh.MergeMeshes(currentPool);
  70184. }
  70185. if (updateSelectionTree != undefined) {
  70186. if (updateSelectionTree) {
  70187. scene.createOrUpdateSelectionOctree();
  70188. }
  70189. }
  70190. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  70191. scene.createOrUpdateSelectionOctree();
  70192. }
  70193. return true;
  70194. };
  70195. return _this;
  70196. }
  70197. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  70198. get: function () {
  70199. return MergeMeshesOptimization._UpdateSelectionTree;
  70200. },
  70201. set: function (value) {
  70202. MergeMeshesOptimization._UpdateSelectionTree = value;
  70203. },
  70204. enumerable: true,
  70205. configurable: true
  70206. });
  70207. MergeMeshesOptimization._UpdateSelectionTree = false;
  70208. return MergeMeshesOptimization;
  70209. }(SceneOptimization));
  70210. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  70211. // Options
  70212. var SceneOptimizerOptions = /** @class */ (function () {
  70213. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  70214. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  70215. if (trackerDuration === void 0) { trackerDuration = 2000; }
  70216. this.targetFrameRate = targetFrameRate;
  70217. this.trackerDuration = trackerDuration;
  70218. this.optimizations = new Array();
  70219. }
  70220. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  70221. var result = new SceneOptimizerOptions(targetFrameRate);
  70222. var priority = 0;
  70223. result.optimizations.push(new MergeMeshesOptimization(priority));
  70224. result.optimizations.push(new ShadowsOptimization(priority));
  70225. result.optimizations.push(new LensFlaresOptimization(priority));
  70226. // Next priority
  70227. priority++;
  70228. result.optimizations.push(new PostProcessesOptimization(priority));
  70229. result.optimizations.push(new ParticlesOptimization(priority));
  70230. // Next priority
  70231. priority++;
  70232. result.optimizations.push(new TextureOptimization(priority, 1024));
  70233. return result;
  70234. };
  70235. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  70236. var result = new SceneOptimizerOptions(targetFrameRate);
  70237. var priority = 0;
  70238. result.optimizations.push(new MergeMeshesOptimization(priority));
  70239. result.optimizations.push(new ShadowsOptimization(priority));
  70240. result.optimizations.push(new LensFlaresOptimization(priority));
  70241. // Next priority
  70242. priority++;
  70243. result.optimizations.push(new PostProcessesOptimization(priority));
  70244. result.optimizations.push(new ParticlesOptimization(priority));
  70245. // Next priority
  70246. priority++;
  70247. result.optimizations.push(new TextureOptimization(priority, 512));
  70248. // Next priority
  70249. priority++;
  70250. result.optimizations.push(new RenderTargetsOptimization(priority));
  70251. // Next priority
  70252. priority++;
  70253. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  70254. return result;
  70255. };
  70256. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  70257. var result = new SceneOptimizerOptions(targetFrameRate);
  70258. var priority = 0;
  70259. result.optimizations.push(new MergeMeshesOptimization(priority));
  70260. result.optimizations.push(new ShadowsOptimization(priority));
  70261. result.optimizations.push(new LensFlaresOptimization(priority));
  70262. // Next priority
  70263. priority++;
  70264. result.optimizations.push(new PostProcessesOptimization(priority));
  70265. result.optimizations.push(new ParticlesOptimization(priority));
  70266. // Next priority
  70267. priority++;
  70268. result.optimizations.push(new TextureOptimization(priority, 256));
  70269. // Next priority
  70270. priority++;
  70271. result.optimizations.push(new RenderTargetsOptimization(priority));
  70272. // Next priority
  70273. priority++;
  70274. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  70275. return result;
  70276. };
  70277. return SceneOptimizerOptions;
  70278. }());
  70279. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  70280. // Scene optimizer tool
  70281. var SceneOptimizer = /** @class */ (function () {
  70282. function SceneOptimizer() {
  70283. }
  70284. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  70285. // TODO: add an epsilon
  70286. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  70287. if (onSuccess) {
  70288. onSuccess();
  70289. }
  70290. return;
  70291. }
  70292. // Apply current level of optimizations
  70293. var allDone = true;
  70294. var noOptimizationApplied = true;
  70295. for (var index = 0; index < options.optimizations.length; index++) {
  70296. var optimization = options.optimizations[index];
  70297. if (optimization.priority === currentPriorityLevel) {
  70298. noOptimizationApplied = false;
  70299. allDone = allDone && optimization.apply(scene);
  70300. }
  70301. }
  70302. // If no optimization was applied, this is a failure :(
  70303. if (noOptimizationApplied) {
  70304. if (onFailure) {
  70305. onFailure();
  70306. }
  70307. return;
  70308. }
  70309. // If all optimizations were done, move to next level
  70310. if (allDone) {
  70311. currentPriorityLevel++;
  70312. }
  70313. // Let's the system running for a specific amount of time before checking FPS
  70314. scene.executeWhenReady(function () {
  70315. setTimeout(function () {
  70316. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  70317. }, options.trackerDuration);
  70318. });
  70319. };
  70320. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  70321. if (!options) {
  70322. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  70323. }
  70324. // Let's the system running for a specific amount of time before checking FPS
  70325. scene.executeWhenReady(function () {
  70326. setTimeout(function () {
  70327. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  70328. }, options.trackerDuration);
  70329. });
  70330. };
  70331. return SceneOptimizer;
  70332. }());
  70333. BABYLON.SceneOptimizer = SceneOptimizer;
  70334. })(BABYLON || (BABYLON = {}));
  70335. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  70336. var BABYLON;
  70337. (function (BABYLON) {
  70338. var OutlineRenderer = /** @class */ (function () {
  70339. function OutlineRenderer(scene) {
  70340. this.zOffset = 1;
  70341. this._scene = scene;
  70342. }
  70343. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  70344. var _this = this;
  70345. if (useOverlay === void 0) { useOverlay = false; }
  70346. var scene = this._scene;
  70347. var engine = this._scene.getEngine();
  70348. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  70349. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  70350. return;
  70351. }
  70352. var mesh = subMesh.getRenderingMesh();
  70353. var material = subMesh.getMaterial();
  70354. engine.enableEffect(this._effect);
  70355. // Logarithmic depth
  70356. if (material.useLogarithmicDepth) {
  70357. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  70358. }
  70359. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  70360. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  70361. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  70362. // Bones
  70363. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70364. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  70365. }
  70366. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  70367. // Alpha test
  70368. if (material && material.needAlphaTesting()) {
  70369. var alphaTexture = material.getAlphaTestTexture();
  70370. if (alphaTexture) {
  70371. this._effect.setTexture("diffuseSampler", alphaTexture);
  70372. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  70373. }
  70374. }
  70375. engine.setZOffset(-this.zOffset);
  70376. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  70377. engine.setZOffset(0);
  70378. };
  70379. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  70380. var defines = [];
  70381. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  70382. var mesh = subMesh.getMesh();
  70383. var material = subMesh.getMaterial();
  70384. if (material) {
  70385. // Alpha test
  70386. if (material.needAlphaTesting()) {
  70387. defines.push("#define ALPHATEST");
  70388. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70389. attribs.push(BABYLON.VertexBuffer.UVKind);
  70390. defines.push("#define UV1");
  70391. }
  70392. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70393. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70394. defines.push("#define UV2");
  70395. }
  70396. }
  70397. //Logarithmic depth
  70398. if (material.useLogarithmicDepth) {
  70399. defines.push("#define LOGARITHMICDEPTH");
  70400. }
  70401. }
  70402. // Bones
  70403. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70404. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70405. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70406. if (mesh.numBoneInfluencers > 4) {
  70407. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  70408. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  70409. }
  70410. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70411. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  70412. }
  70413. else {
  70414. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70415. }
  70416. // Instances
  70417. if (useInstances) {
  70418. defines.push("#define INSTANCES");
  70419. attribs.push("world0");
  70420. attribs.push("world1");
  70421. attribs.push("world2");
  70422. attribs.push("world3");
  70423. }
  70424. // Get correct effect
  70425. var join = defines.join("\n");
  70426. if (this._cachedDefines !== join) {
  70427. this._cachedDefines = join;
  70428. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  70429. }
  70430. return this._effect.isReady();
  70431. };
  70432. return OutlineRenderer;
  70433. }());
  70434. BABYLON.OutlineRenderer = OutlineRenderer;
  70435. })(BABYLON || (BABYLON = {}));
  70436. //# sourceMappingURL=babylon.outlineRenderer.js.map
  70437. var BABYLON;
  70438. (function (BABYLON) {
  70439. var FaceAdjacencies = /** @class */ (function () {
  70440. function FaceAdjacencies() {
  70441. this.edges = new Array();
  70442. this.edgesConnectedCount = 0;
  70443. }
  70444. return FaceAdjacencies;
  70445. }());
  70446. var EdgesRenderer = /** @class */ (function () {
  70447. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  70448. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  70449. if (epsilon === void 0) { epsilon = 0.95; }
  70450. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  70451. this.edgesWidthScalerForOrthographic = 1000.0;
  70452. this.edgesWidthScalerForPerspective = 50.0;
  70453. this._linesPositions = new Array();
  70454. this._linesNormals = new Array();
  70455. this._linesIndices = new Array();
  70456. this._buffers = {};
  70457. this._checkVerticesInsteadOfIndices = false;
  70458. this._source = source;
  70459. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  70460. this._epsilon = epsilon;
  70461. this._prepareRessources();
  70462. this._generateEdgesLines();
  70463. }
  70464. EdgesRenderer.prototype._prepareRessources = function () {
  70465. if (this._lineShader) {
  70466. return;
  70467. }
  70468. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  70469. attributes: ["position", "normal"],
  70470. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  70471. });
  70472. this._lineShader.disableDepthWrite = true;
  70473. this._lineShader.backFaceCulling = false;
  70474. };
  70475. EdgesRenderer.prototype._rebuild = function () {
  70476. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  70477. if (buffer) {
  70478. buffer._rebuild();
  70479. }
  70480. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  70481. if (buffer) {
  70482. buffer._rebuild();
  70483. }
  70484. var scene = this._source.getScene();
  70485. var engine = scene.getEngine();
  70486. this._ib = engine.createIndexBuffer(this._linesIndices);
  70487. };
  70488. EdgesRenderer.prototype.dispose = function () {
  70489. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  70490. if (buffer) {
  70491. buffer.dispose();
  70492. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  70493. }
  70494. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  70495. if (buffer) {
  70496. buffer.dispose();
  70497. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  70498. }
  70499. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  70500. this._lineShader.dispose();
  70501. };
  70502. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  70503. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  70504. return 0;
  70505. }
  70506. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  70507. return 1;
  70508. }
  70509. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  70510. return 2;
  70511. }
  70512. return -1;
  70513. };
  70514. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  70515. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  70516. return 0;
  70517. }
  70518. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  70519. return 1;
  70520. }
  70521. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  70522. return 2;
  70523. }
  70524. return -1;
  70525. };
  70526. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  70527. var needToCreateLine;
  70528. if (edge === undefined) {
  70529. needToCreateLine = true;
  70530. }
  70531. else {
  70532. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  70533. needToCreateLine = dotProduct < this._epsilon;
  70534. }
  70535. if (needToCreateLine) {
  70536. var offset = this._linesPositions.length / 3;
  70537. var normal = p0.subtract(p1);
  70538. normal.normalize();
  70539. // Positions
  70540. this._linesPositions.push(p0.x);
  70541. this._linesPositions.push(p0.y);
  70542. this._linesPositions.push(p0.z);
  70543. this._linesPositions.push(p0.x);
  70544. this._linesPositions.push(p0.y);
  70545. this._linesPositions.push(p0.z);
  70546. this._linesPositions.push(p1.x);
  70547. this._linesPositions.push(p1.y);
  70548. this._linesPositions.push(p1.z);
  70549. this._linesPositions.push(p1.x);
  70550. this._linesPositions.push(p1.y);
  70551. this._linesPositions.push(p1.z);
  70552. // Normals
  70553. this._linesNormals.push(p1.x);
  70554. this._linesNormals.push(p1.y);
  70555. this._linesNormals.push(p1.z);
  70556. this._linesNormals.push(-1);
  70557. this._linesNormals.push(p1.x);
  70558. this._linesNormals.push(p1.y);
  70559. this._linesNormals.push(p1.z);
  70560. this._linesNormals.push(1);
  70561. this._linesNormals.push(p0.x);
  70562. this._linesNormals.push(p0.y);
  70563. this._linesNormals.push(p0.z);
  70564. this._linesNormals.push(-1);
  70565. this._linesNormals.push(p0.x);
  70566. this._linesNormals.push(p0.y);
  70567. this._linesNormals.push(p0.z);
  70568. this._linesNormals.push(1);
  70569. // Indices
  70570. this._linesIndices.push(offset);
  70571. this._linesIndices.push(offset + 1);
  70572. this._linesIndices.push(offset + 2);
  70573. this._linesIndices.push(offset);
  70574. this._linesIndices.push(offset + 2);
  70575. this._linesIndices.push(offset + 3);
  70576. }
  70577. };
  70578. EdgesRenderer.prototype._generateEdgesLines = function () {
  70579. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  70580. var indices = this._source.getIndices();
  70581. // First let's find adjacencies
  70582. var adjacencies = new Array();
  70583. var faceNormals = new Array();
  70584. var index;
  70585. var faceAdjacencies;
  70586. // Prepare faces
  70587. for (index = 0; index < indices.length; index += 3) {
  70588. faceAdjacencies = new FaceAdjacencies();
  70589. var p0Index = indices[index];
  70590. var p1Index = indices[index + 1];
  70591. var p2Index = indices[index + 2];
  70592. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  70593. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  70594. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  70595. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  70596. faceNormal.normalize();
  70597. faceNormals.push(faceNormal);
  70598. adjacencies.push(faceAdjacencies);
  70599. }
  70600. // Scan
  70601. for (index = 0; index < adjacencies.length; index++) {
  70602. faceAdjacencies = adjacencies[index];
  70603. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  70604. var otherFaceAdjacencies = adjacencies[otherIndex];
  70605. if (faceAdjacencies.edgesConnectedCount === 3) {
  70606. break;
  70607. }
  70608. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  70609. continue;
  70610. }
  70611. var otherP0 = indices[otherIndex * 3];
  70612. var otherP1 = indices[otherIndex * 3 + 1];
  70613. var otherP2 = indices[otherIndex * 3 + 2];
  70614. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  70615. var otherEdgeIndex;
  70616. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  70617. continue;
  70618. }
  70619. switch (edgeIndex) {
  70620. case 0:
  70621. if (this._checkVerticesInsteadOfIndices) {
  70622. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  70623. }
  70624. else {
  70625. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  70626. }
  70627. break;
  70628. case 1:
  70629. if (this._checkVerticesInsteadOfIndices) {
  70630. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  70631. }
  70632. else {
  70633. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  70634. }
  70635. break;
  70636. case 2:
  70637. if (this._checkVerticesInsteadOfIndices) {
  70638. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  70639. }
  70640. else {
  70641. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  70642. }
  70643. break;
  70644. }
  70645. if (otherEdgeIndex === -1) {
  70646. continue;
  70647. }
  70648. faceAdjacencies.edges[edgeIndex] = otherIndex;
  70649. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  70650. faceAdjacencies.edgesConnectedCount++;
  70651. otherFaceAdjacencies.edgesConnectedCount++;
  70652. if (faceAdjacencies.edgesConnectedCount === 3) {
  70653. break;
  70654. }
  70655. }
  70656. }
  70657. }
  70658. // Create lines
  70659. for (index = 0; index < adjacencies.length; index++) {
  70660. // 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
  70661. var current = adjacencies[index];
  70662. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  70663. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  70664. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  70665. }
  70666. // Merge into a single mesh
  70667. var engine = this._source.getScene().getEngine();
  70668. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  70669. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  70670. this._ib = engine.createIndexBuffer(this._linesIndices);
  70671. this._indicesCount = this._linesIndices.length;
  70672. };
  70673. EdgesRenderer.prototype.render = function () {
  70674. if (!this._lineShader.isReady()) {
  70675. return;
  70676. }
  70677. var scene = this._source.getScene();
  70678. var engine = scene.getEngine();
  70679. this._lineShader._preBind();
  70680. // VBOs
  70681. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  70682. scene.resetCachedMaterial();
  70683. this._lineShader.setColor4("color", this._source.edgesColor);
  70684. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  70685. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  70686. }
  70687. else {
  70688. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  70689. }
  70690. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  70691. this._lineShader.bind(this._source.getWorldMatrix());
  70692. // Draw order
  70693. engine.draw(true, 0, this._indicesCount);
  70694. this._lineShader.unbind();
  70695. engine.setDepthWrite(true);
  70696. };
  70697. return EdgesRenderer;
  70698. }());
  70699. BABYLON.EdgesRenderer = EdgesRenderer;
  70700. })(BABYLON || (BABYLON = {}));
  70701. //# sourceMappingURL=babylon.edgesRenderer.js.map
  70702. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  70703. /// <reference path="..\Math\babylon.math.ts" />
  70704. var BABYLON;
  70705. (function (BABYLON) {
  70706. /**
  70707. * Special Glow Blur post process only blurring the alpha channel
  70708. * It enforces keeping the most luminous color in the color channel.
  70709. */
  70710. var GlowBlurPostProcess = /** @class */ (function (_super) {
  70711. __extends(GlowBlurPostProcess, _super);
  70712. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  70713. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70714. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  70715. _this.direction = direction;
  70716. _this.kernel = kernel;
  70717. _this.onApplyObservable.add(function (effect) {
  70718. effect.setFloat2("screenSize", _this.width, _this.height);
  70719. effect.setVector2("direction", _this.direction);
  70720. effect.setFloat("blurWidth", _this.kernel);
  70721. });
  70722. return _this;
  70723. }
  70724. return GlowBlurPostProcess;
  70725. }(BABYLON.PostProcess));
  70726. /**
  70727. * The highlight layer Helps adding a glow effect around a mesh.
  70728. *
  70729. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  70730. * glowy meshes to your scene.
  70731. *
  70732. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  70733. */
  70734. var HighlightLayer = /** @class */ (function () {
  70735. /**
  70736. * Instantiates a new highlight Layer and references it to the scene..
  70737. * @param name The name of the layer
  70738. * @param scene The scene to use the layer in
  70739. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  70740. */
  70741. function HighlightLayer(name, scene, options) {
  70742. this.name = name;
  70743. this._vertexBuffers = {};
  70744. this._mainTextureDesiredSize = { width: 0, height: 0 };
  70745. this._meshes = {};
  70746. this._maxSize = 0;
  70747. this._shouldRender = false;
  70748. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  70749. this._excludedMeshes = {};
  70750. /**
  70751. * Specifies whether or not the inner glow is ACTIVE in the layer.
  70752. */
  70753. this.innerGlow = true;
  70754. /**
  70755. * Specifies whether or not the outer glow is ACTIVE in the layer.
  70756. */
  70757. this.outerGlow = true;
  70758. /**
  70759. * Specifies wether the highlight layer is enabled or not.
  70760. */
  70761. this.isEnabled = true;
  70762. /**
  70763. * An event triggered when the highlight layer has been disposed.
  70764. * @type {BABYLON.Observable}
  70765. */
  70766. this.onDisposeObservable = new BABYLON.Observable();
  70767. /**
  70768. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  70769. * @type {BABYLON.Observable}
  70770. */
  70771. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  70772. /**
  70773. * An event triggered when the highlight layer is being blurred.
  70774. * @type {BABYLON.Observable}
  70775. */
  70776. this.onBeforeBlurObservable = new BABYLON.Observable();
  70777. /**
  70778. * An event triggered when the highlight layer has been blurred.
  70779. * @type {BABYLON.Observable}
  70780. */
  70781. this.onAfterBlurObservable = new BABYLON.Observable();
  70782. /**
  70783. * An event triggered when the glowing blurred texture is being merged in the scene.
  70784. * @type {BABYLON.Observable}
  70785. */
  70786. this.onBeforeComposeObservable = new BABYLON.Observable();
  70787. /**
  70788. * An event triggered when the glowing blurred texture has been merged in the scene.
  70789. * @type {BABYLON.Observable}
  70790. */
  70791. this.onAfterComposeObservable = new BABYLON.Observable();
  70792. /**
  70793. * An event triggered when the highlight layer changes its size.
  70794. * @type {BABYLON.Observable}
  70795. */
  70796. this.onSizeChangedObservable = new BABYLON.Observable();
  70797. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  70798. var engine = scene.getEngine();
  70799. this._engine = engine;
  70800. this._maxSize = this._engine.getCaps().maxTextureSize;
  70801. this._scene.highlightLayers.push(this);
  70802. // Warn on stencil.
  70803. if (!this._engine.isStencilEnable) {
  70804. 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 }");
  70805. }
  70806. // Adapt options
  70807. this._options = options || {
  70808. mainTextureRatio: 0.5,
  70809. blurTextureSizeRatio: 0.5,
  70810. blurHorizontalSize: 1.0,
  70811. blurVerticalSize: 1.0,
  70812. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  70813. camera: null
  70814. };
  70815. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  70816. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  70817. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  70818. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  70819. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  70820. // VBO
  70821. var vertices = [];
  70822. vertices.push(1, 1);
  70823. vertices.push(-1, 1);
  70824. vertices.push(-1, -1);
  70825. vertices.push(1, -1);
  70826. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70827. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  70828. this._createIndexBuffer();
  70829. // Effect
  70830. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  70831. // Render target
  70832. this.setMainTextureSize();
  70833. // Create Textures and post processes
  70834. this.createTextureAndPostProcesses();
  70835. }
  70836. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  70837. /**
  70838. * Gets the horizontal size of the blur.
  70839. */
  70840. get: function () {
  70841. return this._horizontalBlurPostprocess.kernel;
  70842. },
  70843. /**
  70844. * Specifies the horizontal size of the blur.
  70845. */
  70846. set: function (value) {
  70847. this._horizontalBlurPostprocess.kernel = value;
  70848. },
  70849. enumerable: true,
  70850. configurable: true
  70851. });
  70852. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  70853. /**
  70854. * Gets the vertical size of the blur.
  70855. */
  70856. get: function () {
  70857. return this._verticalBlurPostprocess.kernel;
  70858. },
  70859. /**
  70860. * Specifies the vertical size of the blur.
  70861. */
  70862. set: function (value) {
  70863. this._verticalBlurPostprocess.kernel = value;
  70864. },
  70865. enumerable: true,
  70866. configurable: true
  70867. });
  70868. Object.defineProperty(HighlightLayer.prototype, "camera", {
  70869. /**
  70870. * Gets the camera attached to the layer.
  70871. */
  70872. get: function () {
  70873. return this._options.camera;
  70874. },
  70875. enumerable: true,
  70876. configurable: true
  70877. });
  70878. HighlightLayer.prototype._createIndexBuffer = function () {
  70879. var engine = this._scene.getEngine();
  70880. // Indices
  70881. var indices = [];
  70882. indices.push(0);
  70883. indices.push(1);
  70884. indices.push(2);
  70885. indices.push(0);
  70886. indices.push(2);
  70887. indices.push(3);
  70888. this._indexBuffer = engine.createIndexBuffer(indices);
  70889. };
  70890. HighlightLayer.prototype._rebuild = function () {
  70891. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70892. if (vb) {
  70893. vb._rebuild();
  70894. }
  70895. this._createIndexBuffer();
  70896. };
  70897. /**
  70898. * Creates the render target textures and post processes used in the highlight layer.
  70899. */
  70900. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  70901. var _this = this;
  70902. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  70903. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  70904. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  70905. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  70906. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  70907. width: this._mainTextureDesiredSize.width,
  70908. height: this._mainTextureDesiredSize.height
  70909. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  70910. this._mainTexture.activeCamera = this._options.camera;
  70911. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70912. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70913. this._mainTexture.anisotropicFilteringLevel = 1;
  70914. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70915. this._mainTexture.renderParticles = false;
  70916. this._mainTexture.renderList = null;
  70917. this._mainTexture.ignoreCameraViewport = true;
  70918. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  70919. width: blurTextureWidth,
  70920. height: blurTextureHeight
  70921. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  70922. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70923. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70924. this._blurTexture.anisotropicFilteringLevel = 16;
  70925. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  70926. this._blurTexture.renderParticles = false;
  70927. this._blurTexture.ignoreCameraViewport = true;
  70928. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  70929. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  70930. effect.setTexture("textureSampler", _this._mainTexture);
  70931. });
  70932. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  70933. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  70934. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  70935. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  70936. });
  70937. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  70938. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  70939. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  70940. });
  70941. }
  70942. else {
  70943. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  70944. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  70945. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  70946. });
  70947. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  70948. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  70949. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  70950. });
  70951. }
  70952. this._mainTexture.onAfterUnbindObservable.add(function () {
  70953. _this.onBeforeBlurObservable.notifyObservers(_this);
  70954. var internalTexture = _this._blurTexture.getInternalTexture();
  70955. if (internalTexture) {
  70956. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  70957. }
  70958. _this.onAfterBlurObservable.notifyObservers(_this);
  70959. });
  70960. // Custom render function
  70961. var renderSubMesh = function (subMesh) {
  70962. if (!_this._meshes) {
  70963. return;
  70964. }
  70965. var mesh = subMesh.getRenderingMesh();
  70966. var scene = _this._scene;
  70967. var engine = scene.getEngine();
  70968. // Culling
  70969. engine.setState(subMesh.getMaterial().backFaceCulling);
  70970. // Managing instances
  70971. var batch = mesh._getInstancesRenderList(subMesh._id);
  70972. if (batch.mustReturn) {
  70973. return;
  70974. }
  70975. // Excluded Mesh
  70976. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  70977. return;
  70978. }
  70979. ;
  70980. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  70981. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  70982. var material = subMesh.getMaterial();
  70983. var emissiveTexture = null;
  70984. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  70985. emissiveTexture = material.emissiveTexture;
  70986. }
  70987. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  70988. engine.enableEffect(_this._glowMapGenerationEffect);
  70989. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  70990. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  70991. if (highlightLayerMesh) {
  70992. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  70993. }
  70994. else {
  70995. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  70996. }
  70997. // Alpha test
  70998. if (material && material.needAlphaTesting()) {
  70999. var alphaTexture = material.getAlphaTestTexture();
  71000. if (alphaTexture) {
  71001. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  71002. var textureMatrix = alphaTexture.getTextureMatrix();
  71003. if (textureMatrix) {
  71004. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  71005. }
  71006. }
  71007. }
  71008. // Glow emissive only
  71009. if (emissiveTexture) {
  71010. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  71011. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  71012. }
  71013. // Bones
  71014. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71015. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71016. }
  71017. // Draw
  71018. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  71019. }
  71020. else {
  71021. // Need to reset refresh rate of the shadowMap
  71022. _this._mainTexture.resetRefreshCounter();
  71023. }
  71024. };
  71025. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71026. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  71027. var index;
  71028. var engine = _this._scene.getEngine();
  71029. if (depthOnlySubMeshes.length) {
  71030. engine.setColorWrite(false);
  71031. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71032. renderSubMesh(depthOnlySubMeshes.data[index]);
  71033. }
  71034. engine.setColorWrite(true);
  71035. }
  71036. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71037. renderSubMesh(opaqueSubMeshes.data[index]);
  71038. }
  71039. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71040. renderSubMesh(alphaTestSubMeshes.data[index]);
  71041. }
  71042. for (index = 0; index < transparentSubMeshes.length; index++) {
  71043. renderSubMesh(transparentSubMeshes.data[index]);
  71044. }
  71045. };
  71046. this._mainTexture.onClearObservable.add(function (engine) {
  71047. engine.clear(HighlightLayer.neutralColor, true, true, true);
  71048. });
  71049. };
  71050. /**
  71051. * Checks for the readiness of the element composing the layer.
  71052. * @param subMesh the mesh to check for
  71053. * @param useInstances specify wether or not to use instances to render the mesh
  71054. * @param emissiveTexture the associated emissive texture used to generate the glow
  71055. * @return true if ready otherwise, false
  71056. */
  71057. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  71058. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  71059. return false;
  71060. }
  71061. var defines = [];
  71062. var attribs = [BABYLON.VertexBuffer.PositionKind];
  71063. var mesh = subMesh.getMesh();
  71064. var material = subMesh.getMaterial();
  71065. var uv1 = false;
  71066. var uv2 = false;
  71067. // Alpha test
  71068. if (material && material.needAlphaTesting()) {
  71069. var alphaTexture = material.getAlphaTestTexture();
  71070. if (alphaTexture) {
  71071. defines.push("#define ALPHATEST");
  71072. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  71073. alphaTexture.coordinatesIndex === 1) {
  71074. defines.push("#define DIFFUSEUV2");
  71075. uv2 = true;
  71076. }
  71077. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71078. defines.push("#define DIFFUSEUV1");
  71079. uv1 = true;
  71080. }
  71081. }
  71082. }
  71083. // Emissive
  71084. if (emissiveTexture) {
  71085. defines.push("#define EMISSIVE");
  71086. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  71087. emissiveTexture.coordinatesIndex === 1) {
  71088. defines.push("#define EMISSIVEUV2");
  71089. uv2 = true;
  71090. }
  71091. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71092. defines.push("#define EMISSIVEUV1");
  71093. uv1 = true;
  71094. }
  71095. }
  71096. if (uv1) {
  71097. attribs.push(BABYLON.VertexBuffer.UVKind);
  71098. defines.push("#define UV1");
  71099. }
  71100. if (uv2) {
  71101. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71102. defines.push("#define UV2");
  71103. }
  71104. // Bones
  71105. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71106. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71107. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71108. if (mesh.numBoneInfluencers > 4) {
  71109. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  71110. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  71111. }
  71112. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71113. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  71114. }
  71115. else {
  71116. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71117. }
  71118. // Instances
  71119. if (useInstances) {
  71120. defines.push("#define INSTANCES");
  71121. attribs.push("world0");
  71122. attribs.push("world1");
  71123. attribs.push("world2");
  71124. attribs.push("world3");
  71125. }
  71126. // Get correct effect
  71127. var join = defines.join("\n");
  71128. if (this._cachedDefines !== join) {
  71129. this._cachedDefines = join;
  71130. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  71131. }
  71132. return this._glowMapGenerationEffect.isReady();
  71133. };
  71134. /**
  71135. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  71136. */
  71137. HighlightLayer.prototype.render = function () {
  71138. var currentEffect = this._glowMapMergeEffect;
  71139. // Check
  71140. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  71141. return;
  71142. var engine = this._scene.getEngine();
  71143. this.onBeforeComposeObservable.notifyObservers(this);
  71144. // Render
  71145. engine.enableEffect(currentEffect);
  71146. engine.setState(false);
  71147. // Cache
  71148. var previousStencilBuffer = engine.getStencilBuffer();
  71149. var previousStencilFunction = engine.getStencilFunction();
  71150. var previousStencilMask = engine.getStencilMask();
  71151. var previousStencilOperationPass = engine.getStencilOperationPass();
  71152. var previousStencilOperationFail = engine.getStencilOperationFail();
  71153. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  71154. var previousAlphaMode = engine.getAlphaMode();
  71155. // Texture
  71156. currentEffect.setTexture("textureSampler", this._blurTexture);
  71157. // VBOs
  71158. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  71159. // Stencil operations
  71160. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  71161. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  71162. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  71163. // Draw order
  71164. engine.setAlphaMode(this._options.alphaBlendingMode);
  71165. engine.setStencilMask(0x00);
  71166. engine.setStencilBuffer(true);
  71167. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  71168. if (this.outerGlow) {
  71169. currentEffect.setFloat("offset", 0);
  71170. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  71171. engine.draw(true, 0, 6);
  71172. }
  71173. if (this.innerGlow) {
  71174. currentEffect.setFloat("offset", 1);
  71175. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  71176. engine.draw(true, 0, 6);
  71177. }
  71178. // Restore Cache
  71179. engine.setStencilFunction(previousStencilFunction);
  71180. engine.setStencilMask(previousStencilMask);
  71181. engine.setAlphaMode(previousAlphaMode);
  71182. engine.setStencilBuffer(previousStencilBuffer);
  71183. engine.setStencilOperationPass(previousStencilOperationPass);
  71184. engine.setStencilOperationFail(previousStencilOperationFail);
  71185. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  71186. engine._stencilState.reset();
  71187. this.onAfterComposeObservable.notifyObservers(this);
  71188. // Handle size changes.
  71189. var size = this._mainTexture.getSize();
  71190. this.setMainTextureSize();
  71191. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  71192. // Recreate RTT and post processes on size change.
  71193. this.onSizeChangedObservable.notifyObservers(this);
  71194. this.disposeTextureAndPostProcesses();
  71195. this.createTextureAndPostProcesses();
  71196. }
  71197. };
  71198. /**
  71199. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  71200. * @param mesh The mesh to exclude from the highlight layer
  71201. */
  71202. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  71203. if (!this._excludedMeshes) {
  71204. return;
  71205. }
  71206. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  71207. if (!meshExcluded) {
  71208. this._excludedMeshes[mesh.uniqueId] = {
  71209. mesh: mesh,
  71210. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  71211. mesh.getEngine().setStencilBuffer(false);
  71212. }),
  71213. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  71214. mesh.getEngine().setStencilBuffer(true);
  71215. }),
  71216. };
  71217. }
  71218. };
  71219. /**
  71220. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  71221. * @param mesh The mesh to highlight
  71222. */
  71223. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  71224. if (!this._excludedMeshes) {
  71225. return;
  71226. }
  71227. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  71228. if (meshExcluded) {
  71229. if (meshExcluded.beforeRender) {
  71230. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  71231. }
  71232. if (meshExcluded.afterRender) {
  71233. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  71234. }
  71235. }
  71236. this._excludedMeshes[mesh.uniqueId] = null;
  71237. };
  71238. /**
  71239. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  71240. * @param mesh The mesh to highlight
  71241. * @param color The color of the highlight
  71242. * @param glowEmissiveOnly Extract the glow from the emissive texture
  71243. */
  71244. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  71245. var _this = this;
  71246. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  71247. if (!this._meshes) {
  71248. return;
  71249. }
  71250. var meshHighlight = this._meshes[mesh.uniqueId];
  71251. if (meshHighlight) {
  71252. meshHighlight.color = color;
  71253. }
  71254. else {
  71255. this._meshes[mesh.uniqueId] = {
  71256. mesh: mesh,
  71257. color: color,
  71258. // Lambda required for capture due to Observable this context
  71259. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  71260. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  71261. _this.defaultStencilReference(mesh);
  71262. }
  71263. else {
  71264. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  71265. }
  71266. }),
  71267. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  71268. glowEmissiveOnly: glowEmissiveOnly
  71269. };
  71270. }
  71271. this._shouldRender = true;
  71272. };
  71273. /**
  71274. * Remove a mesh from the highlight layer in order to make it stop glowing.
  71275. * @param mesh The mesh to highlight
  71276. */
  71277. HighlightLayer.prototype.removeMesh = function (mesh) {
  71278. if (!this._meshes) {
  71279. return;
  71280. }
  71281. var meshHighlight = this._meshes[mesh.uniqueId];
  71282. if (meshHighlight) {
  71283. if (meshHighlight.observerHighlight) {
  71284. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  71285. }
  71286. if (meshHighlight.observerDefault) {
  71287. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  71288. }
  71289. }
  71290. this._meshes[mesh.uniqueId] = null;
  71291. this._shouldRender = false;
  71292. for (var meshHighlightToCheck in this._meshes) {
  71293. if (meshHighlightToCheck) {
  71294. this._shouldRender = true;
  71295. break;
  71296. }
  71297. }
  71298. };
  71299. /**
  71300. * Returns true if the layer contains information to display, otherwise false.
  71301. */
  71302. HighlightLayer.prototype.shouldRender = function () {
  71303. return this.isEnabled && this._shouldRender;
  71304. };
  71305. /**
  71306. * Sets the main texture desired size which is the closest power of two
  71307. * of the engine canvas size.
  71308. */
  71309. HighlightLayer.prototype.setMainTextureSize = function () {
  71310. if (this._options.mainTextureFixedSize) {
  71311. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  71312. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  71313. }
  71314. else {
  71315. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  71316. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  71317. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  71318. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  71319. }
  71320. };
  71321. /**
  71322. * Force the stencil to the normal expected value for none glowing parts
  71323. */
  71324. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  71325. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  71326. };
  71327. /**
  71328. * Dispose only the render target textures and post process.
  71329. */
  71330. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  71331. this._blurTexture.dispose();
  71332. this._mainTexture.dispose();
  71333. this._downSamplePostprocess.dispose();
  71334. this._horizontalBlurPostprocess.dispose();
  71335. this._verticalBlurPostprocess.dispose();
  71336. };
  71337. /**
  71338. * Dispose the highlight layer and free resources.
  71339. */
  71340. HighlightLayer.prototype.dispose = function () {
  71341. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71342. if (vertexBuffer) {
  71343. vertexBuffer.dispose();
  71344. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  71345. }
  71346. if (this._indexBuffer) {
  71347. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  71348. this._indexBuffer = null;
  71349. }
  71350. // Clean textures and post processes
  71351. this.disposeTextureAndPostProcesses();
  71352. if (this._meshes) {
  71353. // Clean mesh references
  71354. for (var id in this._meshes) {
  71355. var meshHighlight = this._meshes[id];
  71356. if (meshHighlight && meshHighlight.mesh) {
  71357. if (meshHighlight.observerHighlight) {
  71358. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  71359. }
  71360. if (meshHighlight.observerDefault) {
  71361. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  71362. }
  71363. }
  71364. }
  71365. this._meshes = null;
  71366. }
  71367. if (this._excludedMeshes) {
  71368. for (var id in this._excludedMeshes) {
  71369. var meshHighlight = this._excludedMeshes[id];
  71370. if (meshHighlight) {
  71371. if (meshHighlight.beforeRender) {
  71372. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  71373. }
  71374. if (meshHighlight.afterRender) {
  71375. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  71376. }
  71377. }
  71378. }
  71379. this._excludedMeshes = null;
  71380. }
  71381. // Remove from scene
  71382. var index = this._scene.highlightLayers.indexOf(this, 0);
  71383. if (index > -1) {
  71384. this._scene.highlightLayers.splice(index, 1);
  71385. }
  71386. // Callback
  71387. this.onDisposeObservable.notifyObservers(this);
  71388. this.onDisposeObservable.clear();
  71389. this.onBeforeRenderMainTextureObservable.clear();
  71390. this.onBeforeBlurObservable.clear();
  71391. this.onBeforeComposeObservable.clear();
  71392. this.onAfterComposeObservable.clear();
  71393. this.onSizeChangedObservable.clear();
  71394. };
  71395. /**
  71396. * The neutral color used during the preparation of the glow effect.
  71397. * This is black by default as the blend operation is a blend operation.
  71398. */
  71399. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  71400. /**
  71401. * Stencil value used for glowing meshes.
  71402. */
  71403. HighlightLayer.glowingMeshStencilReference = 0x02;
  71404. /**
  71405. * Stencil value used for the other meshes in the scene.
  71406. */
  71407. HighlightLayer.normalMeshStencilReference = 0x01;
  71408. return HighlightLayer;
  71409. }());
  71410. BABYLON.HighlightLayer = HighlightLayer;
  71411. })(BABYLON || (BABYLON = {}));
  71412. //# sourceMappingURL=babylon.highlightlayer.js.map
  71413. var BABYLON;
  71414. (function (BABYLON) {
  71415. var AssetTaskState;
  71416. (function (AssetTaskState) {
  71417. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  71418. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  71419. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  71420. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  71421. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  71422. var AbstractAssetTask = /** @class */ (function () {
  71423. function AbstractAssetTask() {
  71424. this.isCompleted = false;
  71425. this.taskState = AssetTaskState.INIT;
  71426. }
  71427. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  71428. var _this = this;
  71429. this.taskState = AssetTaskState.RUNNING;
  71430. this.runTask(scene, function () {
  71431. _this.onDoneCallback(onSuccess, onError);
  71432. }, function (msg, exception) {
  71433. _this.onErrorCallback(onError, msg, exception);
  71434. });
  71435. };
  71436. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  71437. throw new Error("runTask is not implemented");
  71438. };
  71439. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  71440. this.taskState = AssetTaskState.ERROR;
  71441. this.errorObject = {
  71442. message: message,
  71443. exception: exception
  71444. };
  71445. if (this.onError) {
  71446. this.onError(this, message, exception);
  71447. }
  71448. onError();
  71449. };
  71450. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  71451. try {
  71452. this.taskState = AssetTaskState.DONE;
  71453. this.isCompleted = true;
  71454. if (this.onSuccess) {
  71455. this.onSuccess(this);
  71456. }
  71457. onSuccess();
  71458. }
  71459. catch (e) {
  71460. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  71461. }
  71462. };
  71463. return AbstractAssetTask;
  71464. }());
  71465. BABYLON.AbstractAssetTask = AbstractAssetTask;
  71466. var MeshAssetTask = /** @class */ (function (_super) {
  71467. __extends(MeshAssetTask, _super);
  71468. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  71469. var _this = _super.call(this) || this;
  71470. _this.name = name;
  71471. _this.meshesNames = meshesNames;
  71472. _this.rootUrl = rootUrl;
  71473. _this.sceneFilename = sceneFilename;
  71474. return _this;
  71475. }
  71476. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  71477. var _this = this;
  71478. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  71479. _this.loadedMeshes = meshes;
  71480. _this.loadedParticleSystems = particleSystems;
  71481. _this.loadedSkeletons = skeletons;
  71482. onSuccess();
  71483. }, null, function (scene, message, exception) {
  71484. onError(message, exception);
  71485. });
  71486. };
  71487. return MeshAssetTask;
  71488. }(AbstractAssetTask));
  71489. BABYLON.MeshAssetTask = MeshAssetTask;
  71490. var TextFileAssetTask = /** @class */ (function (_super) {
  71491. __extends(TextFileAssetTask, _super);
  71492. function TextFileAssetTask(name, url) {
  71493. var _this = _super.call(this) || this;
  71494. _this.name = name;
  71495. _this.url = url;
  71496. return _this;
  71497. }
  71498. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  71499. var _this = this;
  71500. BABYLON.Tools.LoadFile(this.url, function (data) {
  71501. _this.text = data;
  71502. onSuccess();
  71503. }, undefined, scene.database, false, function (request, exception) {
  71504. if (request) {
  71505. onError(request.status + " " + request.statusText, exception);
  71506. }
  71507. });
  71508. };
  71509. return TextFileAssetTask;
  71510. }(AbstractAssetTask));
  71511. BABYLON.TextFileAssetTask = TextFileAssetTask;
  71512. var BinaryFileAssetTask = /** @class */ (function (_super) {
  71513. __extends(BinaryFileAssetTask, _super);
  71514. function BinaryFileAssetTask(name, url) {
  71515. var _this = _super.call(this) || this;
  71516. _this.name = name;
  71517. _this.url = url;
  71518. return _this;
  71519. }
  71520. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  71521. var _this = this;
  71522. BABYLON.Tools.LoadFile(this.url, function (data) {
  71523. _this.data = data;
  71524. onSuccess();
  71525. }, undefined, scene.database, true, function (request, exception) {
  71526. if (request) {
  71527. onError(request.status + " " + request.statusText, exception);
  71528. }
  71529. });
  71530. };
  71531. return BinaryFileAssetTask;
  71532. }(AbstractAssetTask));
  71533. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  71534. var ImageAssetTask = /** @class */ (function (_super) {
  71535. __extends(ImageAssetTask, _super);
  71536. function ImageAssetTask(name, url) {
  71537. var _this = _super.call(this) || this;
  71538. _this.name = name;
  71539. _this.url = url;
  71540. return _this;
  71541. }
  71542. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  71543. var _this = this;
  71544. var img = new Image();
  71545. BABYLON.Tools.SetCorsBehavior(this.url, img);
  71546. img.onload = function () {
  71547. _this.image = img;
  71548. onSuccess();
  71549. };
  71550. img.onerror = function (err) {
  71551. onError("Error loading image", err);
  71552. };
  71553. img.src = this.url;
  71554. };
  71555. return ImageAssetTask;
  71556. }(AbstractAssetTask));
  71557. BABYLON.ImageAssetTask = ImageAssetTask;
  71558. var TextureAssetTask = /** @class */ (function (_super) {
  71559. __extends(TextureAssetTask, _super);
  71560. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  71561. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71562. var _this = _super.call(this) || this;
  71563. _this.name = name;
  71564. _this.url = url;
  71565. _this.noMipmap = noMipmap;
  71566. _this.invertY = invertY;
  71567. _this.samplingMode = samplingMode;
  71568. return _this;
  71569. }
  71570. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  71571. var onload = function () {
  71572. onSuccess();
  71573. };
  71574. var onerror = function (msg, exception) {
  71575. onError(msg, exception);
  71576. };
  71577. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  71578. };
  71579. return TextureAssetTask;
  71580. }(AbstractAssetTask));
  71581. BABYLON.TextureAssetTask = TextureAssetTask;
  71582. var CubeTextureAssetTask = /** @class */ (function (_super) {
  71583. __extends(CubeTextureAssetTask, _super);
  71584. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  71585. var _this = _super.call(this) || this;
  71586. _this.name = name;
  71587. _this.url = url;
  71588. _this.extensions = extensions;
  71589. _this.noMipmap = noMipmap;
  71590. _this.files = files;
  71591. return _this;
  71592. }
  71593. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  71594. var onload = function () {
  71595. onSuccess();
  71596. };
  71597. var onerror = function (msg, exception) {
  71598. onError(msg, exception);
  71599. };
  71600. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  71601. };
  71602. return CubeTextureAssetTask;
  71603. }(AbstractAssetTask));
  71604. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  71605. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  71606. __extends(HDRCubeTextureAssetTask, _super);
  71607. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  71608. if (noMipmap === void 0) { noMipmap = false; }
  71609. if (generateHarmonics === void 0) { generateHarmonics = true; }
  71610. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  71611. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  71612. var _this = _super.call(this) || this;
  71613. _this.name = name;
  71614. _this.url = url;
  71615. _this.size = size;
  71616. _this.noMipmap = noMipmap;
  71617. _this.generateHarmonics = generateHarmonics;
  71618. _this.useInGammaSpace = useInGammaSpace;
  71619. _this.usePMREMGenerator = usePMREMGenerator;
  71620. return _this;
  71621. }
  71622. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  71623. var onload = function () {
  71624. onSuccess();
  71625. };
  71626. var onerror = function (message, exception) {
  71627. onError(message, exception);
  71628. };
  71629. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  71630. };
  71631. return HDRCubeTextureAssetTask;
  71632. }(AbstractAssetTask));
  71633. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  71634. var AssetsManager = /** @class */ (function () {
  71635. function AssetsManager(scene) {
  71636. this.tasks = new Array();
  71637. this.waitingTasksCount = 0;
  71638. //Observables
  71639. this.onTaskSuccessObservable = new BABYLON.Observable();
  71640. this.onTaskErrorObservable = new BABYLON.Observable();
  71641. this.onTasksDoneObservable = new BABYLON.Observable();
  71642. this.useDefaultLoadingScreen = true;
  71643. this._scene = scene;
  71644. }
  71645. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  71646. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  71647. this.tasks.push(task);
  71648. return task;
  71649. };
  71650. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  71651. var task = new TextFileAssetTask(taskName, url);
  71652. this.tasks.push(task);
  71653. return task;
  71654. };
  71655. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  71656. var task = new BinaryFileAssetTask(taskName, url);
  71657. this.tasks.push(task);
  71658. return task;
  71659. };
  71660. AssetsManager.prototype.addImageTask = function (taskName, url) {
  71661. var task = new ImageAssetTask(taskName, url);
  71662. this.tasks.push(task);
  71663. return task;
  71664. };
  71665. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  71666. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71667. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  71668. this.tasks.push(task);
  71669. return task;
  71670. };
  71671. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  71672. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  71673. this.tasks.push(task);
  71674. return task;
  71675. };
  71676. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  71677. if (noMipmap === void 0) { noMipmap = false; }
  71678. if (generateHarmonics === void 0) { generateHarmonics = true; }
  71679. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  71680. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  71681. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  71682. this.tasks.push(task);
  71683. return task;
  71684. };
  71685. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  71686. this.waitingTasksCount--;
  71687. if (this.waitingTasksCount === 0) {
  71688. try {
  71689. if (this.onFinish) {
  71690. this.onFinish(this.tasks);
  71691. }
  71692. this.onTasksDoneObservable.notifyObservers(this.tasks);
  71693. }
  71694. catch (e) {
  71695. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  71696. console.log(e);
  71697. }
  71698. this._scene.getEngine().hideLoadingUI();
  71699. }
  71700. };
  71701. AssetsManager.prototype._runTask = function (task) {
  71702. var _this = this;
  71703. var done = function () {
  71704. try {
  71705. if (_this.onTaskSuccess) {
  71706. _this.onTaskSuccess(task);
  71707. }
  71708. _this.onTaskSuccessObservable.notifyObservers(task);
  71709. _this._decreaseWaitingTasksCount();
  71710. }
  71711. catch (e) {
  71712. error("Error executing task success callbacks", e);
  71713. }
  71714. };
  71715. var error = function (message, exception) {
  71716. task.errorObject = task.errorObject || {
  71717. message: message,
  71718. exception: exception
  71719. };
  71720. if (_this.onTaskError) {
  71721. _this.onTaskError(task);
  71722. }
  71723. _this.onTaskErrorObservable.notifyObservers(task);
  71724. _this._decreaseWaitingTasksCount();
  71725. };
  71726. task.run(this._scene, done, error);
  71727. };
  71728. AssetsManager.prototype.reset = function () {
  71729. this.tasks = new Array();
  71730. return this;
  71731. };
  71732. AssetsManager.prototype.load = function () {
  71733. this.waitingTasksCount = this.tasks.length;
  71734. if (this.waitingTasksCount === 0) {
  71735. if (this.onFinish) {
  71736. this.onFinish(this.tasks);
  71737. }
  71738. this.onTasksDoneObservable.notifyObservers(this.tasks);
  71739. return this;
  71740. }
  71741. if (this.useDefaultLoadingScreen) {
  71742. this._scene.getEngine().displayLoadingUI();
  71743. }
  71744. for (var index = 0; index < this.tasks.length; index++) {
  71745. var task = this.tasks[index];
  71746. this._runTask(task);
  71747. }
  71748. return this;
  71749. };
  71750. return AssetsManager;
  71751. }());
  71752. BABYLON.AssetsManager = AssetsManager;
  71753. })(BABYLON || (BABYLON = {}));
  71754. //# sourceMappingURL=babylon.assetsManager.js.map
  71755. var BABYLON;
  71756. (function (BABYLON) {
  71757. var serializedGeometries = [];
  71758. var serializeGeometry = function (geometry, serializationGeometries) {
  71759. if (serializedGeometries[geometry.id]) {
  71760. return;
  71761. }
  71762. if (geometry.doNotSerialize) {
  71763. return;
  71764. }
  71765. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  71766. serializationGeometries.boxes.push(geometry.serialize());
  71767. }
  71768. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  71769. serializationGeometries.spheres.push(geometry.serialize());
  71770. }
  71771. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  71772. serializationGeometries.cylinders.push(geometry.serialize());
  71773. }
  71774. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  71775. serializationGeometries.toruses.push(geometry.serialize());
  71776. }
  71777. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  71778. serializationGeometries.grounds.push(geometry.serialize());
  71779. }
  71780. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  71781. serializationGeometries.planes.push(geometry.serialize());
  71782. }
  71783. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  71784. serializationGeometries.torusKnots.push(geometry.serialize());
  71785. }
  71786. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  71787. throw new Error("Unknown primitive type");
  71788. }
  71789. else {
  71790. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  71791. }
  71792. serializedGeometries[geometry.id] = true;
  71793. };
  71794. var serializeMesh = function (mesh, serializationScene) {
  71795. var serializationObject = {};
  71796. // Geometry
  71797. var geometry = mesh._geometry;
  71798. if (geometry) {
  71799. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  71800. // 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
  71801. serializeGeometry(geometry, serializationScene.geometries);
  71802. }
  71803. }
  71804. // Custom
  71805. if (mesh.serialize) {
  71806. mesh.serialize(serializationObject);
  71807. }
  71808. return serializationObject;
  71809. };
  71810. var finalizeSingleMesh = function (mesh, serializationObject) {
  71811. //only works if the mesh is already loaded
  71812. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  71813. //serialize material
  71814. if (mesh.material) {
  71815. if (mesh.material instanceof BABYLON.StandardMaterial) {
  71816. serializationObject.materials = serializationObject.materials || [];
  71817. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  71818. serializationObject.materials.push(mesh.material.serialize());
  71819. }
  71820. }
  71821. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  71822. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  71823. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  71824. serializationObject.multiMaterials.push(mesh.material.serialize());
  71825. }
  71826. }
  71827. }
  71828. //serialize geometry
  71829. var geometry = mesh._geometry;
  71830. if (geometry) {
  71831. if (!serializationObject.geometries) {
  71832. serializationObject.geometries = {};
  71833. serializationObject.geometries.boxes = [];
  71834. serializationObject.geometries.spheres = [];
  71835. serializationObject.geometries.cylinders = [];
  71836. serializationObject.geometries.toruses = [];
  71837. serializationObject.geometries.grounds = [];
  71838. serializationObject.geometries.planes = [];
  71839. serializationObject.geometries.torusKnots = [];
  71840. serializationObject.geometries.vertexData = [];
  71841. }
  71842. serializeGeometry(geometry, serializationObject.geometries);
  71843. }
  71844. // Skeletons
  71845. if (mesh.skeleton) {
  71846. serializationObject.skeletons = serializationObject.skeletons || [];
  71847. serializationObject.skeletons.push(mesh.skeleton.serialize());
  71848. }
  71849. //serialize the actual mesh
  71850. serializationObject.meshes = serializationObject.meshes || [];
  71851. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  71852. }
  71853. };
  71854. var SceneSerializer = /** @class */ (function () {
  71855. function SceneSerializer() {
  71856. }
  71857. SceneSerializer.ClearCache = function () {
  71858. serializedGeometries = [];
  71859. };
  71860. SceneSerializer.Serialize = function (scene) {
  71861. var serializationObject = {};
  71862. SceneSerializer.ClearCache();
  71863. // Scene
  71864. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  71865. serializationObject.autoClear = scene.autoClear;
  71866. serializationObject.clearColor = scene.clearColor.asArray();
  71867. serializationObject.ambientColor = scene.ambientColor.asArray();
  71868. serializationObject.gravity = scene.gravity.asArray();
  71869. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  71870. serializationObject.workerCollisions = scene.workerCollisions;
  71871. // Fog
  71872. if (scene.fogMode && scene.fogMode !== 0) {
  71873. serializationObject.fogMode = scene.fogMode;
  71874. serializationObject.fogColor = scene.fogColor.asArray();
  71875. serializationObject.fogStart = scene.fogStart;
  71876. serializationObject.fogEnd = scene.fogEnd;
  71877. serializationObject.fogDensity = scene.fogDensity;
  71878. }
  71879. //Physics
  71880. if (scene.isPhysicsEnabled()) {
  71881. var physicEngine = scene.getPhysicsEngine();
  71882. if (physicEngine) {
  71883. serializationObject.physicsEnabled = true;
  71884. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  71885. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  71886. }
  71887. }
  71888. // Metadata
  71889. if (scene.metadata) {
  71890. serializationObject.metadata = scene.metadata;
  71891. }
  71892. // Morph targets
  71893. serializationObject.morphTargetManagers = [];
  71894. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  71895. var abstractMesh = _a[_i];
  71896. var manager = abstractMesh.morphTargetManager;
  71897. if (manager) {
  71898. serializationObject.morphTargetManagers.push(manager.serialize());
  71899. }
  71900. }
  71901. // Lights
  71902. serializationObject.lights = [];
  71903. var index;
  71904. var light;
  71905. for (index = 0; index < scene.lights.length; index++) {
  71906. light = scene.lights[index];
  71907. if (!light.doNotSerialize) {
  71908. serializationObject.lights.push(light.serialize());
  71909. }
  71910. }
  71911. // Cameras
  71912. serializationObject.cameras = [];
  71913. for (index = 0; index < scene.cameras.length; index++) {
  71914. var camera = scene.cameras[index];
  71915. if (!camera.doNotSerialize) {
  71916. serializationObject.cameras.push(camera.serialize());
  71917. }
  71918. }
  71919. if (scene.activeCamera) {
  71920. serializationObject.activeCameraID = scene.activeCamera.id;
  71921. }
  71922. // Animations
  71923. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  71924. // Materials
  71925. serializationObject.materials = [];
  71926. serializationObject.multiMaterials = [];
  71927. var material;
  71928. for (index = 0; index < scene.materials.length; index++) {
  71929. material = scene.materials[index];
  71930. if (!material.doNotSerialize) {
  71931. serializationObject.materials.push(material.serialize());
  71932. }
  71933. }
  71934. // MultiMaterials
  71935. serializationObject.multiMaterials = [];
  71936. for (index = 0; index < scene.multiMaterials.length; index++) {
  71937. var multiMaterial = scene.multiMaterials[index];
  71938. serializationObject.multiMaterials.push(multiMaterial.serialize());
  71939. }
  71940. // Skeletons
  71941. serializationObject.skeletons = [];
  71942. for (index = 0; index < scene.skeletons.length; index++) {
  71943. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  71944. }
  71945. // Geometries
  71946. serializationObject.geometries = {};
  71947. serializationObject.geometries.boxes = [];
  71948. serializationObject.geometries.spheres = [];
  71949. serializationObject.geometries.cylinders = [];
  71950. serializationObject.geometries.toruses = [];
  71951. serializationObject.geometries.grounds = [];
  71952. serializationObject.geometries.planes = [];
  71953. serializationObject.geometries.torusKnots = [];
  71954. serializationObject.geometries.vertexData = [];
  71955. serializedGeometries = [];
  71956. var geometries = scene.getGeometries();
  71957. for (index = 0; index < geometries.length; index++) {
  71958. var geometry = geometries[index];
  71959. if (geometry.isReady()) {
  71960. serializeGeometry(geometry, serializationObject.geometries);
  71961. }
  71962. }
  71963. // Meshes
  71964. serializationObject.meshes = [];
  71965. for (index = 0; index < scene.meshes.length; index++) {
  71966. var abstractMesh = scene.meshes[index];
  71967. if (abstractMesh instanceof BABYLON.Mesh) {
  71968. var mesh = abstractMesh;
  71969. if (!mesh.doNotSerialize) {
  71970. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  71971. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  71972. }
  71973. }
  71974. }
  71975. }
  71976. // Particles Systems
  71977. serializationObject.particleSystems = [];
  71978. for (index = 0; index < scene.particleSystems.length; index++) {
  71979. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  71980. }
  71981. // Lens flares
  71982. serializationObject.lensFlareSystems = [];
  71983. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  71984. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  71985. }
  71986. // Shadows
  71987. serializationObject.shadowGenerators = [];
  71988. for (index = 0; index < scene.lights.length; index++) {
  71989. light = scene.lights[index];
  71990. var shadowGenerator = light.getShadowGenerator();
  71991. if (shadowGenerator) {
  71992. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  71993. }
  71994. }
  71995. // Action Manager
  71996. if (scene.actionManager) {
  71997. serializationObject.actions = scene.actionManager.serialize("scene");
  71998. }
  71999. // Audio
  72000. serializationObject.sounds = [];
  72001. for (index = 0; index < scene.soundTracks.length; index++) {
  72002. var soundtrack = scene.soundTracks[index];
  72003. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  72004. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  72005. }
  72006. }
  72007. return serializationObject;
  72008. };
  72009. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  72010. if (withParents === void 0) { withParents = false; }
  72011. if (withChildren === void 0) { withChildren = false; }
  72012. var serializationObject = {};
  72013. SceneSerializer.ClearCache();
  72014. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  72015. if (withParents || withChildren) {
  72016. //deliberate for loop! not for each, appended should be processed as well.
  72017. for (var i = 0; i < toSerialize.length; ++i) {
  72018. if (withChildren) {
  72019. toSerialize[i].getDescendants().forEach(function (node) {
  72020. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  72021. toSerialize.push(node);
  72022. }
  72023. });
  72024. }
  72025. //make sure the array doesn't contain the object already
  72026. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  72027. toSerialize.push(toSerialize[i].parent);
  72028. }
  72029. }
  72030. }
  72031. toSerialize.forEach(function (mesh) {
  72032. finalizeSingleMesh(mesh, serializationObject);
  72033. });
  72034. return serializationObject;
  72035. };
  72036. return SceneSerializer;
  72037. }());
  72038. BABYLON.SceneSerializer = SceneSerializer;
  72039. })(BABYLON || (BABYLON = {}));
  72040. //# sourceMappingURL=babylon.sceneSerializer.js.map
  72041. var BABYLON;
  72042. (function (BABYLON) {
  72043. var ReflectionProbe = /** @class */ (function () {
  72044. function ReflectionProbe(name, size, scene, generateMipMaps) {
  72045. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72046. var _this = this;
  72047. this.name = name;
  72048. this._viewMatrix = BABYLON.Matrix.Identity();
  72049. this._target = BABYLON.Vector3.Zero();
  72050. this._add = BABYLON.Vector3.Zero();
  72051. this.invertYAxis = false;
  72052. this.position = BABYLON.Vector3.Zero();
  72053. this._scene = scene;
  72054. this._scene.reflectionProbes.push(this);
  72055. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  72056. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  72057. switch (faceIndex) {
  72058. case 0:
  72059. _this._add.copyFromFloats(1, 0, 0);
  72060. break;
  72061. case 1:
  72062. _this._add.copyFromFloats(-1, 0, 0);
  72063. break;
  72064. case 2:
  72065. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  72066. break;
  72067. case 3:
  72068. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  72069. break;
  72070. case 4:
  72071. _this._add.copyFromFloats(0, 0, 1);
  72072. break;
  72073. case 5:
  72074. _this._add.copyFromFloats(0, 0, -1);
  72075. break;
  72076. }
  72077. if (_this._attachedMesh) {
  72078. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  72079. }
  72080. _this.position.addToRef(_this._add, _this._target);
  72081. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  72082. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  72083. });
  72084. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  72085. scene.updateTransformMatrix(true);
  72086. });
  72087. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  72088. }
  72089. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  72090. get: function () {
  72091. return this._renderTargetTexture.samples;
  72092. },
  72093. set: function (value) {
  72094. this._renderTargetTexture.samples = value;
  72095. },
  72096. enumerable: true,
  72097. configurable: true
  72098. });
  72099. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  72100. get: function () {
  72101. return this._renderTargetTexture.refreshRate;
  72102. },
  72103. set: function (value) {
  72104. this._renderTargetTexture.refreshRate = value;
  72105. },
  72106. enumerable: true,
  72107. configurable: true
  72108. });
  72109. ReflectionProbe.prototype.getScene = function () {
  72110. return this._scene;
  72111. };
  72112. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  72113. get: function () {
  72114. return this._renderTargetTexture;
  72115. },
  72116. enumerable: true,
  72117. configurable: true
  72118. });
  72119. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  72120. get: function () {
  72121. return this._renderTargetTexture.renderList;
  72122. },
  72123. enumerable: true,
  72124. configurable: true
  72125. });
  72126. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  72127. this._attachedMesh = mesh;
  72128. };
  72129. /**
  72130. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  72131. *
  72132. * @param renderingGroupId The rendering group id corresponding to its index
  72133. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  72134. */
  72135. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  72136. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  72137. };
  72138. ReflectionProbe.prototype.dispose = function () {
  72139. var index = this._scene.reflectionProbes.indexOf(this);
  72140. if (index !== -1) {
  72141. // Remove from the scene if found
  72142. this._scene.reflectionProbes.splice(index, 1);
  72143. }
  72144. if (this._renderTargetTexture) {
  72145. this._renderTargetTexture.dispose();
  72146. this._renderTargetTexture = null;
  72147. }
  72148. };
  72149. return ReflectionProbe;
  72150. }());
  72151. BABYLON.ReflectionProbe = ReflectionProbe;
  72152. })(BABYLON || (BABYLON = {}));
  72153. //# sourceMappingURL=babylon.reflectionProbe.js.map
  72154. var BABYLON;
  72155. (function (BABYLON) {
  72156. var Layer = /** @class */ (function () {
  72157. function Layer(name, imgUrl, scene, isBackground, color) {
  72158. this.name = name;
  72159. this.scale = new BABYLON.Vector2(1, 1);
  72160. this.offset = new BABYLON.Vector2(0, 0);
  72161. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  72162. this.layerMask = 0x0FFFFFFF;
  72163. this._vertexBuffers = {};
  72164. // Events
  72165. /**
  72166. * An event triggered when the layer is disposed.
  72167. * @type {BABYLON.Observable}
  72168. */
  72169. this.onDisposeObservable = new BABYLON.Observable();
  72170. /**
  72171. * An event triggered before rendering the scene
  72172. * @type {BABYLON.Observable}
  72173. */
  72174. this.onBeforeRenderObservable = new BABYLON.Observable();
  72175. /**
  72176. * An event triggered after rendering the scene
  72177. * @type {BABYLON.Observable}
  72178. */
  72179. this.onAfterRenderObservable = new BABYLON.Observable();
  72180. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  72181. this.isBackground = isBackground === undefined ? true : isBackground;
  72182. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  72183. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  72184. this._scene.layers.push(this);
  72185. var engine = this._scene.getEngine();
  72186. // VBO
  72187. var vertices = [];
  72188. vertices.push(1, 1);
  72189. vertices.push(-1, 1);
  72190. vertices.push(-1, -1);
  72191. vertices.push(1, -1);
  72192. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  72193. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  72194. this._createIndexBuffer();
  72195. // Effects
  72196. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  72197. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  72198. }
  72199. Object.defineProperty(Layer.prototype, "onDispose", {
  72200. set: function (callback) {
  72201. if (this._onDisposeObserver) {
  72202. this.onDisposeObservable.remove(this._onDisposeObserver);
  72203. }
  72204. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  72205. },
  72206. enumerable: true,
  72207. configurable: true
  72208. });
  72209. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  72210. set: function (callback) {
  72211. if (this._onBeforeRenderObserver) {
  72212. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  72213. }
  72214. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  72215. },
  72216. enumerable: true,
  72217. configurable: true
  72218. });
  72219. Object.defineProperty(Layer.prototype, "onAfterRender", {
  72220. set: function (callback) {
  72221. if (this._onAfterRenderObserver) {
  72222. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  72223. }
  72224. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  72225. },
  72226. enumerable: true,
  72227. configurable: true
  72228. });
  72229. Layer.prototype._createIndexBuffer = function () {
  72230. var engine = this._scene.getEngine();
  72231. // Indices
  72232. var indices = [];
  72233. indices.push(0);
  72234. indices.push(1);
  72235. indices.push(2);
  72236. indices.push(0);
  72237. indices.push(2);
  72238. indices.push(3);
  72239. this._indexBuffer = engine.createIndexBuffer(indices);
  72240. };
  72241. Layer.prototype._rebuild = function () {
  72242. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72243. if (vb) {
  72244. vb._rebuild();
  72245. }
  72246. this._createIndexBuffer();
  72247. };
  72248. Layer.prototype.render = function () {
  72249. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  72250. // Check
  72251. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  72252. return;
  72253. var engine = this._scene.getEngine();
  72254. this.onBeforeRenderObservable.notifyObservers(this);
  72255. // Render
  72256. engine.enableEffect(currentEffect);
  72257. engine.setState(false);
  72258. // Texture
  72259. currentEffect.setTexture("textureSampler", this.texture);
  72260. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  72261. // Color
  72262. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  72263. // Scale / offset
  72264. currentEffect.setVector2("offset", this.offset);
  72265. currentEffect.setVector2("scale", this.scale);
  72266. // VBOs
  72267. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  72268. // Draw order
  72269. if (!this.alphaTest) {
  72270. engine.setAlphaMode(this.alphaBlendingMode);
  72271. engine.draw(true, 0, 6);
  72272. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  72273. }
  72274. else {
  72275. engine.draw(true, 0, 6);
  72276. }
  72277. this.onAfterRenderObservable.notifyObservers(this);
  72278. };
  72279. Layer.prototype.dispose = function () {
  72280. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72281. if (vertexBuffer) {
  72282. vertexBuffer.dispose();
  72283. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  72284. }
  72285. if (this._indexBuffer) {
  72286. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  72287. this._indexBuffer = null;
  72288. }
  72289. if (this.texture) {
  72290. this.texture.dispose();
  72291. this.texture = null;
  72292. }
  72293. // Remove from scene
  72294. var index = this._scene.layers.indexOf(this);
  72295. this._scene.layers.splice(index, 1);
  72296. // Callback
  72297. this.onDisposeObservable.notifyObservers(this);
  72298. this.onDisposeObservable.clear();
  72299. this.onAfterRenderObservable.clear();
  72300. this.onBeforeRenderObservable.clear();
  72301. };
  72302. return Layer;
  72303. }());
  72304. BABYLON.Layer = Layer;
  72305. })(BABYLON || (BABYLON = {}));
  72306. //# sourceMappingURL=babylon.layer.js.map
  72307. var BABYLON;
  72308. (function (BABYLON) {
  72309. var TextureTools = /** @class */ (function () {
  72310. function TextureTools() {
  72311. }
  72312. /**
  72313. * Uses the GPU to create a copy texture rescaled at a given size
  72314. * @param texture Texture to copy from
  72315. * @param width Desired width
  72316. * @param height Desired height
  72317. * @return Generated texture
  72318. */
  72319. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  72320. if (useBilinearMode === void 0) { useBilinearMode = true; }
  72321. var scene = texture.getScene();
  72322. var engine = scene.getEngine();
  72323. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  72324. rtt.wrapU = texture.wrapU;
  72325. rtt.wrapV = texture.wrapV;
  72326. rtt.uOffset = texture.uOffset;
  72327. rtt.vOffset = texture.vOffset;
  72328. rtt.uScale = texture.uScale;
  72329. rtt.vScale = texture.vScale;
  72330. rtt.uAng = texture.uAng;
  72331. rtt.vAng = texture.vAng;
  72332. rtt.wAng = texture.wAng;
  72333. rtt.coordinatesIndex = texture.coordinatesIndex;
  72334. rtt.level = texture.level;
  72335. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  72336. rtt._texture.isReady = false;
  72337. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72338. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72339. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  72340. passPostProcess.getEffect().executeWhenCompiled(function () {
  72341. passPostProcess.onApply = function (effect) {
  72342. effect.setTexture("textureSampler", texture);
  72343. };
  72344. var internalTexture = rtt.getInternalTexture();
  72345. if (internalTexture) {
  72346. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  72347. engine.unBindFramebuffer(internalTexture);
  72348. rtt.disposeFramebufferObjects();
  72349. passPostProcess.dispose();
  72350. internalTexture.isReady = true;
  72351. }
  72352. });
  72353. return rtt;
  72354. };
  72355. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  72356. if (!scene._environmentBRDFTexture) {
  72357. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72358. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72359. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72360. scene._environmentBRDFTexture = texture;
  72361. }
  72362. return scene._environmentBRDFTexture;
  72363. };
  72364. 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=";
  72365. return TextureTools;
  72366. }());
  72367. BABYLON.TextureTools = TextureTools;
  72368. })(BABYLON || (BABYLON = {}));
  72369. //# sourceMappingURL=babylon.textureTools.js.map
  72370. var BABYLON;
  72371. (function (BABYLON) {
  72372. var FramingBehavior = /** @class */ (function () {
  72373. function FramingBehavior() {
  72374. this._mode = FramingBehavior.FitFrustumSidesMode;
  72375. this._radiusScale = 1.0;
  72376. this._positionScale = 0.5;
  72377. this._defaultElevation = 0.3;
  72378. this._elevationReturnTime = 1500;
  72379. this._elevationReturnWaitTime = 1000;
  72380. this._zoomStopsAnimation = false;
  72381. this._framingTime = 1500;
  72382. this._isPointerDown = false;
  72383. this._lastInteractionTime = -Infinity;
  72384. // Framing control
  72385. this._animatables = new Array();
  72386. this._betaIsAnimating = false;
  72387. }
  72388. Object.defineProperty(FramingBehavior.prototype, "name", {
  72389. get: function () {
  72390. return "Framing";
  72391. },
  72392. enumerable: true,
  72393. configurable: true
  72394. });
  72395. Object.defineProperty(FramingBehavior.prototype, "mode", {
  72396. /**
  72397. * Gets current mode used by the behavior.
  72398. */
  72399. get: function () {
  72400. return this._mode;
  72401. },
  72402. /**
  72403. * Sets the current mode used by the behavior
  72404. */
  72405. set: function (mode) {
  72406. this._mode = mode;
  72407. },
  72408. enumerable: true,
  72409. configurable: true
  72410. });
  72411. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  72412. /**
  72413. * Gets the scale applied to the radius
  72414. */
  72415. get: function () {
  72416. return this._radiusScale;
  72417. },
  72418. /**
  72419. * Sets the scale applied to the radius (1 by default)
  72420. */
  72421. set: function (radius) {
  72422. this._radiusScale = radius;
  72423. },
  72424. enumerable: true,
  72425. configurable: true
  72426. });
  72427. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  72428. /**
  72429. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  72430. */
  72431. get: function () {
  72432. return this._positionScale;
  72433. },
  72434. /**
  72435. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  72436. */
  72437. set: function (scale) {
  72438. this._positionScale = scale;
  72439. },
  72440. enumerable: true,
  72441. configurable: true
  72442. });
  72443. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  72444. /**
  72445. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  72446. * behaviour is triggered, in radians.
  72447. */
  72448. get: function () {
  72449. return this._defaultElevation;
  72450. },
  72451. /**
  72452. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  72453. * behaviour is triggered, in radians.
  72454. */
  72455. set: function (elevation) {
  72456. this._defaultElevation = elevation;
  72457. },
  72458. enumerable: true,
  72459. configurable: true
  72460. });
  72461. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  72462. /**
  72463. * Gets the time (in milliseconds) taken to return to the default beta position.
  72464. * Negative value indicates camera should not return to default.
  72465. */
  72466. get: function () {
  72467. return this._elevationReturnTime;
  72468. },
  72469. /**
  72470. * Sets the time (in milliseconds) taken to return to the default beta position.
  72471. * Negative value indicates camera should not return to default.
  72472. */
  72473. set: function (speed) {
  72474. this._elevationReturnTime = speed;
  72475. },
  72476. enumerable: true,
  72477. configurable: true
  72478. });
  72479. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  72480. /**
  72481. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  72482. */
  72483. get: function () {
  72484. return this._elevationReturnWaitTime;
  72485. },
  72486. /**
  72487. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  72488. */
  72489. set: function (time) {
  72490. this._elevationReturnWaitTime = time;
  72491. },
  72492. enumerable: true,
  72493. configurable: true
  72494. });
  72495. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  72496. /**
  72497. * Gets the flag that indicates if user zooming should stop animation.
  72498. */
  72499. get: function () {
  72500. return this._zoomStopsAnimation;
  72501. },
  72502. /**
  72503. * Sets the flag that indicates if user zooming should stop animation.
  72504. */
  72505. set: function (flag) {
  72506. this._zoomStopsAnimation = flag;
  72507. },
  72508. enumerable: true,
  72509. configurable: true
  72510. });
  72511. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  72512. /**
  72513. * Gets the transition time when framing the mesh, in milliseconds
  72514. */
  72515. get: function () {
  72516. return this._framingTime;
  72517. },
  72518. /**
  72519. * Sets the transition time when framing the mesh, in milliseconds
  72520. */
  72521. set: function (time) {
  72522. this._framingTime = time;
  72523. },
  72524. enumerable: true,
  72525. configurable: true
  72526. });
  72527. FramingBehavior.prototype.attach = function (camera) {
  72528. var _this = this;
  72529. this._attachedCamera = camera;
  72530. var scene = this._attachedCamera.getScene();
  72531. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  72532. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  72533. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  72534. _this._isPointerDown = true;
  72535. return;
  72536. }
  72537. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  72538. _this._isPointerDown = false;
  72539. }
  72540. });
  72541. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  72542. if (mesh) {
  72543. _this.zoomOnMesh(mesh);
  72544. }
  72545. });
  72546. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  72547. // Stop the animation if there is user interaction and the animation should stop for this interaction
  72548. _this._applyUserInteraction();
  72549. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  72550. // back to the default position after a given timeout
  72551. _this._maintainCameraAboveGround();
  72552. });
  72553. };
  72554. FramingBehavior.prototype.detach = function () {
  72555. if (!this._attachedCamera) {
  72556. return;
  72557. }
  72558. var scene = this._attachedCamera.getScene();
  72559. if (this._onPrePointerObservableObserver) {
  72560. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  72561. }
  72562. if (this._onAfterCheckInputsObserver) {
  72563. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  72564. }
  72565. if (this._onMeshTargetChangedObserver) {
  72566. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  72567. }
  72568. this._attachedCamera = null;
  72569. };
  72570. /**
  72571. * Targets the given mesh and updates zoom level accordingly.
  72572. * @param mesh The mesh to target.
  72573. * @param radius Optional. If a cached radius position already exists, overrides default.
  72574. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  72575. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  72576. * @param onAnimationEnd Callback triggered at the end of the framing animation
  72577. */
  72578. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  72579. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  72580. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  72581. mesh.computeWorldMatrix(true);
  72582. var boundingBox = mesh.getBoundingInfo().boundingBox;
  72583. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  72584. };
  72585. /**
  72586. * Targets the given mesh and updates zoom level accordingly.
  72587. * @param mesh The mesh to target.
  72588. * @param radius Optional. If a cached radius position already exists, overrides default.
  72589. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  72590. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  72591. * @param onAnimationEnd Callback triggered at the end of the framing animation
  72592. */
  72593. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  72594. var _this = this;
  72595. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  72596. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  72597. var zoomTarget;
  72598. if (!this._attachedCamera) {
  72599. return;
  72600. }
  72601. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  72602. var bottom = minimumWorld.y;
  72603. var top = maximumWorld.y;
  72604. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  72605. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  72606. if (focusOnOriginXZ) {
  72607. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  72608. }
  72609. else {
  72610. var centerWorld = minimumWorld.add(radiusWorld);
  72611. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  72612. }
  72613. if (!this._vectorTransition) {
  72614. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  72615. }
  72616. this._betaIsAnimating = true;
  72617. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  72618. if (animatable) {
  72619. this._animatables.push(animatable);
  72620. }
  72621. // sets the radius and lower radius bounds
  72622. // Small delta ensures camera is not always at lower zoom limit.
  72623. var radius = 0;
  72624. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  72625. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  72626. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  72627. radius = position;
  72628. }
  72629. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  72630. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  72631. if (this._attachedCamera.lowerRadiusLimit === null) {
  72632. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  72633. }
  72634. }
  72635. // Set sensibilities
  72636. var extend = maximumWorld.subtract(minimumWorld).length();
  72637. this._attachedCamera.panningSensibility = 5000 / extend;
  72638. this._attachedCamera.wheelPrecision = 100 / radius;
  72639. // transition to new radius
  72640. if (!this._radiusTransition) {
  72641. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  72642. }
  72643. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  72644. if (onAnimationEnd) {
  72645. onAnimationEnd();
  72646. }
  72647. if (_this._attachedCamera) {
  72648. _this._attachedCamera.storeState();
  72649. }
  72650. });
  72651. if (animatable) {
  72652. this._animatables.push(animatable);
  72653. }
  72654. };
  72655. /**
  72656. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  72657. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  72658. * frustum width.
  72659. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  72660. * to fully enclose the mesh in the viewing frustum.
  72661. */
  72662. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  72663. var size = maximumWorld.subtract(minimumWorld);
  72664. var boxVectorGlobalDiagonal = size.length();
  72665. var frustumSlope = this._getFrustumSlope();
  72666. // Formula for setting distance
  72667. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  72668. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  72669. // Horizon distance
  72670. var radius = radiusWithoutFraming * this._radiusScale;
  72671. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  72672. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  72673. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  72674. var camera = this._attachedCamera;
  72675. if (!camera) {
  72676. return 0;
  72677. }
  72678. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  72679. // Don't exceed the requested limit
  72680. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  72681. }
  72682. // Don't exceed the upper radius limit
  72683. if (camera.upperRadiusLimit) {
  72684. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  72685. }
  72686. return distance;
  72687. };
  72688. /**
  72689. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  72690. * is automatically returned to its default position (expected to be above ground plane).
  72691. */
  72692. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  72693. var _this = this;
  72694. if (this._elevationReturnTime < 0) {
  72695. return;
  72696. }
  72697. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  72698. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  72699. var limitBeta = Math.PI * 0.5;
  72700. // Bring the camera back up if below the ground plane
  72701. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  72702. this._betaIsAnimating = true;
  72703. //Transition to new position
  72704. this.stopAllAnimations();
  72705. if (!this._betaTransition) {
  72706. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  72707. }
  72708. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  72709. _this._clearAnimationLocks();
  72710. _this.stopAllAnimations();
  72711. });
  72712. if (animatabe) {
  72713. this._animatables.push(animatabe);
  72714. }
  72715. }
  72716. };
  72717. /**
  72718. * Returns the frustum slope based on the canvas ratio and camera FOV
  72719. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  72720. */
  72721. FramingBehavior.prototype._getFrustumSlope = function () {
  72722. // Calculate the viewport ratio
  72723. // Aspect Ratio is Height/Width.
  72724. var camera = this._attachedCamera;
  72725. if (!camera) {
  72726. return BABYLON.Vector2.Zero();
  72727. }
  72728. var engine = camera.getScene().getEngine();
  72729. var aspectRatio = engine.getAspectRatio(camera);
  72730. // Camera FOV is the vertical field of view (top-bottom) in radians.
  72731. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  72732. var frustumSlopeY = Math.tan(camera.fov / 2);
  72733. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  72734. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  72735. // along the forward vector.
  72736. var frustumSlopeX = frustumSlopeY * aspectRatio;
  72737. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  72738. };
  72739. /**
  72740. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  72741. */
  72742. FramingBehavior.prototype._clearAnimationLocks = function () {
  72743. this._betaIsAnimating = false;
  72744. };
  72745. /**
  72746. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  72747. */
  72748. FramingBehavior.prototype._applyUserInteraction = function () {
  72749. if (this.isUserIsMoving) {
  72750. this._lastInteractionTime = BABYLON.Tools.Now;
  72751. this.stopAllAnimations();
  72752. this._clearAnimationLocks();
  72753. }
  72754. };
  72755. /**
  72756. * Stops and removes all animations that have been applied to the camera
  72757. */
  72758. FramingBehavior.prototype.stopAllAnimations = function () {
  72759. if (this._attachedCamera) {
  72760. this._attachedCamera.animations = [];
  72761. }
  72762. while (this._animatables.length) {
  72763. if (this._animatables[0]) {
  72764. this._animatables[0].onAnimationEnd = null;
  72765. this._animatables[0].stop();
  72766. }
  72767. this._animatables.shift();
  72768. }
  72769. };
  72770. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  72771. /**
  72772. * Gets a value indicating if the user is moving the camera
  72773. */
  72774. get: function () {
  72775. if (!this._attachedCamera) {
  72776. return false;
  72777. }
  72778. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  72779. this._attachedCamera.inertialBetaOffset !== 0 ||
  72780. this._attachedCamera.inertialRadiusOffset !== 0 ||
  72781. this._attachedCamera.inertialPanningX !== 0 ||
  72782. this._attachedCamera.inertialPanningY !== 0 ||
  72783. this._isPointerDown;
  72784. },
  72785. enumerable: true,
  72786. configurable: true
  72787. });
  72788. /**
  72789. * The easing function used by animations
  72790. */
  72791. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  72792. /**
  72793. * The easing mode used by animations
  72794. */
  72795. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  72796. // Statics
  72797. /**
  72798. * The camera can move all the way towards the mesh.
  72799. */
  72800. FramingBehavior.IgnoreBoundsSizeMode = 0;
  72801. /**
  72802. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  72803. */
  72804. FramingBehavior.FitFrustumSidesMode = 1;
  72805. return FramingBehavior;
  72806. }());
  72807. BABYLON.FramingBehavior = FramingBehavior;
  72808. })(BABYLON || (BABYLON = {}));
  72809. //# sourceMappingURL=babylon.framingBehavior.js.map
  72810. var BABYLON;
  72811. (function (BABYLON) {
  72812. /**
  72813. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  72814. */
  72815. var BouncingBehavior = /** @class */ (function () {
  72816. function BouncingBehavior() {
  72817. /**
  72818. * The duration of the animation, in milliseconds
  72819. */
  72820. this.transitionDuration = 450;
  72821. /**
  72822. * Length of the distance animated by the transition when lower radius is reached
  72823. */
  72824. this.lowerRadiusTransitionRange = 2;
  72825. /**
  72826. * Length of the distance animated by the transition when upper radius is reached
  72827. */
  72828. this.upperRadiusTransitionRange = -2;
  72829. this._autoTransitionRange = false;
  72830. // Animations
  72831. this._radiusIsAnimating = false;
  72832. this._radiusBounceTransition = null;
  72833. this._animatables = new Array();
  72834. }
  72835. Object.defineProperty(BouncingBehavior.prototype, "name", {
  72836. get: function () {
  72837. return "Bouncing";
  72838. },
  72839. enumerable: true,
  72840. configurable: true
  72841. });
  72842. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  72843. /**
  72844. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  72845. */
  72846. get: function () {
  72847. return this._autoTransitionRange;
  72848. },
  72849. /**
  72850. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  72851. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  72852. */
  72853. set: function (value) {
  72854. var _this = this;
  72855. if (this._autoTransitionRange === value) {
  72856. return;
  72857. }
  72858. this._autoTransitionRange = value;
  72859. var camera = this._attachedCamera;
  72860. if (!camera) {
  72861. return;
  72862. }
  72863. if (value) {
  72864. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  72865. if (!mesh) {
  72866. return;
  72867. }
  72868. mesh.computeWorldMatrix(true);
  72869. var diagonal = mesh.getBoundingInfo().diagonalLength;
  72870. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  72871. _this.upperRadiusTransitionRange = diagonal * 0.05;
  72872. });
  72873. }
  72874. else if (this._onMeshTargetChangedObserver) {
  72875. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  72876. }
  72877. },
  72878. enumerable: true,
  72879. configurable: true
  72880. });
  72881. BouncingBehavior.prototype.attach = function (camera) {
  72882. var _this = this;
  72883. this._attachedCamera = camera;
  72884. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  72885. if (!_this._attachedCamera) {
  72886. return;
  72887. }
  72888. // Add the bounce animation to the lower radius limit
  72889. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  72890. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  72891. }
  72892. // Add the bounce animation to the upper radius limit
  72893. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  72894. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  72895. }
  72896. });
  72897. };
  72898. BouncingBehavior.prototype.detach = function () {
  72899. if (!this._attachedCamera) {
  72900. return;
  72901. }
  72902. if (this._onAfterCheckInputsObserver) {
  72903. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  72904. }
  72905. if (this._onMeshTargetChangedObserver) {
  72906. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  72907. }
  72908. this._attachedCamera = null;
  72909. };
  72910. /**
  72911. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  72912. * @param radiusLimit The limit to check against.
  72913. * @return Bool to indicate if at limit.
  72914. */
  72915. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  72916. if (!this._attachedCamera) {
  72917. return false;
  72918. }
  72919. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  72920. return true;
  72921. }
  72922. return false;
  72923. };
  72924. /**
  72925. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  72926. * @param radiusDelta The delta by which to animate to. Can be negative.
  72927. */
  72928. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  72929. var _this = this;
  72930. if (!this._attachedCamera) {
  72931. return;
  72932. }
  72933. if (!this._radiusBounceTransition) {
  72934. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  72935. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  72936. }
  72937. // Prevent zoom until bounce has completed
  72938. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  72939. this._attachedCamera.wheelPrecision = Infinity;
  72940. this._attachedCamera.inertialRadiusOffset = 0;
  72941. // Animate to the radius limit
  72942. this.stopAllAnimations();
  72943. this._radiusIsAnimating = true;
  72944. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  72945. if (animatable) {
  72946. this._animatables.push(animatable);
  72947. }
  72948. };
  72949. /**
  72950. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  72951. */
  72952. BouncingBehavior.prototype._clearAnimationLocks = function () {
  72953. this._radiusIsAnimating = false;
  72954. if (this._attachedCamera) {
  72955. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  72956. }
  72957. };
  72958. /**
  72959. * Stops and removes all animations that have been applied to the camera
  72960. */
  72961. BouncingBehavior.prototype.stopAllAnimations = function () {
  72962. if (this._attachedCamera) {
  72963. this._attachedCamera.animations = [];
  72964. }
  72965. while (this._animatables.length) {
  72966. this._animatables[0].onAnimationEnd = null;
  72967. this._animatables[0].stop();
  72968. this._animatables.shift();
  72969. }
  72970. };
  72971. /**
  72972. * The easing function used by animations
  72973. */
  72974. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  72975. /**
  72976. * The easing mode used by animations
  72977. */
  72978. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  72979. return BouncingBehavior;
  72980. }());
  72981. BABYLON.BouncingBehavior = BouncingBehavior;
  72982. })(BABYLON || (BABYLON = {}));
  72983. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  72984. var BABYLON;
  72985. (function (BABYLON) {
  72986. var AutoRotationBehavior = /** @class */ (function () {
  72987. function AutoRotationBehavior() {
  72988. this._zoomStopsAnimation = false;
  72989. this._idleRotationSpeed = 0.05;
  72990. this._idleRotationWaitTime = 2000;
  72991. this._idleRotationSpinupTime = 2000;
  72992. this._isPointerDown = false;
  72993. this._lastFrameTime = null;
  72994. this._lastInteractionTime = -Infinity;
  72995. this._cameraRotationSpeed = 0;
  72996. this._lastFrameRadius = 0;
  72997. }
  72998. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  72999. get: function () {
  73000. return "AutoRotation";
  73001. },
  73002. enumerable: true,
  73003. configurable: true
  73004. });
  73005. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  73006. /**
  73007. * Gets the flag that indicates if user zooming should stop animation.
  73008. */
  73009. get: function () {
  73010. return this._zoomStopsAnimation;
  73011. },
  73012. /**
  73013. * Sets the flag that indicates if user zooming should stop animation.
  73014. */
  73015. set: function (flag) {
  73016. this._zoomStopsAnimation = flag;
  73017. },
  73018. enumerable: true,
  73019. configurable: true
  73020. });
  73021. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  73022. /**
  73023. * Gets the default speed at which the camera rotates around the model.
  73024. */
  73025. get: function () {
  73026. return this._idleRotationSpeed;
  73027. },
  73028. /**
  73029. * Sets the default speed at which the camera rotates around the model.
  73030. */
  73031. set: function (speed) {
  73032. this._idleRotationSpeed = speed;
  73033. },
  73034. enumerable: true,
  73035. configurable: true
  73036. });
  73037. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  73038. /**
  73039. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  73040. */
  73041. get: function () {
  73042. return this._idleRotationWaitTime;
  73043. },
  73044. /**
  73045. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  73046. */
  73047. set: function (time) {
  73048. this._idleRotationWaitTime = time;
  73049. },
  73050. enumerable: true,
  73051. configurable: true
  73052. });
  73053. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  73054. /**
  73055. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  73056. */
  73057. get: function () {
  73058. return this._idleRotationSpinupTime;
  73059. },
  73060. /**
  73061. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  73062. */
  73063. set: function (time) {
  73064. this._idleRotationSpinupTime = time;
  73065. },
  73066. enumerable: true,
  73067. configurable: true
  73068. });
  73069. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  73070. /**
  73071. * Gets a value indicating if the camera is currently rotating because of this behavior
  73072. */
  73073. get: function () {
  73074. return Math.abs(this._cameraRotationSpeed) > 0;
  73075. },
  73076. enumerable: true,
  73077. configurable: true
  73078. });
  73079. AutoRotationBehavior.prototype.attach = function (camera) {
  73080. var _this = this;
  73081. this._attachedCamera = camera;
  73082. var scene = this._attachedCamera.getScene();
  73083. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  73084. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  73085. _this._isPointerDown = true;
  73086. return;
  73087. }
  73088. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  73089. _this._isPointerDown = false;
  73090. }
  73091. });
  73092. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  73093. var now = BABYLON.Tools.Now;
  73094. var dt = 0;
  73095. if (_this._lastFrameTime != null) {
  73096. dt = now - _this._lastFrameTime;
  73097. }
  73098. _this._lastFrameTime = now;
  73099. // Stop the animation if there is user interaction and the animation should stop for this interaction
  73100. _this._applyUserInteraction();
  73101. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  73102. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  73103. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  73104. // Step camera rotation by rotation speed
  73105. if (_this._attachedCamera) {
  73106. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  73107. }
  73108. });
  73109. };
  73110. AutoRotationBehavior.prototype.detach = function () {
  73111. if (!this._attachedCamera) {
  73112. return;
  73113. }
  73114. var scene = this._attachedCamera.getScene();
  73115. if (this._onPrePointerObservableObserver) {
  73116. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  73117. }
  73118. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  73119. this._attachedCamera = null;
  73120. };
  73121. /**
  73122. * Returns true if user is scrolling.
  73123. * @return true if user is scrolling.
  73124. */
  73125. AutoRotationBehavior.prototype._userIsZooming = function () {
  73126. if (!this._attachedCamera) {
  73127. return false;
  73128. }
  73129. return this._attachedCamera.inertialRadiusOffset !== 0;
  73130. };
  73131. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  73132. if (!this._attachedCamera) {
  73133. return false;
  73134. }
  73135. var zoomHasHitLimit = false;
  73136. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  73137. zoomHasHitLimit = true;
  73138. }
  73139. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  73140. this._lastFrameRadius = this._attachedCamera.radius;
  73141. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  73142. };
  73143. /**
  73144. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  73145. */
  73146. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  73147. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  73148. this._lastInteractionTime = BABYLON.Tools.Now;
  73149. }
  73150. };
  73151. // Tools
  73152. AutoRotationBehavior.prototype._userIsMoving = function () {
  73153. if (!this._attachedCamera) {
  73154. return false;
  73155. }
  73156. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  73157. this._attachedCamera.inertialBetaOffset !== 0 ||
  73158. this._attachedCamera.inertialRadiusOffset !== 0 ||
  73159. this._attachedCamera.inertialPanningX !== 0 ||
  73160. this._attachedCamera.inertialPanningY !== 0 ||
  73161. this._isPointerDown;
  73162. };
  73163. return AutoRotationBehavior;
  73164. }());
  73165. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  73166. })(BABYLON || (BABYLON = {}));
  73167. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  73168. var BABYLON;
  73169. (function (BABYLON) {
  73170. var NullEngineOptions = /** @class */ (function () {
  73171. function NullEngineOptions() {
  73172. this.renderWidth = 512;
  73173. this.renderHeight = 256;
  73174. this.textureSize = 512;
  73175. }
  73176. return NullEngineOptions;
  73177. }());
  73178. BABYLON.NullEngineOptions = NullEngineOptions;
  73179. /**
  73180. * The null engine class provides support for headless version of babylon.js.
  73181. * This can be used in server side scenario or for testing purposes
  73182. */
  73183. var NullEngine = /** @class */ (function (_super) {
  73184. __extends(NullEngine, _super);
  73185. function NullEngine(options) {
  73186. if (options === void 0) { options = new NullEngineOptions(); }
  73187. var _this = _super.call(this, null) || this;
  73188. _this._options = options;
  73189. // Init caps
  73190. // We consider we are on a webgl1 capable device
  73191. _this._caps = new BABYLON.EngineCapabilities();
  73192. _this._caps.maxTexturesImageUnits = 16;
  73193. _this._caps.maxVertexTextureImageUnits = 16;
  73194. _this._caps.maxTextureSize = 512;
  73195. _this._caps.maxCubemapTextureSize = 512;
  73196. _this._caps.maxRenderTextureSize = 512;
  73197. _this._caps.maxVertexAttribs = 16;
  73198. _this._caps.maxVaryingVectors = 16;
  73199. _this._caps.maxFragmentUniformVectors = 16;
  73200. _this._caps.maxVertexUniformVectors = 16;
  73201. // Extensions
  73202. _this._caps.standardDerivatives = false;
  73203. _this._caps.astc = null;
  73204. _this._caps.s3tc = null;
  73205. _this._caps.pvrtc = null;
  73206. _this._caps.etc1 = null;
  73207. _this._caps.etc2 = null;
  73208. _this._caps.textureAnisotropicFilterExtension = null;
  73209. _this._caps.maxAnisotropy = 0;
  73210. _this._caps.uintIndices = false;
  73211. _this._caps.fragmentDepthSupported = false;
  73212. _this._caps.highPrecisionShaderSupported = true;
  73213. _this._caps.colorBufferFloat = false;
  73214. _this._caps.textureFloat = false;
  73215. _this._caps.textureFloatLinearFiltering = false;
  73216. _this._caps.textureFloatRender = false;
  73217. _this._caps.textureHalfFloat = false;
  73218. _this._caps.textureHalfFloatLinearFiltering = false;
  73219. _this._caps.textureHalfFloatRender = false;
  73220. _this._caps.textureLOD = false;
  73221. _this._caps.drawBuffersExtension = false;
  73222. _this._caps.depthTextureExtension = false;
  73223. _this._caps.vertexArrayObject = false;
  73224. _this._caps.instancedArrays = false;
  73225. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  73226. // Wrappers
  73227. if (typeof URL === "undefined") {
  73228. URL = {
  73229. createObjectURL: function () { },
  73230. revokeObjectURL: function () { }
  73231. };
  73232. }
  73233. if (typeof Blob === "undefined") {
  73234. Blob = function () { };
  73235. }
  73236. return _this;
  73237. }
  73238. NullEngine.prototype.createVertexBuffer = function (vertices) {
  73239. return {
  73240. capacity: 0,
  73241. references: 1,
  73242. is32Bits: false
  73243. };
  73244. };
  73245. NullEngine.prototype.createIndexBuffer = function (indices) {
  73246. return {
  73247. capacity: 0,
  73248. references: 1,
  73249. is32Bits: false
  73250. };
  73251. };
  73252. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  73253. if (stencil === void 0) { stencil = false; }
  73254. };
  73255. NullEngine.prototype.getRenderWidth = function (useScreen) {
  73256. if (useScreen === void 0) { useScreen = false; }
  73257. if (!useScreen && this._currentRenderTarget) {
  73258. return this._currentRenderTarget.width;
  73259. }
  73260. return this._options.renderWidth;
  73261. };
  73262. NullEngine.prototype.getRenderHeight = function (useScreen) {
  73263. if (useScreen === void 0) { useScreen = false; }
  73264. if (!useScreen && this._currentRenderTarget) {
  73265. return this._currentRenderTarget.height;
  73266. }
  73267. return this._options.renderHeight;
  73268. };
  73269. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  73270. this._cachedViewport = viewport;
  73271. };
  73272. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  73273. return {
  73274. __SPECTOR_rebuildProgram: null,
  73275. };
  73276. };
  73277. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  73278. return [];
  73279. };
  73280. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  73281. return [];
  73282. };
  73283. NullEngine.prototype.bindSamplers = function (effect) {
  73284. this._currentEffect = null;
  73285. };
  73286. NullEngine.prototype.enableEffect = function (effect) {
  73287. this._currentEffect = effect;
  73288. if (effect.onBind) {
  73289. effect.onBind(effect);
  73290. }
  73291. effect.onBindObservable.notifyObservers(effect);
  73292. };
  73293. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  73294. if (zOffset === void 0) { zOffset = 0; }
  73295. if (reverseSide === void 0) { reverseSide = false; }
  73296. };
  73297. NullEngine.prototype.setIntArray = function (uniform, array) {
  73298. };
  73299. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  73300. };
  73301. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  73302. };
  73303. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  73304. };
  73305. NullEngine.prototype.setFloatArray = function (uniform, array) {
  73306. };
  73307. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  73308. };
  73309. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  73310. };
  73311. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  73312. };
  73313. NullEngine.prototype.setArray = function (uniform, array) {
  73314. };
  73315. NullEngine.prototype.setArray2 = function (uniform, array) {
  73316. };
  73317. NullEngine.prototype.setArray3 = function (uniform, array) {
  73318. };
  73319. NullEngine.prototype.setArray4 = function (uniform, array) {
  73320. };
  73321. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  73322. };
  73323. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  73324. };
  73325. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  73326. };
  73327. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  73328. };
  73329. NullEngine.prototype.setFloat = function (uniform, value) {
  73330. };
  73331. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  73332. };
  73333. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  73334. };
  73335. NullEngine.prototype.setBool = function (uniform, bool) {
  73336. };
  73337. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  73338. };
  73339. NullEngine.prototype.setColor3 = function (uniform, color3) {
  73340. };
  73341. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  73342. };
  73343. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  73344. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  73345. if (this._alphaMode === mode) {
  73346. return;
  73347. }
  73348. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  73349. if (!noDepthWriteChange) {
  73350. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  73351. }
  73352. this._alphaMode = mode;
  73353. };
  73354. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  73355. };
  73356. NullEngine.prototype.wipeCaches = function (bruteForce) {
  73357. if (this.preventCacheWipeBetweenFrames) {
  73358. return;
  73359. }
  73360. this.resetTextureCache();
  73361. this._currentEffect = null;
  73362. if (bruteForce) {
  73363. this._currentProgram = null;
  73364. this._stencilState.reset();
  73365. this._depthCullingState.reset();
  73366. this.setDepthFunctionToLessOrEqual();
  73367. this._alphaState.reset();
  73368. }
  73369. this._cachedVertexBuffers = null;
  73370. this._cachedIndexBuffer = null;
  73371. this._cachedEffectForVertexBuffers = null;
  73372. };
  73373. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  73374. };
  73375. NullEngine.prototype._createTexture = function () {
  73376. return {};
  73377. };
  73378. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  73379. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73380. if (onLoad === void 0) { onLoad = null; }
  73381. if (onError === void 0) { onError = null; }
  73382. if (buffer === void 0) { buffer = null; }
  73383. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  73384. var url = String(urlArg);
  73385. texture.url = url;
  73386. texture.generateMipMaps = !noMipmap;
  73387. texture.samplingMode = samplingMode;
  73388. texture.invertY = invertY;
  73389. texture.baseWidth = this._options.textureSize;
  73390. texture.baseHeight = this._options.textureSize;
  73391. texture.width = this._options.textureSize;
  73392. texture.height = this._options.textureSize;
  73393. if (format) {
  73394. texture.format = format;
  73395. }
  73396. texture.isReady = true;
  73397. if (onLoad) {
  73398. onLoad();
  73399. }
  73400. return texture;
  73401. };
  73402. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  73403. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  73404. if (options !== undefined && typeof options === "object") {
  73405. fullOptions.generateMipMaps = options.generateMipMaps;
  73406. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  73407. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  73408. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  73409. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  73410. }
  73411. else {
  73412. fullOptions.generateMipMaps = options;
  73413. fullOptions.generateDepthBuffer = true;
  73414. fullOptions.generateStencilBuffer = false;
  73415. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73416. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  73417. }
  73418. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  73419. var width = size.width || size;
  73420. var height = size.height || size;
  73421. texture._depthStencilBuffer = {};
  73422. texture._framebuffer = {};
  73423. texture.baseWidth = width;
  73424. texture.baseHeight = height;
  73425. texture.width = width;
  73426. texture.height = height;
  73427. texture.isReady = true;
  73428. texture.samples = 1;
  73429. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  73430. texture.samplingMode = fullOptions.samplingMode;
  73431. texture.type = fullOptions.type;
  73432. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  73433. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  73434. return texture;
  73435. };
  73436. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  73437. texture.samplingMode = samplingMode;
  73438. };
  73439. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  73440. if (this._currentRenderTarget) {
  73441. this.unBindFramebuffer(this._currentRenderTarget);
  73442. }
  73443. this._currentRenderTarget = texture;
  73444. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  73445. if (this._cachedViewport && !forceFullscreenViewport) {
  73446. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  73447. }
  73448. };
  73449. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  73450. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  73451. this._currentRenderTarget = null;
  73452. if (onBeforeUnbind) {
  73453. if (texture._MSAAFramebuffer) {
  73454. this._currentFramebuffer = texture._framebuffer;
  73455. }
  73456. onBeforeUnbind();
  73457. }
  73458. this._currentFramebuffer = null;
  73459. };
  73460. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  73461. var vbo = {
  73462. capacity: 1,
  73463. references: 1,
  73464. is32Bits: false
  73465. };
  73466. return vbo;
  73467. };
  73468. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  73469. if (offset === void 0) { offset = 0; }
  73470. };
  73471. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  73472. };
  73473. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  73474. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  73475. this._activeTexturesCache[this._activeTexture] = texture;
  73476. }
  73477. };
  73478. NullEngine.prototype._bindTexture = function (channel, texture) {
  73479. if (channel < 0) {
  73480. return;
  73481. }
  73482. this._bindTextureDirectly(0, texture);
  73483. };
  73484. return NullEngine;
  73485. }(BABYLON.Engine));
  73486. BABYLON.NullEngine = NullEngine;
  73487. })(BABYLON || (BABYLON = {}));
  73488. //# sourceMappingURL=babylon.nullEngine.js.map
  73489. 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}"};
  73490. 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\nuniform sampler2D txColorTransform;\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#ifdef COLORGRADING\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;\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\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(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#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","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};"};
  73491. (function universalModuleDefinition(root, factory) {
  73492. if (root && root["BABYLON"]) {
  73493. return;
  73494. }
  73495. if(typeof exports === 'object' && typeof module === 'object')
  73496. module.exports = factory();
  73497. else if(typeof define === 'function' && define.amd)
  73498. define([], factory);
  73499. else if(typeof exports === 'object')
  73500. exports["BABYLON"] = factory();
  73501. else {
  73502. root["BABYLON"] = factory();
  73503. }
  73504. })(this, function() {
  73505. return BABYLON;
  73506. });