babylon.max.js 4.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. //# sourceMappingURL=babylon.types.js.map
  18. var BABYLON;
  19. (function (BABYLON) {
  20. var KeyboardEventTypes = /** @class */ (function () {
  21. function KeyboardEventTypes() {
  22. }
  23. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  24. get: function () {
  25. return KeyboardEventTypes._KEYDOWN;
  26. },
  27. enumerable: true,
  28. configurable: true
  29. });
  30. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  31. get: function () {
  32. return KeyboardEventTypes._KEYUP;
  33. },
  34. enumerable: true,
  35. configurable: true
  36. });
  37. KeyboardEventTypes._KEYDOWN = 0x01;
  38. KeyboardEventTypes._KEYUP = 0x02;
  39. return KeyboardEventTypes;
  40. }());
  41. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  42. var KeyboardInfo = /** @class */ (function () {
  43. function KeyboardInfo(type, event) {
  44. this.type = type;
  45. this.event = event;
  46. }
  47. return KeyboardInfo;
  48. }());
  49. BABYLON.KeyboardInfo = KeyboardInfo;
  50. /**
  51. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  52. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  53. */
  54. var KeyboardInfoPre = /** @class */ (function (_super) {
  55. __extends(KeyboardInfoPre, _super);
  56. function KeyboardInfoPre(type, event) {
  57. var _this = _super.call(this, type, event) || this;
  58. _this.skipOnPointerObservable = false;
  59. return _this;
  60. }
  61. return KeyboardInfoPre;
  62. }(KeyboardInfo));
  63. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  64. })(BABYLON || (BABYLON = {}));
  65. //# sourceMappingURL=babylon.keyboardEvents.js.map
  66. var BABYLON;
  67. (function (BABYLON) {
  68. var PointerEventTypes = /** @class */ (function () {
  69. function PointerEventTypes() {
  70. }
  71. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  72. get: function () {
  73. return PointerEventTypes._POINTERDOWN;
  74. },
  75. enumerable: true,
  76. configurable: true
  77. });
  78. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  79. get: function () {
  80. return PointerEventTypes._POINTERUP;
  81. },
  82. enumerable: true,
  83. configurable: true
  84. });
  85. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  86. get: function () {
  87. return PointerEventTypes._POINTERMOVE;
  88. },
  89. enumerable: true,
  90. configurable: true
  91. });
  92. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  93. get: function () {
  94. return PointerEventTypes._POINTERWHEEL;
  95. },
  96. enumerable: true,
  97. configurable: true
  98. });
  99. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  100. get: function () {
  101. return PointerEventTypes._POINTERPICK;
  102. },
  103. enumerable: true,
  104. configurable: true
  105. });
  106. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  107. get: function () {
  108. return PointerEventTypes._POINTERTAP;
  109. },
  110. enumerable: true,
  111. configurable: true
  112. });
  113. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  114. get: function () {
  115. return PointerEventTypes._POINTERDOUBLETAP;
  116. },
  117. enumerable: true,
  118. configurable: true
  119. });
  120. PointerEventTypes._POINTERDOWN = 0x01;
  121. PointerEventTypes._POINTERUP = 0x02;
  122. PointerEventTypes._POINTERMOVE = 0x04;
  123. PointerEventTypes._POINTERWHEEL = 0x08;
  124. PointerEventTypes._POINTERPICK = 0x10;
  125. PointerEventTypes._POINTERTAP = 0x20;
  126. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  127. return PointerEventTypes;
  128. }());
  129. BABYLON.PointerEventTypes = PointerEventTypes;
  130. var PointerInfoBase = /** @class */ (function () {
  131. function PointerInfoBase(type, event) {
  132. this.type = type;
  133. this.event = event;
  134. }
  135. return PointerInfoBase;
  136. }());
  137. BABYLON.PointerInfoBase = PointerInfoBase;
  138. /**
  139. * This class is used to store pointer related info for the onPrePointerObservable event.
  140. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  141. */
  142. var PointerInfoPre = /** @class */ (function (_super) {
  143. __extends(PointerInfoPre, _super);
  144. function PointerInfoPre(type, event, localX, localY) {
  145. var _this = _super.call(this, type, event) || this;
  146. _this.skipOnPointerObservable = false;
  147. _this.localPosition = new BABYLON.Vector2(localX, localY);
  148. return _this;
  149. }
  150. return PointerInfoPre;
  151. }(PointerInfoBase));
  152. BABYLON.PointerInfoPre = PointerInfoPre;
  153. /**
  154. * This type contains all the data related to a pointer event in Babylon.js.
  155. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  156. */
  157. var PointerInfo = /** @class */ (function (_super) {
  158. __extends(PointerInfo, _super);
  159. function PointerInfo(type, event, pickInfo) {
  160. var _this = _super.call(this, type, event) || this;
  161. _this.pickInfo = pickInfo;
  162. return _this;
  163. }
  164. return PointerInfo;
  165. }(PointerInfoBase));
  166. BABYLON.PointerInfo = PointerInfo;
  167. })(BABYLON || (BABYLON = {}));
  168. //# sourceMappingURL=babylon.pointerEvents.js.map
  169. var BABYLON;
  170. (function (BABYLON) {
  171. BABYLON.ToGammaSpace = 1 / 2.2;
  172. BABYLON.ToLinearSpace = 2.2;
  173. BABYLON.Epsilon = 0.001;
  174. var Color3 = /** @class */ (function () {
  175. /**
  176. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  177. */
  178. function Color3(r, g, b) {
  179. if (r === void 0) { r = 0; }
  180. if (g === void 0) { g = 0; }
  181. if (b === void 0) { b = 0; }
  182. this.r = r;
  183. this.g = g;
  184. this.b = b;
  185. }
  186. /**
  187. * Returns a string with the Color3 current values.
  188. */
  189. Color3.prototype.toString = function () {
  190. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  191. };
  192. /**
  193. * Returns the string "Color3".
  194. */
  195. Color3.prototype.getClassName = function () {
  196. return "Color3";
  197. };
  198. /**
  199. * Returns the Color3 hash code.
  200. */
  201. Color3.prototype.getHashCode = function () {
  202. var hash = this.r || 0;
  203. hash = (hash * 397) ^ (this.g || 0);
  204. hash = (hash * 397) ^ (this.b || 0);
  205. return hash;
  206. };
  207. // Operators
  208. /**
  209. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  210. * Returns the Color3.
  211. */
  212. Color3.prototype.toArray = function (array, index) {
  213. if (index === undefined) {
  214. index = 0;
  215. }
  216. array[index] = this.r;
  217. array[index + 1] = this.g;
  218. array[index + 2] = this.b;
  219. return this;
  220. };
  221. /**
  222. * Returns a new Color4 object from the current Color3 and the passed alpha.
  223. */
  224. Color3.prototype.toColor4 = function (alpha) {
  225. if (alpha === void 0) { alpha = 1; }
  226. return new Color4(this.r, this.g, this.b, alpha);
  227. };
  228. /**
  229. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  230. */
  231. Color3.prototype.asArray = function () {
  232. var result = new Array();
  233. this.toArray(result, 0);
  234. return result;
  235. };
  236. /**
  237. * Returns the luminance value (float).
  238. */
  239. Color3.prototype.toLuminance = function () {
  240. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  241. };
  242. /**
  243. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  244. * Returns this new object.
  245. */
  246. Color3.prototype.multiply = function (otherColor) {
  247. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  248. };
  249. /**
  250. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  251. * Returns the current Color3.
  252. */
  253. Color3.prototype.multiplyToRef = function (otherColor, result) {
  254. result.r = this.r * otherColor.r;
  255. result.g = this.g * otherColor.g;
  256. result.b = this.b * otherColor.b;
  257. return this;
  258. };
  259. /**
  260. * Boolean : True if the rgb values are equal to the passed ones.
  261. */
  262. Color3.prototype.equals = function (otherColor) {
  263. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  264. };
  265. /**
  266. * Boolean : True if the rgb values are equal to the passed ones.
  267. */
  268. Color3.prototype.equalsFloats = function (r, g, b) {
  269. return this.r === r && this.g === g && this.b === b;
  270. };
  271. /**
  272. * Multiplies in place each rgb value by scale.
  273. * Returns the updated Color3.
  274. */
  275. Color3.prototype.scale = function (scale) {
  276. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  277. };
  278. /**
  279. * Multiplies the rgb values by scale and stores the result into "result".
  280. * Returns the unmodified current Color3.
  281. */
  282. Color3.prototype.scaleToRef = function (scale, result) {
  283. result.r = this.r * scale;
  284. result.g = this.g * scale;
  285. result.b = this.b * scale;
  286. return this;
  287. };
  288. /**
  289. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  290. */
  291. Color3.prototype.add = function (otherColor) {
  292. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  293. };
  294. /**
  295. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  296. * Returns the unmodified current Color3.
  297. */
  298. Color3.prototype.addToRef = function (otherColor, result) {
  299. result.r = this.r + otherColor.r;
  300. result.g = this.g + otherColor.g;
  301. result.b = this.b + otherColor.b;
  302. return this;
  303. };
  304. /**
  305. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  306. */
  307. Color3.prototype.subtract = function (otherColor) {
  308. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  309. };
  310. /**
  311. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  312. * Returns the unmodified current Color3.
  313. */
  314. Color3.prototype.subtractToRef = function (otherColor, result) {
  315. result.r = this.r - otherColor.r;
  316. result.g = this.g - otherColor.g;
  317. result.b = this.b - otherColor.b;
  318. return this;
  319. };
  320. /**
  321. * Returns a new Color3 copied the current one.
  322. */
  323. Color3.prototype.clone = function () {
  324. return new Color3(this.r, this.g, this.b);
  325. };
  326. /**
  327. * Copies the rgb values from the source in the current Color3.
  328. * Returns the updated Color3.
  329. */
  330. Color3.prototype.copyFrom = function (source) {
  331. this.r = source.r;
  332. this.g = source.g;
  333. this.b = source.b;
  334. return this;
  335. };
  336. /**
  337. * Updates the Color3 rgb values from the passed floats.
  338. * Returns the Color3.
  339. */
  340. Color3.prototype.copyFromFloats = function (r, g, b) {
  341. this.r = r;
  342. this.g = g;
  343. this.b = b;
  344. return this;
  345. };
  346. /**
  347. * Updates the Color3 rgb values from the passed floats.
  348. * Returns the Color3.
  349. */
  350. Color3.prototype.set = function (r, g, b) {
  351. return this.copyFromFloats(r, g, b);
  352. };
  353. /**
  354. * Returns the Color3 hexadecimal code as a string.
  355. */
  356. Color3.prototype.toHexString = function () {
  357. var intR = (this.r * 255) | 0;
  358. var intG = (this.g * 255) | 0;
  359. var intB = (this.b * 255) | 0;
  360. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  361. };
  362. /**
  363. * Returns a new Color3 converted to linear space.
  364. */
  365. Color3.prototype.toLinearSpace = function () {
  366. var convertedColor = new Color3();
  367. this.toLinearSpaceToRef(convertedColor);
  368. return convertedColor;
  369. };
  370. /**
  371. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  372. * Returns the unmodified Color3.
  373. */
  374. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  375. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  376. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  377. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  378. return this;
  379. };
  380. /**
  381. * Returns a new Color3 converted to gamma space.
  382. */
  383. Color3.prototype.toGammaSpace = function () {
  384. var convertedColor = new Color3();
  385. this.toGammaSpaceToRef(convertedColor);
  386. return convertedColor;
  387. };
  388. /**
  389. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  390. * Returns the unmodified Color3.
  391. */
  392. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  393. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  394. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  395. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  396. return this;
  397. };
  398. // Statics
  399. /**
  400. * Creates a new Color3 from the string containing valid hexadecimal values.
  401. */
  402. Color3.FromHexString = function (hex) {
  403. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  404. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  405. return new Color3(0, 0, 0);
  406. }
  407. var r = parseInt(hex.substring(1, 3), 16);
  408. var g = parseInt(hex.substring(3, 5), 16);
  409. var b = parseInt(hex.substring(5, 7), 16);
  410. return Color3.FromInts(r, g, b);
  411. };
  412. /**
  413. * Creates a new Vector3 from the startind index of the passed array.
  414. */
  415. Color3.FromArray = function (array, offset) {
  416. if (offset === void 0) { offset = 0; }
  417. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  418. };
  419. /**
  420. * Creates a new Color3 from integer values ( < 256).
  421. */
  422. Color3.FromInts = function (r, g, b) {
  423. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  424. };
  425. /**
  426. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  427. */
  428. Color3.Lerp = function (start, end, amount) {
  429. var r = start.r + ((end.r - start.r) * amount);
  430. var g = start.g + ((end.g - start.g) * amount);
  431. var b = start.b + ((end.b - start.b) * amount);
  432. return new Color3(r, g, b);
  433. };
  434. Color3.Red = function () { return new Color3(1, 0, 0); };
  435. Color3.Green = function () { return new Color3(0, 1, 0); };
  436. Color3.Blue = function () { return new Color3(0, 0, 1); };
  437. Color3.Black = function () { return new Color3(0, 0, 0); };
  438. Color3.White = function () { return new Color3(1, 1, 1); };
  439. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  440. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  441. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  442. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  443. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  444. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  445. return Color3;
  446. }());
  447. BABYLON.Color3 = Color3;
  448. var Color4 = /** @class */ (function () {
  449. /**
  450. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  451. */
  452. function Color4(r, g, b, a) {
  453. if (r === void 0) { r = 0; }
  454. if (g === void 0) { g = 0; }
  455. if (b === void 0) { b = 0; }
  456. if (a === void 0) { a = 1; }
  457. this.r = r;
  458. this.g = g;
  459. this.b = b;
  460. this.a = a;
  461. }
  462. // Operators
  463. /**
  464. * Adds in place the passed Color4 values to the current Color4.
  465. * Returns the updated Color4.
  466. */
  467. Color4.prototype.addInPlace = function (right) {
  468. this.r += right.r;
  469. this.g += right.g;
  470. this.b += right.b;
  471. this.a += right.a;
  472. return this;
  473. };
  474. /**
  475. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  476. */
  477. Color4.prototype.asArray = function () {
  478. var result = new Array();
  479. this.toArray(result, 0);
  480. return result;
  481. };
  482. /**
  483. * Stores from the starting index in the passed array the Color4 successive values.
  484. * Returns the Color4.
  485. */
  486. Color4.prototype.toArray = function (array, index) {
  487. if (index === undefined) {
  488. index = 0;
  489. }
  490. array[index] = this.r;
  491. array[index + 1] = this.g;
  492. array[index + 2] = this.b;
  493. array[index + 3] = this.a;
  494. return this;
  495. };
  496. /**
  497. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  498. */
  499. Color4.prototype.add = function (right) {
  500. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  501. };
  502. /**
  503. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  504. */
  505. Color4.prototype.subtract = function (right) {
  506. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  507. };
  508. /**
  509. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  510. * Returns the Color4.
  511. */
  512. Color4.prototype.subtractToRef = function (right, result) {
  513. result.r = this.r - right.r;
  514. result.g = this.g - right.g;
  515. result.b = this.b - right.b;
  516. result.a = this.a - right.a;
  517. return this;
  518. };
  519. /**
  520. * Creates a new Color4 with the current Color4 values multiplied by scale.
  521. */
  522. Color4.prototype.scale = function (scale) {
  523. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  524. };
  525. /**
  526. * Multiplies the current Color4 values by scale and stores the result in "result".
  527. * Returns the Color4.
  528. */
  529. Color4.prototype.scaleToRef = function (scale, result) {
  530. result.r = this.r * scale;
  531. result.g = this.g * scale;
  532. result.b = this.b * scale;
  533. result.a = this.a * scale;
  534. return this;
  535. };
  536. /**
  537. * Multipy an RGBA Color4 value by another and return a new Color4 object
  538. * @param color The Color4 (RGBA) value to multiply by
  539. * @returns A new Color4.
  540. */
  541. Color4.prototype.multiply = function (color) {
  542. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  543. };
  544. /**
  545. * Multipy an RGBA Color4 value by another and push the result in a reference value
  546. * @param color The Color4 (RGBA) value to multiply by
  547. * @param result The Color4 (RGBA) to fill the result in
  548. * @returns the result Color4.
  549. */
  550. Color4.prototype.multiplyToRef = function (color, result) {
  551. result.r = this.r * color.r;
  552. result.g = this.g * color.g;
  553. result.b = this.b * color.b;
  554. result.a = this.a * color.a;
  555. return result;
  556. };
  557. /**
  558. * Returns a string with the Color4 values.
  559. */
  560. Color4.prototype.toString = function () {
  561. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  562. };
  563. /**
  564. * Returns the string "Color4"
  565. */
  566. Color4.prototype.getClassName = function () {
  567. return "Color4";
  568. };
  569. /**
  570. * Return the Color4 hash code as a number.
  571. */
  572. Color4.prototype.getHashCode = function () {
  573. var hash = this.r || 0;
  574. hash = (hash * 397) ^ (this.g || 0);
  575. hash = (hash * 397) ^ (this.b || 0);
  576. hash = (hash * 397) ^ (this.a || 0);
  577. return hash;
  578. };
  579. /**
  580. * Creates a new Color4 copied from the current one.
  581. */
  582. Color4.prototype.clone = function () {
  583. return new Color4(this.r, this.g, this.b, this.a);
  584. };
  585. /**
  586. * Copies the passed Color4 values into the current one.
  587. * Returns the updated Color4.
  588. */
  589. Color4.prototype.copyFrom = function (source) {
  590. this.r = source.r;
  591. this.g = source.g;
  592. this.b = source.b;
  593. this.a = source.a;
  594. return this;
  595. };
  596. /**
  597. * Copies the passed float values into the current one.
  598. * Returns the updated Color4.
  599. */
  600. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  601. this.r = r;
  602. this.g = g;
  603. this.b = b;
  604. this.a = a;
  605. return this;
  606. };
  607. /**
  608. * Copies the passed float values into the current one.
  609. * Returns the updated Color4.
  610. */
  611. Color4.prototype.set = function (r, g, b, a) {
  612. return this.copyFromFloats(r, g, b, a);
  613. };
  614. /**
  615. * Returns a string containing the hexadecimal Color4 code.
  616. */
  617. Color4.prototype.toHexString = function () {
  618. var intR = (this.r * 255) | 0;
  619. var intG = (this.g * 255) | 0;
  620. var intB = (this.b * 255) | 0;
  621. var intA = (this.a * 255) | 0;
  622. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  623. };
  624. /**
  625. * Returns a new Color4 converted to linear space.
  626. */
  627. Color4.prototype.toLinearSpace = function () {
  628. var convertedColor = new Color4();
  629. this.toLinearSpaceToRef(convertedColor);
  630. return convertedColor;
  631. };
  632. /**
  633. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  634. * Returns the unmodified Color4.
  635. */
  636. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  637. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  638. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  639. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  640. convertedColor.a = this.a;
  641. return this;
  642. };
  643. /**
  644. * Returns a new Color4 converted to gamma space.
  645. */
  646. Color4.prototype.toGammaSpace = function () {
  647. var convertedColor = new Color4();
  648. this.toGammaSpaceToRef(convertedColor);
  649. return convertedColor;
  650. };
  651. /**
  652. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  653. * Returns the unmodified Color4.
  654. */
  655. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  656. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  657. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  658. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  659. convertedColor.a = this.a;
  660. return this;
  661. };
  662. // Statics
  663. /**
  664. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  665. */
  666. Color4.FromHexString = function (hex) {
  667. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  668. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  669. return new Color4(0.0, 0.0, 0.0, 0.0);
  670. }
  671. var r = parseInt(hex.substring(1, 3), 16);
  672. var g = parseInt(hex.substring(3, 5), 16);
  673. var b = parseInt(hex.substring(5, 7), 16);
  674. var a = parseInt(hex.substring(7, 9), 16);
  675. return Color4.FromInts(r, g, b, a);
  676. };
  677. /**
  678. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  679. */
  680. Color4.Lerp = function (left, right, amount) {
  681. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  682. Color4.LerpToRef(left, right, amount, result);
  683. return result;
  684. };
  685. /**
  686. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  687. */
  688. Color4.LerpToRef = function (left, right, amount, result) {
  689. result.r = left.r + (right.r - left.r) * amount;
  690. result.g = left.g + (right.g - left.g) * amount;
  691. result.b = left.b + (right.b - left.b) * amount;
  692. result.a = left.a + (right.a - left.a) * amount;
  693. };
  694. /**
  695. * Creates a new Color4 from the starting index element of the passed array.
  696. */
  697. Color4.FromArray = function (array, offset) {
  698. if (offset === void 0) { offset = 0; }
  699. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  700. };
  701. /**
  702. * Creates a new Color4 from the passed integers ( < 256 ).
  703. */
  704. Color4.FromInts = function (r, g, b, a) {
  705. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  706. };
  707. Color4.CheckColors4 = function (colors, count) {
  708. // Check if color3 was used
  709. if (colors.length === count * 3) {
  710. var colors4 = [];
  711. for (var index = 0; index < colors.length; index += 3) {
  712. var newIndex = (index / 3) * 4;
  713. colors4[newIndex] = colors[index];
  714. colors4[newIndex + 1] = colors[index + 1];
  715. colors4[newIndex + 2] = colors[index + 2];
  716. colors4[newIndex + 3] = 1.0;
  717. }
  718. return colors4;
  719. }
  720. return colors;
  721. };
  722. return Color4;
  723. }());
  724. BABYLON.Color4 = Color4;
  725. var Vector2 = /** @class */ (function () {
  726. /**
  727. * Creates a new Vector2 from the passed x and y coordinates.
  728. */
  729. function Vector2(x, y) {
  730. this.x = x;
  731. this.y = y;
  732. }
  733. /**
  734. * Returns a string with the Vector2 coordinates.
  735. */
  736. Vector2.prototype.toString = function () {
  737. return "{X: " + this.x + " Y:" + this.y + "}";
  738. };
  739. /**
  740. * Returns the string "Vector2"
  741. */
  742. Vector2.prototype.getClassName = function () {
  743. return "Vector2";
  744. };
  745. /**
  746. * Returns the Vector2 hash code as a number.
  747. */
  748. Vector2.prototype.getHashCode = function () {
  749. var hash = this.x || 0;
  750. hash = (hash * 397) ^ (this.y || 0);
  751. return hash;
  752. };
  753. // Operators
  754. /**
  755. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  756. * Returns the Vector2.
  757. */
  758. Vector2.prototype.toArray = function (array, index) {
  759. if (index === void 0) { index = 0; }
  760. array[index] = this.x;
  761. array[index + 1] = this.y;
  762. return this;
  763. };
  764. /**
  765. * Returns a new array with 2 elements : the Vector2 coordinates.
  766. */
  767. Vector2.prototype.asArray = function () {
  768. var result = new Array();
  769. this.toArray(result, 0);
  770. return result;
  771. };
  772. /**
  773. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  774. * Returns the updated Vector2.
  775. */
  776. Vector2.prototype.copyFrom = function (source) {
  777. this.x = source.x;
  778. this.y = source.y;
  779. return this;
  780. };
  781. /**
  782. * Sets the Vector2 coordinates with the passed floats.
  783. * Returns the updated Vector2.
  784. */
  785. Vector2.prototype.copyFromFloats = function (x, y) {
  786. this.x = x;
  787. this.y = y;
  788. return this;
  789. };
  790. /**
  791. * Sets the Vector2 coordinates with the passed floats.
  792. * Returns the updated Vector2.
  793. */
  794. Vector2.prototype.set = function (x, y) {
  795. return this.copyFromFloats(x, y);
  796. };
  797. /**
  798. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  799. */
  800. Vector2.prototype.add = function (otherVector) {
  801. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  802. };
  803. /**
  804. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  805. * Returns the Vector2.
  806. */
  807. Vector2.prototype.addToRef = function (otherVector, result) {
  808. result.x = this.x + otherVector.x;
  809. result.y = this.y + otherVector.y;
  810. return this;
  811. };
  812. /**
  813. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  814. * Returns the updated Vector2.
  815. */
  816. Vector2.prototype.addInPlace = function (otherVector) {
  817. this.x += otherVector.x;
  818. this.y += otherVector.y;
  819. return this;
  820. };
  821. /**
  822. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  823. */
  824. Vector2.prototype.addVector3 = function (otherVector) {
  825. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  826. };
  827. /**
  828. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  829. */
  830. Vector2.prototype.subtract = function (otherVector) {
  831. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  832. };
  833. /**
  834. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  835. * Returns the Vector2.
  836. */
  837. Vector2.prototype.subtractToRef = function (otherVector, result) {
  838. result.x = this.x - otherVector.x;
  839. result.y = this.y - otherVector.y;
  840. return this;
  841. };
  842. /**
  843. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  844. * Returns the updated Vector2.
  845. */
  846. Vector2.prototype.subtractInPlace = function (otherVector) {
  847. this.x -= otherVector.x;
  848. this.y -= otherVector.y;
  849. return this;
  850. };
  851. /**
  852. * Multiplies in place the current Vector2 coordinates by the passed ones.
  853. * Returns the updated Vector2.
  854. */
  855. Vector2.prototype.multiplyInPlace = function (otherVector) {
  856. this.x *= otherVector.x;
  857. this.y *= otherVector.y;
  858. return this;
  859. };
  860. /**
  861. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  862. */
  863. Vector2.prototype.multiply = function (otherVector) {
  864. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  865. };
  866. /**
  867. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  868. * Returns the Vector2.
  869. */
  870. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  871. result.x = this.x * otherVector.x;
  872. result.y = this.y * otherVector.y;
  873. return this;
  874. };
  875. /**
  876. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  877. */
  878. Vector2.prototype.multiplyByFloats = function (x, y) {
  879. return new Vector2(this.x * x, this.y * y);
  880. };
  881. /**
  882. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  883. */
  884. Vector2.prototype.divide = function (otherVector) {
  885. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  886. };
  887. /**
  888. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  889. * Returns the Vector2.
  890. */
  891. Vector2.prototype.divideToRef = function (otherVector, result) {
  892. result.x = this.x / otherVector.x;
  893. result.y = this.y / otherVector.y;
  894. return this;
  895. };
  896. /**
  897. * Returns a new Vector2 with current Vector2 negated coordinates.
  898. */
  899. Vector2.prototype.negate = function () {
  900. return new Vector2(-this.x, -this.y);
  901. };
  902. /**
  903. * Multiply the Vector2 coordinates by scale.
  904. * Returns the updated Vector2.
  905. */
  906. Vector2.prototype.scaleInPlace = function (scale) {
  907. this.x *= scale;
  908. this.y *= scale;
  909. return this;
  910. };
  911. /**
  912. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  913. */
  914. Vector2.prototype.scale = function (scale) {
  915. return new Vector2(this.x * scale, this.y * scale);
  916. };
  917. /**
  918. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  919. */
  920. Vector2.prototype.equals = function (otherVector) {
  921. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  922. };
  923. /**
  924. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  925. */
  926. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  927. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  928. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  929. };
  930. // Properties
  931. /**
  932. * Returns the vector length (float).
  933. */
  934. Vector2.prototype.length = function () {
  935. return Math.sqrt(this.x * this.x + this.y * this.y);
  936. };
  937. /**
  938. * Returns the vector squared length (float);
  939. */
  940. Vector2.prototype.lengthSquared = function () {
  941. return (this.x * this.x + this.y * this.y);
  942. };
  943. // Methods
  944. /**
  945. * Normalize the vector.
  946. * Returns the updated Vector2.
  947. */
  948. Vector2.prototype.normalize = function () {
  949. var len = this.length();
  950. if (len === 0)
  951. return this;
  952. var num = 1.0 / len;
  953. this.x *= num;
  954. this.y *= num;
  955. return this;
  956. };
  957. /**
  958. * Returns a new Vector2 copied from the Vector2.
  959. */
  960. Vector2.prototype.clone = function () {
  961. return new Vector2(this.x, this.y);
  962. };
  963. // Statics
  964. /**
  965. * Returns a new Vector2(0, 0)
  966. */
  967. Vector2.Zero = function () {
  968. return new Vector2(0, 0);
  969. };
  970. /**
  971. * Returns a new Vector2(1, 1)
  972. */
  973. Vector2.One = function () {
  974. return new Vector2(1, 1);
  975. };
  976. /**
  977. * Returns a new Vector2 set from the passed index element of the passed array.
  978. */
  979. Vector2.FromArray = function (array, offset) {
  980. if (offset === void 0) { offset = 0; }
  981. return new Vector2(array[offset], array[offset + 1]);
  982. };
  983. /**
  984. * Sets "result" from the passed index element of the passed array.
  985. */
  986. Vector2.FromArrayToRef = function (array, offset, result) {
  987. result.x = array[offset];
  988. result.y = array[offset + 1];
  989. };
  990. /**
  991. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  992. */
  993. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  994. var squared = amount * amount;
  995. var cubed = amount * squared;
  996. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  997. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  998. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  999. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1000. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1001. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1002. return new Vector2(x, y);
  1003. };
  1004. /**
  1005. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  1006. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1007. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1008. */
  1009. Vector2.Clamp = function (value, min, max) {
  1010. var x = value.x;
  1011. x = (x > max.x) ? max.x : x;
  1012. x = (x < min.x) ? min.x : x;
  1013. var y = value.y;
  1014. y = (y > max.y) ? max.y : y;
  1015. y = (y < min.y) ? min.y : y;
  1016. return new Vector2(x, y);
  1017. };
  1018. /**
  1019. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1020. */
  1021. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1022. var squared = amount * amount;
  1023. var cubed = amount * squared;
  1024. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1025. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1026. var part3 = (cubed - (2.0 * squared)) + amount;
  1027. var part4 = cubed - squared;
  1028. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1029. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1030. return new Vector2(x, y);
  1031. };
  1032. /**
  1033. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1034. */
  1035. Vector2.Lerp = function (start, end, amount) {
  1036. var x = start.x + ((end.x - start.x) * amount);
  1037. var y = start.y + ((end.y - start.y) * amount);
  1038. return new Vector2(x, y);
  1039. };
  1040. /**
  1041. * Returns the dot product (float) of the vector "left" and the vector "right".
  1042. */
  1043. Vector2.Dot = function (left, right) {
  1044. return left.x * right.x + left.y * right.y;
  1045. };
  1046. /**
  1047. * Returns a new Vector2 equal to the normalized passed vector.
  1048. */
  1049. Vector2.Normalize = function (vector) {
  1050. var newVector = vector.clone();
  1051. newVector.normalize();
  1052. return newVector;
  1053. };
  1054. /**
  1055. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1056. */
  1057. Vector2.Minimize = function (left, right) {
  1058. var x = (left.x < right.x) ? left.x : right.x;
  1059. var y = (left.y < right.y) ? left.y : right.y;
  1060. return new Vector2(x, y);
  1061. };
  1062. /**
  1063. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1064. */
  1065. Vector2.Maximize = function (left, right) {
  1066. var x = (left.x > right.x) ? left.x : right.x;
  1067. var y = (left.y > right.y) ? left.y : right.y;
  1068. return new Vector2(x, y);
  1069. };
  1070. /**
  1071. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1072. */
  1073. Vector2.Transform = function (vector, transformation) {
  1074. var r = Vector2.Zero();
  1075. Vector2.TransformToRef(vector, transformation, r);
  1076. return r;
  1077. };
  1078. /**
  1079. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1080. */
  1081. Vector2.TransformToRef = function (vector, transformation, result) {
  1082. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1083. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1084. result.x = x;
  1085. result.y = y;
  1086. };
  1087. /**
  1088. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1089. */
  1090. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1091. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1092. var sign = a < 0 ? -1 : 1;
  1093. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1094. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1095. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1096. };
  1097. /**
  1098. * Returns the distance (float) between the vectors "value1" and "value2".
  1099. */
  1100. Vector2.Distance = function (value1, value2) {
  1101. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1102. };
  1103. /**
  1104. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1105. */
  1106. Vector2.DistanceSquared = function (value1, value2) {
  1107. var x = value1.x - value2.x;
  1108. var y = value1.y - value2.y;
  1109. return (x * x) + (y * y);
  1110. };
  1111. /**
  1112. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1113. */
  1114. Vector2.Center = function (value1, value2) {
  1115. var center = value1.add(value2);
  1116. center.scaleInPlace(0.5);
  1117. return center;
  1118. };
  1119. /**
  1120. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1121. */
  1122. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1123. var l2 = Vector2.DistanceSquared(segA, segB);
  1124. if (l2 === 0.0) {
  1125. return Vector2.Distance(p, segA);
  1126. }
  1127. var v = segB.subtract(segA);
  1128. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1129. var proj = segA.add(v.multiplyByFloats(t, t));
  1130. return Vector2.Distance(p, proj);
  1131. };
  1132. return Vector2;
  1133. }());
  1134. BABYLON.Vector2 = Vector2;
  1135. var Vector3 = /** @class */ (function () {
  1136. /**
  1137. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1138. * A Vector3 is the main object used in 3D geometry.
  1139. * It can represent etiher the coordinates of a point the space, either a direction.
  1140. */
  1141. function Vector3(x, y, z) {
  1142. this.x = x;
  1143. this.y = y;
  1144. this.z = z;
  1145. }
  1146. /**
  1147. * Returns a string with the Vector3 coordinates.
  1148. */
  1149. Vector3.prototype.toString = function () {
  1150. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1151. };
  1152. /**
  1153. * Returns the string "Vector3"
  1154. */
  1155. Vector3.prototype.getClassName = function () {
  1156. return "Vector3";
  1157. };
  1158. /**
  1159. * Returns the Vector hash code.
  1160. */
  1161. Vector3.prototype.getHashCode = function () {
  1162. var hash = this.x || 0;
  1163. hash = (hash * 397) ^ (this.y || 0);
  1164. hash = (hash * 397) ^ (this.z || 0);
  1165. return hash;
  1166. };
  1167. // Operators
  1168. /**
  1169. * Returns a new array with three elements : the coordinates the Vector3.
  1170. */
  1171. Vector3.prototype.asArray = function () {
  1172. var result = [];
  1173. this.toArray(result, 0);
  1174. return result;
  1175. };
  1176. /**
  1177. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1178. * Returns the Vector3.
  1179. */
  1180. Vector3.prototype.toArray = function (array, index) {
  1181. if (index === void 0) { index = 0; }
  1182. array[index] = this.x;
  1183. array[index + 1] = this.y;
  1184. array[index + 2] = this.z;
  1185. return this;
  1186. };
  1187. /**
  1188. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1189. */
  1190. Vector3.prototype.toQuaternion = function () {
  1191. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1192. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1193. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1194. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1195. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1196. var cosy = Math.cos(this.y * 0.5);
  1197. var siny = Math.sin(this.y * 0.5);
  1198. result.x = coszMinusx * siny;
  1199. result.y = -sinzMinusx * siny;
  1200. result.z = sinxPlusz * cosy;
  1201. result.w = cosxPlusz * cosy;
  1202. return result;
  1203. };
  1204. /**
  1205. * Adds the passed vector to the current Vector3.
  1206. * Returns the updated Vector3.
  1207. */
  1208. Vector3.prototype.addInPlace = function (otherVector) {
  1209. this.x += otherVector.x;
  1210. this.y += otherVector.y;
  1211. this.z += otherVector.z;
  1212. return this;
  1213. };
  1214. /**
  1215. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1216. */
  1217. Vector3.prototype.add = function (otherVector) {
  1218. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1219. };
  1220. /**
  1221. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1222. * Returns the current Vector3.
  1223. */
  1224. Vector3.prototype.addToRef = function (otherVector, result) {
  1225. result.x = this.x + otherVector.x;
  1226. result.y = this.y + otherVector.y;
  1227. result.z = this.z + otherVector.z;
  1228. return this;
  1229. };
  1230. /**
  1231. * Subtract the passed vector from the current Vector3.
  1232. * Returns the updated Vector3.
  1233. */
  1234. Vector3.prototype.subtractInPlace = function (otherVector) {
  1235. this.x -= otherVector.x;
  1236. this.y -= otherVector.y;
  1237. this.z -= otherVector.z;
  1238. return this;
  1239. };
  1240. /**
  1241. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1242. */
  1243. Vector3.prototype.subtract = function (otherVector) {
  1244. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1245. };
  1246. /**
  1247. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1248. * Returns the current Vector3.
  1249. */
  1250. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1251. result.x = this.x - otherVector.x;
  1252. result.y = this.y - otherVector.y;
  1253. result.z = this.z - otherVector.z;
  1254. return this;
  1255. };
  1256. /**
  1257. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1258. */
  1259. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1260. return new Vector3(this.x - x, this.y - y, this.z - z);
  1261. };
  1262. /**
  1263. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1264. * Returns the current Vector3.
  1265. */
  1266. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1267. result.x = this.x - x;
  1268. result.y = this.y - y;
  1269. result.z = this.z - z;
  1270. return this;
  1271. };
  1272. /**
  1273. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1274. */
  1275. Vector3.prototype.negate = function () {
  1276. return new Vector3(-this.x, -this.y, -this.z);
  1277. };
  1278. /**
  1279. * Multiplies the Vector3 coordinates by the float "scale".
  1280. * Returns the updated Vector3.
  1281. */
  1282. Vector3.prototype.scaleInPlace = function (scale) {
  1283. this.x *= scale;
  1284. this.y *= scale;
  1285. this.z *= scale;
  1286. return this;
  1287. };
  1288. /**
  1289. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1290. */
  1291. Vector3.prototype.scale = function (scale) {
  1292. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1293. };
  1294. /**
  1295. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1296. * Returns the current Vector3.
  1297. */
  1298. Vector3.prototype.scaleToRef = function (scale, result) {
  1299. result.x = this.x * scale;
  1300. result.y = this.y * scale;
  1301. result.z = this.z * scale;
  1302. return this;
  1303. };
  1304. /**
  1305. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1306. */
  1307. Vector3.prototype.equals = function (otherVector) {
  1308. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1309. };
  1310. /**
  1311. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1312. */
  1313. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1314. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1315. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  1316. };
  1317. /**
  1318. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1319. */
  1320. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1321. return this.x === x && this.y === y && this.z === z;
  1322. };
  1323. /**
  1324. * Muliplies the current Vector3 coordinates by the passed ones.
  1325. * Returns the updated Vector3.
  1326. */
  1327. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1328. this.x *= otherVector.x;
  1329. this.y *= otherVector.y;
  1330. this.z *= otherVector.z;
  1331. return this;
  1332. };
  1333. /**
  1334. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1335. */
  1336. Vector3.prototype.multiply = function (otherVector) {
  1337. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1338. };
  1339. /**
  1340. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1341. * Returns the current Vector3.
  1342. */
  1343. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1344. result.x = this.x * otherVector.x;
  1345. result.y = this.y * otherVector.y;
  1346. result.z = this.z * otherVector.z;
  1347. return this;
  1348. };
  1349. /**
  1350. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1351. */
  1352. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1353. return new Vector3(this.x * x, this.y * y, this.z * z);
  1354. };
  1355. /**
  1356. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1357. */
  1358. Vector3.prototype.divide = function (otherVector) {
  1359. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1360. };
  1361. /**
  1362. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1363. * Returns the current Vector3.
  1364. */
  1365. Vector3.prototype.divideToRef = function (otherVector, result) {
  1366. result.x = this.x / otherVector.x;
  1367. result.y = this.y / otherVector.y;
  1368. result.z = this.z / otherVector.z;
  1369. return this;
  1370. };
  1371. /**
  1372. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1373. * Returns the updated Vector3.
  1374. */
  1375. Vector3.prototype.MinimizeInPlace = function (other) {
  1376. if (other.x < this.x)
  1377. this.x = other.x;
  1378. if (other.y < this.y)
  1379. this.y = other.y;
  1380. if (other.z < this.z)
  1381. this.z = other.z;
  1382. return this;
  1383. };
  1384. /**
  1385. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1386. * Returns the updated Vector3.
  1387. */
  1388. Vector3.prototype.MaximizeInPlace = function (other) {
  1389. if (other.x > this.x)
  1390. this.x = other.x;
  1391. if (other.y > this.y)
  1392. this.y = other.y;
  1393. if (other.z > this.z)
  1394. this.z = other.z;
  1395. return this;
  1396. };
  1397. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  1398. /**
  1399. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  1400. */
  1401. get: function () {
  1402. var absX = Math.abs(this.x);
  1403. var absY = Math.abs(this.y);
  1404. if (absX !== absY) {
  1405. return true;
  1406. }
  1407. var absZ = Math.abs(this.z);
  1408. if (absX !== absZ) {
  1409. return true;
  1410. }
  1411. if (absY !== absZ) {
  1412. return true;
  1413. }
  1414. return false;
  1415. },
  1416. enumerable: true,
  1417. configurable: true
  1418. });
  1419. // Properties
  1420. /**
  1421. * Returns the length of the Vector3 (float).
  1422. */
  1423. Vector3.prototype.length = function () {
  1424. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1425. };
  1426. /**
  1427. * Returns the squared length of the Vector3 (float).
  1428. */
  1429. Vector3.prototype.lengthSquared = function () {
  1430. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1431. };
  1432. /**
  1433. * Normalize the current Vector3.
  1434. * Returns the updated Vector3.
  1435. * /!\ In place operation.
  1436. */
  1437. Vector3.prototype.normalize = function () {
  1438. var len = this.length();
  1439. if (len === 0 || len === 1.0)
  1440. return this;
  1441. var num = 1.0 / len;
  1442. this.x *= num;
  1443. this.y *= num;
  1444. this.z *= num;
  1445. return this;
  1446. };
  1447. /**
  1448. * Normalize the current Vector3 to a new vector.
  1449. * @returns the new Vector3.
  1450. */
  1451. Vector3.prototype.normalizeToNew = function () {
  1452. var normalized = new Vector3(0, 0, 0);
  1453. this.normalizeToRef(normalized);
  1454. return normalized;
  1455. };
  1456. /**
  1457. * Normalize the current Vector3 to the reference.
  1458. * @param the reference to update.
  1459. * @returns the updated Vector3.
  1460. */
  1461. Vector3.prototype.normalizeToRef = function (reference) {
  1462. var len = this.length();
  1463. if (len === 0 || len === 1.0) {
  1464. reference.set(this.x, this.y, this.z);
  1465. return reference;
  1466. }
  1467. var scale = 1.0 / len;
  1468. this.scaleToRef(scale, reference);
  1469. return reference;
  1470. };
  1471. /**
  1472. * Returns a new Vector3 copied from the current Vector3.
  1473. */
  1474. Vector3.prototype.clone = function () {
  1475. return new Vector3(this.x, this.y, this.z);
  1476. };
  1477. /**
  1478. * Copies the passed vector coordinates to the current Vector3 ones.
  1479. * Returns the updated Vector3.
  1480. */
  1481. Vector3.prototype.copyFrom = function (source) {
  1482. this.x = source.x;
  1483. this.y = source.y;
  1484. this.z = source.z;
  1485. return this;
  1486. };
  1487. /**
  1488. * Copies the passed floats to the current Vector3 coordinates.
  1489. * Returns the updated Vector3.
  1490. */
  1491. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1492. this.x = x;
  1493. this.y = y;
  1494. this.z = z;
  1495. return this;
  1496. };
  1497. /**
  1498. * Copies the passed floats to the current Vector3 coordinates.
  1499. * Returns the updated Vector3.
  1500. */
  1501. Vector3.prototype.set = function (x, y, z) {
  1502. return this.copyFromFloats(x, y, z);
  1503. };
  1504. // Statics
  1505. /**
  1506. *
  1507. */
  1508. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1509. var d0 = Vector3.Dot(vector0, axis) - size;
  1510. var d1 = Vector3.Dot(vector1, axis) - size;
  1511. var s = d0 / (d0 - d1);
  1512. return s;
  1513. };
  1514. /**
  1515. * Returns a new Vector3 set from the index "offset" of the passed array.
  1516. */
  1517. Vector3.FromArray = function (array, offset) {
  1518. if (!offset) {
  1519. offset = 0;
  1520. }
  1521. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1522. };
  1523. /**
  1524. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1525. * This function is deprecated. Use FromArray instead.
  1526. */
  1527. Vector3.FromFloatArray = function (array, offset) {
  1528. return Vector3.FromArray(array, offset);
  1529. };
  1530. /**
  1531. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1532. */
  1533. Vector3.FromArrayToRef = function (array, offset, result) {
  1534. result.x = array[offset];
  1535. result.y = array[offset + 1];
  1536. result.z = array[offset + 2];
  1537. };
  1538. /**
  1539. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1540. * This function is deprecated. Use FromArrayToRef instead.
  1541. */
  1542. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1543. return Vector3.FromArrayToRef(array, offset, result);
  1544. };
  1545. /**
  1546. * Sets the passed vector "result" with the passed floats.
  1547. */
  1548. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1549. result.x = x;
  1550. result.y = y;
  1551. result.z = z;
  1552. };
  1553. /**
  1554. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1555. */
  1556. Vector3.Zero = function () {
  1557. return new Vector3(0.0, 0.0, 0.0);
  1558. };
  1559. /**
  1560. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1561. */
  1562. Vector3.One = function () {
  1563. return new Vector3(1.0, 1.0, 1.0);
  1564. };
  1565. /**
  1566. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1567. */
  1568. Vector3.Up = function () {
  1569. return new Vector3(0.0, 1.0, 0.0);
  1570. };
  1571. /**
  1572. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1573. */
  1574. Vector3.Forward = function () {
  1575. return new Vector3(0.0, 0.0, 1.0);
  1576. };
  1577. /**
  1578. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1579. */
  1580. Vector3.Right = function () {
  1581. return new Vector3(1.0, 0.0, 0.0);
  1582. };
  1583. /**
  1584. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1585. */
  1586. Vector3.Left = function () {
  1587. return new Vector3(-1.0, 0.0, 0.0);
  1588. };
  1589. /**
  1590. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1591. * This method computes tranformed coordinates only, not transformed direction vectors.
  1592. */
  1593. Vector3.TransformCoordinates = function (vector, transformation) {
  1594. var result = Vector3.Zero();
  1595. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1596. return result;
  1597. };
  1598. /**
  1599. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1600. * This method computes tranformed coordinates only, not transformed direction vectors.
  1601. */
  1602. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1603. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1604. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1605. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1606. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1607. result.x = x / w;
  1608. result.y = y / w;
  1609. result.z = z / w;
  1610. };
  1611. /**
  1612. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1613. * This method computes tranformed coordinates only, not transformed direction vectors.
  1614. */
  1615. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1616. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1617. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1618. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1619. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1620. result.x = rx / rw;
  1621. result.y = ry / rw;
  1622. result.z = rz / rw;
  1623. };
  1624. /**
  1625. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1626. * This methods computes transformed normalized direction vectors only.
  1627. */
  1628. Vector3.TransformNormal = function (vector, transformation) {
  1629. var result = Vector3.Zero();
  1630. Vector3.TransformNormalToRef(vector, transformation, result);
  1631. return result;
  1632. };
  1633. /**
  1634. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1635. * This methods computes transformed normalized direction vectors only.
  1636. */
  1637. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1638. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1639. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1640. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1641. result.x = x;
  1642. result.y = y;
  1643. result.z = z;
  1644. };
  1645. /**
  1646. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1647. * This methods computes transformed normalized direction vectors only.
  1648. */
  1649. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1650. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1651. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1652. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1653. };
  1654. /**
  1655. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1656. */
  1657. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1658. var squared = amount * amount;
  1659. var cubed = amount * squared;
  1660. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1661. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1662. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1663. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1664. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1665. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1666. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1667. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1668. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1669. return new Vector3(x, y, z);
  1670. };
  1671. /**
  1672. * 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".
  1673. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1674. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1675. */
  1676. Vector3.Clamp = function (value, min, max) {
  1677. var x = value.x;
  1678. x = (x > max.x) ? max.x : x;
  1679. x = (x < min.x) ? min.x : x;
  1680. var y = value.y;
  1681. y = (y > max.y) ? max.y : y;
  1682. y = (y < min.y) ? min.y : y;
  1683. var z = value.z;
  1684. z = (z > max.z) ? max.z : z;
  1685. z = (z < min.z) ? min.z : z;
  1686. return new Vector3(x, y, z);
  1687. };
  1688. /**
  1689. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1690. */
  1691. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1692. var squared = amount * amount;
  1693. var cubed = amount * squared;
  1694. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1695. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1696. var part3 = (cubed - (2.0 * squared)) + amount;
  1697. var part4 = cubed - squared;
  1698. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1699. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1700. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1701. return new Vector3(x, y, z);
  1702. };
  1703. /**
  1704. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1705. */
  1706. Vector3.Lerp = function (start, end, amount) {
  1707. var result = new Vector3(0, 0, 0);
  1708. Vector3.LerpToRef(start, end, amount, result);
  1709. return result;
  1710. };
  1711. /**
  1712. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1713. */
  1714. Vector3.LerpToRef = function (start, end, amount, result) {
  1715. result.x = start.x + ((end.x - start.x) * amount);
  1716. result.y = start.y + ((end.y - start.y) * amount);
  1717. result.z = start.z + ((end.z - start.z) * amount);
  1718. };
  1719. /**
  1720. * Returns the dot product (float) between the vectors "left" and "right".
  1721. */
  1722. Vector3.Dot = function (left, right) {
  1723. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1724. };
  1725. /**
  1726. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1727. * The cross product is then orthogonal to both "left" and "right".
  1728. */
  1729. Vector3.Cross = function (left, right) {
  1730. var result = Vector3.Zero();
  1731. Vector3.CrossToRef(left, right, result);
  1732. return result;
  1733. };
  1734. /**
  1735. * Sets the passed vector "result" with the cross product of "left" and "right".
  1736. * The cross product is then orthogonal to both "left" and "right".
  1737. */
  1738. Vector3.CrossToRef = function (left, right, result) {
  1739. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1740. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1741. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1742. result.copyFrom(MathTmp.Vector3[0]);
  1743. };
  1744. /**
  1745. * Returns a new Vector3 as the normalization of the passed vector.
  1746. */
  1747. Vector3.Normalize = function (vector) {
  1748. var result = Vector3.Zero();
  1749. Vector3.NormalizeToRef(vector, result);
  1750. return result;
  1751. };
  1752. /**
  1753. * Sets the passed vector "result" with the normalization of the passed first vector.
  1754. */
  1755. Vector3.NormalizeToRef = function (vector, result) {
  1756. result.copyFrom(vector);
  1757. result.normalize();
  1758. };
  1759. Vector3.Project = function (vector, world, transform, viewport) {
  1760. var cw = viewport.width;
  1761. var ch = viewport.height;
  1762. var cx = viewport.x;
  1763. var cy = viewport.y;
  1764. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1765. 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);
  1766. var matrix = MathTmp.Matrix[0];
  1767. world.multiplyToRef(transform, matrix);
  1768. matrix.multiplyToRef(viewportMatrix, matrix);
  1769. return Vector3.TransformCoordinates(vector, matrix);
  1770. };
  1771. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1772. var matrix = MathTmp.Matrix[0];
  1773. world.multiplyToRef(transform, matrix);
  1774. matrix.invert();
  1775. source.x = source.x / viewportWidth * 2 - 1;
  1776. source.y = -(source.y / viewportHeight * 2 - 1);
  1777. var vector = Vector3.TransformCoordinates(source, matrix);
  1778. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1779. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1780. vector = vector.scale(1.0 / num);
  1781. }
  1782. return vector;
  1783. };
  1784. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1785. var result = Vector3.Zero();
  1786. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  1787. return result;
  1788. };
  1789. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  1790. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  1791. };
  1792. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  1793. var matrix = MathTmp.Matrix[0];
  1794. world.multiplyToRef(view, matrix);
  1795. matrix.multiplyToRef(projection, matrix);
  1796. matrix.invert();
  1797. var screenSource = MathTmp.Vector3[0];
  1798. screenSource.x = sourceX / viewportWidth * 2 - 1;
  1799. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  1800. screenSource.z = 2 * sourceZ - 1.0;
  1801. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  1802. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1803. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1804. result.scaleInPlace(1.0 / num);
  1805. }
  1806. };
  1807. Vector3.Minimize = function (left, right) {
  1808. var min = left.clone();
  1809. min.MinimizeInPlace(right);
  1810. return min;
  1811. };
  1812. Vector3.Maximize = function (left, right) {
  1813. var max = left.clone();
  1814. max.MaximizeInPlace(right);
  1815. return max;
  1816. };
  1817. /**
  1818. * Returns the distance (float) between the vectors "value1" and "value2".
  1819. */
  1820. Vector3.Distance = function (value1, value2) {
  1821. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1822. };
  1823. /**
  1824. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1825. */
  1826. Vector3.DistanceSquared = function (value1, value2) {
  1827. var x = value1.x - value2.x;
  1828. var y = value1.y - value2.y;
  1829. var z = value1.z - value2.z;
  1830. return (x * x) + (y * y) + (z * z);
  1831. };
  1832. /**
  1833. * Returns a new Vector3 located at the center between "value1" and "value2".
  1834. */
  1835. Vector3.Center = function (value1, value2) {
  1836. var center = value1.add(value2);
  1837. center.scaleInPlace(0.5);
  1838. return center;
  1839. };
  1840. /**
  1841. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1842. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1843. * to something in order to rotate it from its local system to the given target system.
  1844. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1845. * Returns a new Vector3.
  1846. */
  1847. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1848. var rotation = Vector3.Zero();
  1849. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1850. return rotation;
  1851. };
  1852. /**
  1853. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1854. */
  1855. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1856. var quat = MathTmp.Quaternion[0];
  1857. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1858. quat.toEulerAnglesToRef(ref);
  1859. };
  1860. return Vector3;
  1861. }());
  1862. BABYLON.Vector3 = Vector3;
  1863. //Vector4 class created for EulerAngle class conversion to Quaternion
  1864. var Vector4 = /** @class */ (function () {
  1865. /**
  1866. * Creates a Vector4 object from the passed floats.
  1867. */
  1868. function Vector4(x, y, z, w) {
  1869. this.x = x;
  1870. this.y = y;
  1871. this.z = z;
  1872. this.w = w;
  1873. }
  1874. /**
  1875. * Returns the string with the Vector4 coordinates.
  1876. */
  1877. Vector4.prototype.toString = function () {
  1878. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1879. };
  1880. /**
  1881. * Returns the string "Vector4".
  1882. */
  1883. Vector4.prototype.getClassName = function () {
  1884. return "Vector4";
  1885. };
  1886. /**
  1887. * Returns the Vector4 hash code.
  1888. */
  1889. Vector4.prototype.getHashCode = function () {
  1890. var hash = this.x || 0;
  1891. hash = (hash * 397) ^ (this.y || 0);
  1892. hash = (hash * 397) ^ (this.z || 0);
  1893. hash = (hash * 397) ^ (this.w || 0);
  1894. return hash;
  1895. };
  1896. // Operators
  1897. /**
  1898. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1899. */
  1900. Vector4.prototype.asArray = function () {
  1901. var result = new Array();
  1902. this.toArray(result, 0);
  1903. return result;
  1904. };
  1905. /**
  1906. * Populates the passed array from the passed index with the Vector4 coordinates.
  1907. * Returns the Vector4.
  1908. */
  1909. Vector4.prototype.toArray = function (array, index) {
  1910. if (index === undefined) {
  1911. index = 0;
  1912. }
  1913. array[index] = this.x;
  1914. array[index + 1] = this.y;
  1915. array[index + 2] = this.z;
  1916. array[index + 3] = this.w;
  1917. return this;
  1918. };
  1919. /**
  1920. * Adds the passed vector to the current Vector4.
  1921. * Returns the updated Vector4.
  1922. */
  1923. Vector4.prototype.addInPlace = function (otherVector) {
  1924. this.x += otherVector.x;
  1925. this.y += otherVector.y;
  1926. this.z += otherVector.z;
  1927. this.w += otherVector.w;
  1928. return this;
  1929. };
  1930. /**
  1931. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1932. */
  1933. Vector4.prototype.add = function (otherVector) {
  1934. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1935. };
  1936. /**
  1937. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1938. * Returns the current Vector4.
  1939. */
  1940. Vector4.prototype.addToRef = function (otherVector, result) {
  1941. result.x = this.x + otherVector.x;
  1942. result.y = this.y + otherVector.y;
  1943. result.z = this.z + otherVector.z;
  1944. result.w = this.w + otherVector.w;
  1945. return this;
  1946. };
  1947. /**
  1948. * Subtract in place the passed vector from the current Vector4.
  1949. * Returns the updated Vector4.
  1950. */
  1951. Vector4.prototype.subtractInPlace = function (otherVector) {
  1952. this.x -= otherVector.x;
  1953. this.y -= otherVector.y;
  1954. this.z -= otherVector.z;
  1955. this.w -= otherVector.w;
  1956. return this;
  1957. };
  1958. /**
  1959. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1960. */
  1961. Vector4.prototype.subtract = function (otherVector) {
  1962. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1963. };
  1964. /**
  1965. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1966. * Returns the current Vector4.
  1967. */
  1968. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1969. result.x = this.x - otherVector.x;
  1970. result.y = this.y - otherVector.y;
  1971. result.z = this.z - otherVector.z;
  1972. result.w = this.w - otherVector.w;
  1973. return this;
  1974. };
  1975. /**
  1976. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1977. */
  1978. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1979. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1980. };
  1981. /**
  1982. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1983. * Returns the current Vector4.
  1984. */
  1985. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1986. result.x = this.x - x;
  1987. result.y = this.y - y;
  1988. result.z = this.z - z;
  1989. result.w = this.w - w;
  1990. return this;
  1991. };
  1992. /**
  1993. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1994. */
  1995. Vector4.prototype.negate = function () {
  1996. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1997. };
  1998. /**
  1999. * Multiplies the current Vector4 coordinates by scale (float).
  2000. * Returns the updated Vector4.
  2001. */
  2002. Vector4.prototype.scaleInPlace = function (scale) {
  2003. this.x *= scale;
  2004. this.y *= scale;
  2005. this.z *= scale;
  2006. this.w *= scale;
  2007. return this;
  2008. };
  2009. /**
  2010. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  2011. */
  2012. Vector4.prototype.scale = function (scale) {
  2013. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  2014. };
  2015. /**
  2016. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  2017. * Returns the current Vector4.
  2018. */
  2019. Vector4.prototype.scaleToRef = function (scale, result) {
  2020. result.x = this.x * scale;
  2021. result.y = this.y * scale;
  2022. result.z = this.z * scale;
  2023. result.w = this.w * scale;
  2024. return this;
  2025. };
  2026. /**
  2027. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  2028. */
  2029. Vector4.prototype.equals = function (otherVector) {
  2030. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  2031. };
  2032. /**
  2033. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  2034. */
  2035. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2036. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2037. return otherVector
  2038. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  2039. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  2040. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  2041. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  2042. };
  2043. /**
  2044. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  2045. */
  2046. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  2047. return this.x === x && this.y === y && this.z === z && this.w === w;
  2048. };
  2049. /**
  2050. * Multiplies in place the current Vector4 by the passed one.
  2051. * Returns the updated Vector4.
  2052. */
  2053. Vector4.prototype.multiplyInPlace = function (otherVector) {
  2054. this.x *= otherVector.x;
  2055. this.y *= otherVector.y;
  2056. this.z *= otherVector.z;
  2057. this.w *= otherVector.w;
  2058. return this;
  2059. };
  2060. /**
  2061. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2062. */
  2063. Vector4.prototype.multiply = function (otherVector) {
  2064. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2065. };
  2066. /**
  2067. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2068. * Returns the current Vector4.
  2069. */
  2070. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2071. result.x = this.x * otherVector.x;
  2072. result.y = this.y * otherVector.y;
  2073. result.z = this.z * otherVector.z;
  2074. result.w = this.w * otherVector.w;
  2075. return this;
  2076. };
  2077. /**
  2078. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2079. */
  2080. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2081. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2082. };
  2083. /**
  2084. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2085. */
  2086. Vector4.prototype.divide = function (otherVector) {
  2087. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2088. };
  2089. /**
  2090. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2091. * Returns the current Vector4.
  2092. */
  2093. Vector4.prototype.divideToRef = function (otherVector, result) {
  2094. result.x = this.x / otherVector.x;
  2095. result.y = this.y / otherVector.y;
  2096. result.z = this.z / otherVector.z;
  2097. result.w = this.w / otherVector.w;
  2098. return this;
  2099. };
  2100. /**
  2101. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2102. */
  2103. Vector4.prototype.MinimizeInPlace = function (other) {
  2104. if (other.x < this.x)
  2105. this.x = other.x;
  2106. if (other.y < this.y)
  2107. this.y = other.y;
  2108. if (other.z < this.z)
  2109. this.z = other.z;
  2110. if (other.w < this.w)
  2111. this.w = other.w;
  2112. return this;
  2113. };
  2114. /**
  2115. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2116. */
  2117. Vector4.prototype.MaximizeInPlace = function (other) {
  2118. if (other.x > this.x)
  2119. this.x = other.x;
  2120. if (other.y > this.y)
  2121. this.y = other.y;
  2122. if (other.z > this.z)
  2123. this.z = other.z;
  2124. if (other.w > this.w)
  2125. this.w = other.w;
  2126. return this;
  2127. };
  2128. // Properties
  2129. /**
  2130. * Returns the Vector4 length (float).
  2131. */
  2132. Vector4.prototype.length = function () {
  2133. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2134. };
  2135. /**
  2136. * Returns the Vector4 squared length (float).
  2137. */
  2138. Vector4.prototype.lengthSquared = function () {
  2139. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2140. };
  2141. // Methods
  2142. /**
  2143. * Normalizes in place the Vector4.
  2144. * Returns the updated Vector4.
  2145. */
  2146. Vector4.prototype.normalize = function () {
  2147. var len = this.length();
  2148. if (len === 0)
  2149. return this;
  2150. var num = 1.0 / len;
  2151. this.x *= num;
  2152. this.y *= num;
  2153. this.z *= num;
  2154. this.w *= num;
  2155. return this;
  2156. };
  2157. /**
  2158. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  2159. */
  2160. Vector4.prototype.toVector3 = function () {
  2161. return new Vector3(this.x, this.y, this.z);
  2162. };
  2163. /**
  2164. * Returns a new Vector4 copied from the current one.
  2165. */
  2166. Vector4.prototype.clone = function () {
  2167. return new Vector4(this.x, this.y, this.z, this.w);
  2168. };
  2169. /**
  2170. * Updates the current Vector4 with the passed one coordinates.
  2171. * Returns the updated Vector4.
  2172. */
  2173. Vector4.prototype.copyFrom = function (source) {
  2174. this.x = source.x;
  2175. this.y = source.y;
  2176. this.z = source.z;
  2177. this.w = source.w;
  2178. return this;
  2179. };
  2180. /**
  2181. * Updates the current Vector4 coordinates with the passed floats.
  2182. * Returns the updated Vector4.
  2183. */
  2184. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  2185. this.x = x;
  2186. this.y = y;
  2187. this.z = z;
  2188. this.w = w;
  2189. return this;
  2190. };
  2191. /**
  2192. * Updates the current Vector4 coordinates with the passed floats.
  2193. * Returns the updated Vector4.
  2194. */
  2195. Vector4.prototype.set = function (x, y, z, w) {
  2196. return this.copyFromFloats(x, y, z, w);
  2197. };
  2198. // Statics
  2199. /**
  2200. * Returns a new Vector4 set from the starting index of the passed array.
  2201. */
  2202. Vector4.FromArray = function (array, offset) {
  2203. if (!offset) {
  2204. offset = 0;
  2205. }
  2206. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2207. };
  2208. /**
  2209. * Updates the passed vector "result" from the starting index of the passed array.
  2210. */
  2211. Vector4.FromArrayToRef = function (array, offset, result) {
  2212. result.x = array[offset];
  2213. result.y = array[offset + 1];
  2214. result.z = array[offset + 2];
  2215. result.w = array[offset + 3];
  2216. };
  2217. /**
  2218. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2219. */
  2220. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2221. Vector4.FromArrayToRef(array, offset, result);
  2222. };
  2223. /**
  2224. * Updates the passed vector "result" coordinates from the passed floats.
  2225. */
  2226. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2227. result.x = x;
  2228. result.y = y;
  2229. result.z = z;
  2230. result.w = w;
  2231. };
  2232. /**
  2233. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2234. */
  2235. Vector4.Zero = function () {
  2236. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2237. };
  2238. /**
  2239. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2240. */
  2241. Vector4.One = function () {
  2242. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2243. };
  2244. /**
  2245. * Returns a new normalized Vector4 from the passed one.
  2246. */
  2247. Vector4.Normalize = function (vector) {
  2248. var result = Vector4.Zero();
  2249. Vector4.NormalizeToRef(vector, result);
  2250. return result;
  2251. };
  2252. /**
  2253. * Updates the passed vector "result" from the normalization of the passed one.
  2254. */
  2255. Vector4.NormalizeToRef = function (vector, result) {
  2256. result.copyFrom(vector);
  2257. result.normalize();
  2258. };
  2259. Vector4.Minimize = function (left, right) {
  2260. var min = left.clone();
  2261. min.MinimizeInPlace(right);
  2262. return min;
  2263. };
  2264. Vector4.Maximize = function (left, right) {
  2265. var max = left.clone();
  2266. max.MaximizeInPlace(right);
  2267. return max;
  2268. };
  2269. /**
  2270. * Returns the distance (float) between the vectors "value1" and "value2".
  2271. */
  2272. Vector4.Distance = function (value1, value2) {
  2273. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2274. };
  2275. /**
  2276. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2277. */
  2278. Vector4.DistanceSquared = function (value1, value2) {
  2279. var x = value1.x - value2.x;
  2280. var y = value1.y - value2.y;
  2281. var z = value1.z - value2.z;
  2282. var w = value1.w - value2.w;
  2283. return (x * x) + (y * y) + (z * z) + (w * w);
  2284. };
  2285. /**
  2286. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2287. */
  2288. Vector4.Center = function (value1, value2) {
  2289. var center = value1.add(value2);
  2290. center.scaleInPlace(0.5);
  2291. return center;
  2292. };
  2293. /**
  2294. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2295. * This methods computes transformed normalized direction vectors only.
  2296. */
  2297. Vector4.TransformNormal = function (vector, transformation) {
  2298. var result = Vector4.Zero();
  2299. Vector4.TransformNormalToRef(vector, transformation, result);
  2300. return result;
  2301. };
  2302. /**
  2303. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2304. * This methods computes transformed normalized direction vectors only.
  2305. */
  2306. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2307. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2308. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2309. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2310. result.x = x;
  2311. result.y = y;
  2312. result.z = z;
  2313. result.w = vector.w;
  2314. };
  2315. /**
  2316. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2317. * This methods computes transformed normalized direction vectors only.
  2318. */
  2319. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2320. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2321. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2322. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2323. result.w = w;
  2324. };
  2325. return Vector4;
  2326. }());
  2327. BABYLON.Vector4 = Vector4;
  2328. var Size = /** @class */ (function () {
  2329. /**
  2330. * Creates a Size object from the passed width and height (floats).
  2331. */
  2332. function Size(width, height) {
  2333. this.width = width;
  2334. this.height = height;
  2335. }
  2336. // Returns a string with the Size width and height.
  2337. Size.prototype.toString = function () {
  2338. return "{W: " + this.width + ", H: " + this.height + "}";
  2339. };
  2340. /**
  2341. * Returns the string "Size"
  2342. */
  2343. Size.prototype.getClassName = function () {
  2344. return "Size";
  2345. };
  2346. /**
  2347. * Returns the Size hash code.
  2348. */
  2349. Size.prototype.getHashCode = function () {
  2350. var hash = this.width || 0;
  2351. hash = (hash * 397) ^ (this.height || 0);
  2352. return hash;
  2353. };
  2354. /**
  2355. * Updates the current size from the passed one.
  2356. * Returns the updated Size.
  2357. */
  2358. Size.prototype.copyFrom = function (src) {
  2359. this.width = src.width;
  2360. this.height = src.height;
  2361. };
  2362. /**
  2363. * Updates in place the current Size from the passed floats.
  2364. * Returns the updated Size.
  2365. */
  2366. Size.prototype.copyFromFloats = function (width, height) {
  2367. this.width = width;
  2368. this.height = height;
  2369. return this;
  2370. };
  2371. /**
  2372. * Updates in place the current Size from the passed floats.
  2373. * Returns the updated Size.
  2374. */
  2375. Size.prototype.set = function (width, height) {
  2376. return this.copyFromFloats(width, height);
  2377. };
  2378. /**
  2379. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2380. */
  2381. Size.prototype.multiplyByFloats = function (w, h) {
  2382. return new Size(this.width * w, this.height * h);
  2383. };
  2384. /**
  2385. * Returns a new Size copied from the passed one.
  2386. */
  2387. Size.prototype.clone = function () {
  2388. return new Size(this.width, this.height);
  2389. };
  2390. /**
  2391. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2392. */
  2393. Size.prototype.equals = function (other) {
  2394. if (!other) {
  2395. return false;
  2396. }
  2397. return (this.width === other.width) && (this.height === other.height);
  2398. };
  2399. Object.defineProperty(Size.prototype, "surface", {
  2400. /**
  2401. * Returns the surface of the Size : width * height (float).
  2402. */
  2403. get: function () {
  2404. return this.width * this.height;
  2405. },
  2406. enumerable: true,
  2407. configurable: true
  2408. });
  2409. /**
  2410. * Returns a new Size set to (0.0, 0.0)
  2411. */
  2412. Size.Zero = function () {
  2413. return new Size(0.0, 0.0);
  2414. };
  2415. /**
  2416. * Returns a new Size set as the addition result of the current Size and the passed one.
  2417. */
  2418. Size.prototype.add = function (otherSize) {
  2419. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2420. return r;
  2421. };
  2422. /**
  2423. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2424. */
  2425. Size.prototype.subtract = function (otherSize) {
  2426. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2427. return r;
  2428. };
  2429. /**
  2430. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2431. */
  2432. Size.Lerp = function (start, end, amount) {
  2433. var w = start.width + ((end.width - start.width) * amount);
  2434. var h = start.height + ((end.height - start.height) * amount);
  2435. return new Size(w, h);
  2436. };
  2437. return Size;
  2438. }());
  2439. BABYLON.Size = Size;
  2440. var Quaternion = /** @class */ (function () {
  2441. /**
  2442. * Creates a new Quaternion from the passed floats.
  2443. */
  2444. function Quaternion(x, y, z, w) {
  2445. if (x === void 0) { x = 0.0; }
  2446. if (y === void 0) { y = 0.0; }
  2447. if (z === void 0) { z = 0.0; }
  2448. if (w === void 0) { w = 1.0; }
  2449. this.x = x;
  2450. this.y = y;
  2451. this.z = z;
  2452. this.w = w;
  2453. }
  2454. /**
  2455. * Returns a string with the Quaternion coordinates.
  2456. */
  2457. Quaternion.prototype.toString = function () {
  2458. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2459. };
  2460. /**
  2461. * Returns the string "Quaternion".
  2462. */
  2463. Quaternion.prototype.getClassName = function () {
  2464. return "Quaternion";
  2465. };
  2466. /**
  2467. * Returns the Quaternion hash code.
  2468. */
  2469. Quaternion.prototype.getHashCode = function () {
  2470. var hash = this.x || 0;
  2471. hash = (hash * 397) ^ (this.y || 0);
  2472. hash = (hash * 397) ^ (this.z || 0);
  2473. hash = (hash * 397) ^ (this.w || 0);
  2474. return hash;
  2475. };
  2476. /**
  2477. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2478. */
  2479. Quaternion.prototype.asArray = function () {
  2480. return [this.x, this.y, this.z, this.w];
  2481. };
  2482. /**
  2483. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2484. */
  2485. Quaternion.prototype.equals = function (otherQuaternion) {
  2486. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2487. };
  2488. /**
  2489. * Returns a new Quaternion copied from the current one.
  2490. */
  2491. Quaternion.prototype.clone = function () {
  2492. return new Quaternion(this.x, this.y, this.z, this.w);
  2493. };
  2494. /**
  2495. * Updates the current Quaternion from the passed one coordinates.
  2496. * Returns the updated Quaterion.
  2497. */
  2498. Quaternion.prototype.copyFrom = function (other) {
  2499. this.x = other.x;
  2500. this.y = other.y;
  2501. this.z = other.z;
  2502. this.w = other.w;
  2503. return this;
  2504. };
  2505. /**
  2506. * Updates the current Quaternion from the passed float coordinates.
  2507. * Returns the updated Quaterion.
  2508. */
  2509. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2510. this.x = x;
  2511. this.y = y;
  2512. this.z = z;
  2513. this.w = w;
  2514. return this;
  2515. };
  2516. /**
  2517. * Updates the current Quaternion from the passed float coordinates.
  2518. * Returns the updated Quaterion.
  2519. */
  2520. Quaternion.prototype.set = function (x, y, z, w) {
  2521. return this.copyFromFloats(x, y, z, w);
  2522. };
  2523. /**
  2524. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2525. */
  2526. Quaternion.prototype.add = function (other) {
  2527. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2528. };
  2529. /**
  2530. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2531. */
  2532. Quaternion.prototype.subtract = function (other) {
  2533. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2534. };
  2535. /**
  2536. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2537. */
  2538. Quaternion.prototype.scale = function (value) {
  2539. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2540. };
  2541. /**
  2542. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2543. */
  2544. Quaternion.prototype.multiply = function (q1) {
  2545. var result = new Quaternion(0, 0, 0, 1.0);
  2546. this.multiplyToRef(q1, result);
  2547. return result;
  2548. };
  2549. /**
  2550. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2551. * Returns the current Quaternion.
  2552. */
  2553. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2554. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2555. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2556. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2557. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2558. result.copyFromFloats(x, y, z, w);
  2559. return this;
  2560. };
  2561. /**
  2562. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2563. * Returns the updated Quaternion.
  2564. */
  2565. Quaternion.prototype.multiplyInPlace = function (q1) {
  2566. this.multiplyToRef(q1, this);
  2567. return this;
  2568. };
  2569. /**
  2570. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2571. * Returns the current Quaternion.
  2572. */
  2573. Quaternion.prototype.conjugateToRef = function (ref) {
  2574. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2575. return this;
  2576. };
  2577. /**
  2578. * Conjugates in place the current Quaternion.
  2579. * Returns the updated Quaternion.
  2580. */
  2581. Quaternion.prototype.conjugateInPlace = function () {
  2582. this.x *= -1;
  2583. this.y *= -1;
  2584. this.z *= -1;
  2585. return this;
  2586. };
  2587. /**
  2588. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2589. */
  2590. Quaternion.prototype.conjugate = function () {
  2591. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2592. return result;
  2593. };
  2594. /**
  2595. * Returns the Quaternion length (float).
  2596. */
  2597. Quaternion.prototype.length = function () {
  2598. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2599. };
  2600. /**
  2601. * Normalize in place the current Quaternion.
  2602. * Returns the updated Quaternion.
  2603. */
  2604. Quaternion.prototype.normalize = function () {
  2605. var length = 1.0 / this.length();
  2606. this.x *= length;
  2607. this.y *= length;
  2608. this.z *= length;
  2609. this.w *= length;
  2610. return this;
  2611. };
  2612. /**
  2613. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2614. */
  2615. Quaternion.prototype.toEulerAngles = function (order) {
  2616. if (order === void 0) { order = "YZX"; }
  2617. var result = Vector3.Zero();
  2618. this.toEulerAnglesToRef(result, order);
  2619. return result;
  2620. };
  2621. /**
  2622. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2623. * Returns the current Quaternion.
  2624. */
  2625. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2626. if (order === void 0) { order = "YZX"; }
  2627. var qz = this.z;
  2628. var qx = this.x;
  2629. var qy = this.y;
  2630. var qw = this.w;
  2631. var sqw = qw * qw;
  2632. var sqz = qz * qz;
  2633. var sqx = qx * qx;
  2634. var sqy = qy * qy;
  2635. var zAxisY = qy * qz - qx * qw;
  2636. var limit = .4999999;
  2637. if (zAxisY < -limit) {
  2638. result.y = 2 * Math.atan2(qy, qw);
  2639. result.x = Math.PI / 2;
  2640. result.z = 0;
  2641. }
  2642. else if (zAxisY > limit) {
  2643. result.y = 2 * Math.atan2(qy, qw);
  2644. result.x = -Math.PI / 2;
  2645. result.z = 0;
  2646. }
  2647. else {
  2648. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2649. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2650. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2651. }
  2652. return this;
  2653. };
  2654. /**
  2655. * Updates the passed rotation matrix with the current Quaternion values.
  2656. * Returns the current Quaternion.
  2657. */
  2658. Quaternion.prototype.toRotationMatrix = function (result) {
  2659. var xx = this.x * this.x;
  2660. var yy = this.y * this.y;
  2661. var zz = this.z * this.z;
  2662. var xy = this.x * this.y;
  2663. var zw = this.z * this.w;
  2664. var zx = this.z * this.x;
  2665. var yw = this.y * this.w;
  2666. var yz = this.y * this.z;
  2667. var xw = this.x * this.w;
  2668. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2669. result.m[1] = 2.0 * (xy + zw);
  2670. result.m[2] = 2.0 * (zx - yw);
  2671. result.m[3] = 0;
  2672. result.m[4] = 2.0 * (xy - zw);
  2673. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2674. result.m[6] = 2.0 * (yz + xw);
  2675. result.m[7] = 0;
  2676. result.m[8] = 2.0 * (zx + yw);
  2677. result.m[9] = 2.0 * (yz - xw);
  2678. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2679. result.m[11] = 0;
  2680. result.m[12] = 0;
  2681. result.m[13] = 0;
  2682. result.m[14] = 0;
  2683. result.m[15] = 1.0;
  2684. result._markAsUpdated();
  2685. return this;
  2686. };
  2687. /**
  2688. * Updates the current Quaternion from the passed rotation matrix values.
  2689. * Returns the updated Quaternion.
  2690. */
  2691. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2692. Quaternion.FromRotationMatrixToRef(matrix, this);
  2693. return this;
  2694. };
  2695. // Statics
  2696. /**
  2697. * Returns a new Quaternion set from the passed rotation matrix values.
  2698. */
  2699. Quaternion.FromRotationMatrix = function (matrix) {
  2700. var result = new Quaternion();
  2701. Quaternion.FromRotationMatrixToRef(matrix, result);
  2702. return result;
  2703. };
  2704. /**
  2705. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2706. */
  2707. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2708. var data = matrix.m;
  2709. var m11 = data[0], m12 = data[4], m13 = data[8];
  2710. var m21 = data[1], m22 = data[5], m23 = data[9];
  2711. var m31 = data[2], m32 = data[6], m33 = data[10];
  2712. var trace = m11 + m22 + m33;
  2713. var s;
  2714. if (trace > 0) {
  2715. s = 0.5 / Math.sqrt(trace + 1.0);
  2716. result.w = 0.25 / s;
  2717. result.x = (m32 - m23) * s;
  2718. result.y = (m13 - m31) * s;
  2719. result.z = (m21 - m12) * s;
  2720. }
  2721. else if (m11 > m22 && m11 > m33) {
  2722. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2723. result.w = (m32 - m23) / s;
  2724. result.x = 0.25 * s;
  2725. result.y = (m12 + m21) / s;
  2726. result.z = (m13 + m31) / s;
  2727. }
  2728. else if (m22 > m33) {
  2729. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2730. result.w = (m13 - m31) / s;
  2731. result.x = (m12 + m21) / s;
  2732. result.y = 0.25 * s;
  2733. result.z = (m23 + m32) / s;
  2734. }
  2735. else {
  2736. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2737. result.w = (m21 - m12) / s;
  2738. result.x = (m13 + m31) / s;
  2739. result.y = (m23 + m32) / s;
  2740. result.z = 0.25 * s;
  2741. }
  2742. };
  2743. /**
  2744. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2745. */
  2746. Quaternion.Zero = function () {
  2747. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2748. };
  2749. /**
  2750. * Returns a new Quaternion as the inverted current Quaternion.
  2751. */
  2752. Quaternion.Inverse = function (q) {
  2753. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2754. };
  2755. /**
  2756. * Returns the identity Quaternion.
  2757. */
  2758. Quaternion.Identity = function () {
  2759. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2760. };
  2761. Quaternion.IsIdentity = function (quaternion) {
  2762. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2763. };
  2764. /**
  2765. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2766. */
  2767. Quaternion.RotationAxis = function (axis, angle) {
  2768. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2769. };
  2770. /**
  2771. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2772. */
  2773. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2774. var sin = Math.sin(angle / 2);
  2775. axis.normalize();
  2776. result.w = Math.cos(angle / 2);
  2777. result.x = axis.x * sin;
  2778. result.y = axis.y * sin;
  2779. result.z = axis.z * sin;
  2780. return result;
  2781. };
  2782. /**
  2783. * Retuns a new Quaternion set from the starting index of the passed array.
  2784. */
  2785. Quaternion.FromArray = function (array, offset) {
  2786. if (!offset) {
  2787. offset = 0;
  2788. }
  2789. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2790. };
  2791. /**
  2792. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2793. */
  2794. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2795. var q = new Quaternion();
  2796. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2797. return q;
  2798. };
  2799. /**
  2800. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2801. */
  2802. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2803. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2804. var halfRoll = roll * 0.5;
  2805. var halfPitch = pitch * 0.5;
  2806. var halfYaw = yaw * 0.5;
  2807. var sinRoll = Math.sin(halfRoll);
  2808. var cosRoll = Math.cos(halfRoll);
  2809. var sinPitch = Math.sin(halfPitch);
  2810. var cosPitch = Math.cos(halfPitch);
  2811. var sinYaw = Math.sin(halfYaw);
  2812. var cosYaw = Math.cos(halfYaw);
  2813. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2814. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2815. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2816. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2817. };
  2818. /**
  2819. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2820. */
  2821. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2822. var result = new Quaternion();
  2823. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2824. return result;
  2825. };
  2826. /**
  2827. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2828. */
  2829. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2830. // Produces a quaternion from Euler angles in the z-x-z orientation
  2831. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2832. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2833. var halfBeta = beta * 0.5;
  2834. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2835. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2836. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2837. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2838. };
  2839. /**
  2840. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2841. * cf to Vector3.RotationFromAxis() documentation.
  2842. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2843. */
  2844. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2845. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2846. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2847. return quat;
  2848. };
  2849. /**
  2850. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2851. * cf to Vector3.RotationFromAxis() documentation.
  2852. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2853. */
  2854. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2855. var rotMat = MathTmp.Matrix[0];
  2856. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2857. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2858. };
  2859. Quaternion.Slerp = function (left, right, amount) {
  2860. var result = Quaternion.Identity();
  2861. Quaternion.SlerpToRef(left, right, amount, result);
  2862. return result;
  2863. };
  2864. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2865. var num2;
  2866. var num3;
  2867. var num = amount;
  2868. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2869. var flag = false;
  2870. if (num4 < 0) {
  2871. flag = true;
  2872. num4 = -num4;
  2873. }
  2874. if (num4 > 0.999999) {
  2875. num3 = 1 - num;
  2876. num2 = flag ? -num : num;
  2877. }
  2878. else {
  2879. var num5 = Math.acos(num4);
  2880. var num6 = (1.0 / Math.sin(num5));
  2881. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2882. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2883. }
  2884. result.x = (num3 * left.x) + (num2 * right.x);
  2885. result.y = (num3 * left.y) + (num2 * right.y);
  2886. result.z = (num3 * left.z) + (num2 * right.z);
  2887. result.w = (num3 * left.w) + (num2 * right.w);
  2888. };
  2889. /**
  2890. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2891. */
  2892. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2893. var squared = amount * amount;
  2894. var cubed = amount * squared;
  2895. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2896. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2897. var part3 = (cubed - (2.0 * squared)) + amount;
  2898. var part4 = cubed - squared;
  2899. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2900. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2901. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2902. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2903. return new Quaternion(x, y, z, w);
  2904. };
  2905. return Quaternion;
  2906. }());
  2907. BABYLON.Quaternion = Quaternion;
  2908. var Matrix = /** @class */ (function () {
  2909. function Matrix() {
  2910. this._isIdentity = false;
  2911. this._isIdentityDirty = true;
  2912. this.m = new Float32Array(16);
  2913. this._markAsUpdated();
  2914. }
  2915. Matrix.prototype._markAsUpdated = function () {
  2916. this.updateFlag = Matrix._updateFlagSeed++;
  2917. this._isIdentityDirty = true;
  2918. };
  2919. // Properties
  2920. /**
  2921. * Boolean : True is the matrix is the identity matrix
  2922. */
  2923. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  2924. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  2925. if (this._isIdentityDirty) {
  2926. this._isIdentityDirty = false;
  2927. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  2928. this._isIdentity = false;
  2929. }
  2930. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2931. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2932. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2933. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  2934. this._isIdentity = false;
  2935. }
  2936. else {
  2937. this._isIdentity = true;
  2938. }
  2939. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  2940. this._isIdentity = false;
  2941. }
  2942. }
  2943. return this._isIdentity;
  2944. };
  2945. /**
  2946. * Returns the matrix determinant (float).
  2947. */
  2948. Matrix.prototype.determinant = function () {
  2949. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2950. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2951. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2952. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2953. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2954. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2955. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2956. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2957. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2958. };
  2959. // Methods
  2960. /**
  2961. * Returns the matrix underlying array.
  2962. */
  2963. Matrix.prototype.toArray = function () {
  2964. return this.m;
  2965. };
  2966. /**
  2967. * Returns the matrix underlying array.
  2968. */
  2969. Matrix.prototype.asArray = function () {
  2970. return this.toArray();
  2971. };
  2972. /**
  2973. * Inverts in place the Matrix.
  2974. * Returns the Matrix inverted.
  2975. */
  2976. Matrix.prototype.invert = function () {
  2977. this.invertToRef(this);
  2978. return this;
  2979. };
  2980. /**
  2981. * Sets all the matrix elements to zero.
  2982. * Returns the Matrix.
  2983. */
  2984. Matrix.prototype.reset = function () {
  2985. for (var index = 0; index < 16; index++) {
  2986. this.m[index] = 0.0;
  2987. }
  2988. this._markAsUpdated();
  2989. return this;
  2990. };
  2991. /**
  2992. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2993. */
  2994. Matrix.prototype.add = function (other) {
  2995. var result = new Matrix();
  2996. this.addToRef(other, result);
  2997. return result;
  2998. };
  2999. /**
  3000. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  3001. * Returns the Matrix.
  3002. */
  3003. Matrix.prototype.addToRef = function (other, result) {
  3004. for (var index = 0; index < 16; index++) {
  3005. result.m[index] = this.m[index] + other.m[index];
  3006. }
  3007. result._markAsUpdated();
  3008. return this;
  3009. };
  3010. /**
  3011. * Adds in place the passed matrix to the current Matrix.
  3012. * Returns the updated Matrix.
  3013. */
  3014. Matrix.prototype.addToSelf = function (other) {
  3015. for (var index = 0; index < 16; index++) {
  3016. this.m[index] += other.m[index];
  3017. }
  3018. this._markAsUpdated();
  3019. return this;
  3020. };
  3021. /**
  3022. * Sets the passed matrix with the current inverted Matrix.
  3023. * Returns the unmodified current Matrix.
  3024. */
  3025. Matrix.prototype.invertToRef = function (other) {
  3026. var l1 = this.m[0];
  3027. var l2 = this.m[1];
  3028. var l3 = this.m[2];
  3029. var l4 = this.m[3];
  3030. var l5 = this.m[4];
  3031. var l6 = this.m[5];
  3032. var l7 = this.m[6];
  3033. var l8 = this.m[7];
  3034. var l9 = this.m[8];
  3035. var l10 = this.m[9];
  3036. var l11 = this.m[10];
  3037. var l12 = this.m[11];
  3038. var l13 = this.m[12];
  3039. var l14 = this.m[13];
  3040. var l15 = this.m[14];
  3041. var l16 = this.m[15];
  3042. var l17 = (l11 * l16) - (l12 * l15);
  3043. var l18 = (l10 * l16) - (l12 * l14);
  3044. var l19 = (l10 * l15) - (l11 * l14);
  3045. var l20 = (l9 * l16) - (l12 * l13);
  3046. var l21 = (l9 * l15) - (l11 * l13);
  3047. var l22 = (l9 * l14) - (l10 * l13);
  3048. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  3049. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  3050. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  3051. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  3052. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  3053. var l28 = (l7 * l16) - (l8 * l15);
  3054. var l29 = (l6 * l16) - (l8 * l14);
  3055. var l30 = (l6 * l15) - (l7 * l14);
  3056. var l31 = (l5 * l16) - (l8 * l13);
  3057. var l32 = (l5 * l15) - (l7 * l13);
  3058. var l33 = (l5 * l14) - (l6 * l13);
  3059. var l34 = (l7 * l12) - (l8 * l11);
  3060. var l35 = (l6 * l12) - (l8 * l10);
  3061. var l36 = (l6 * l11) - (l7 * l10);
  3062. var l37 = (l5 * l12) - (l8 * l9);
  3063. var l38 = (l5 * l11) - (l7 * l9);
  3064. var l39 = (l5 * l10) - (l6 * l9);
  3065. other.m[0] = l23 * l27;
  3066. other.m[4] = l24 * l27;
  3067. other.m[8] = l25 * l27;
  3068. other.m[12] = l26 * l27;
  3069. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3070. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3071. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3072. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3073. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3074. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3075. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3076. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3077. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3078. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3079. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3080. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3081. other._markAsUpdated();
  3082. return this;
  3083. };
  3084. /**
  3085. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3086. * Returns the updated Matrix.
  3087. */
  3088. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3089. this.m[12] = x;
  3090. this.m[13] = y;
  3091. this.m[14] = z;
  3092. this._markAsUpdated();
  3093. return this;
  3094. };
  3095. /**
  3096. * Inserts the translation vector in the current Matrix.
  3097. * Returns the updated Matrix.
  3098. */
  3099. Matrix.prototype.setTranslation = function (vector3) {
  3100. this.m[12] = vector3.x;
  3101. this.m[13] = vector3.y;
  3102. this.m[14] = vector3.z;
  3103. this._markAsUpdated();
  3104. return this;
  3105. };
  3106. /**
  3107. * Returns a new Vector3 as the extracted translation from the Matrix.
  3108. */
  3109. Matrix.prototype.getTranslation = function () {
  3110. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3111. };
  3112. /**
  3113. * Fill a Vector3 with the extracted translation from the Matrix.
  3114. */
  3115. Matrix.prototype.getTranslationToRef = function (result) {
  3116. result.x = this.m[12];
  3117. result.y = this.m[13];
  3118. result.z = this.m[14];
  3119. return this;
  3120. };
  3121. /**
  3122. * Remove rotation and scaling part from the Matrix.
  3123. * Returns the updated Matrix.
  3124. */
  3125. Matrix.prototype.removeRotationAndScaling = function () {
  3126. this.setRowFromFloats(0, 1, 0, 0, 0);
  3127. this.setRowFromFloats(1, 0, 1, 0, 0);
  3128. this.setRowFromFloats(2, 0, 0, 1, 0);
  3129. return this;
  3130. };
  3131. /**
  3132. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  3133. */
  3134. Matrix.prototype.multiply = function (other) {
  3135. var result = new Matrix();
  3136. this.multiplyToRef(other, result);
  3137. return result;
  3138. };
  3139. /**
  3140. * Updates the current Matrix from the passed one values.
  3141. * Returns the updated Matrix.
  3142. */
  3143. Matrix.prototype.copyFrom = function (other) {
  3144. for (var index = 0; index < 16; index++) {
  3145. this.m[index] = other.m[index];
  3146. }
  3147. this._markAsUpdated();
  3148. return this;
  3149. };
  3150. /**
  3151. * Populates the passed array from the starting index with the Matrix values.
  3152. * Returns the Matrix.
  3153. */
  3154. Matrix.prototype.copyToArray = function (array, offset) {
  3155. if (offset === void 0) { offset = 0; }
  3156. for (var index = 0; index < 16; index++) {
  3157. array[offset + index] = this.m[index];
  3158. }
  3159. return this;
  3160. };
  3161. /**
  3162. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  3163. */
  3164. Matrix.prototype.multiplyToRef = function (other, result) {
  3165. this.multiplyToArray(other, result.m, 0);
  3166. result._markAsUpdated();
  3167. return this;
  3168. };
  3169. /**
  3170. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  3171. */
  3172. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  3173. var tm0 = this.m[0];
  3174. var tm1 = this.m[1];
  3175. var tm2 = this.m[2];
  3176. var tm3 = this.m[3];
  3177. var tm4 = this.m[4];
  3178. var tm5 = this.m[5];
  3179. var tm6 = this.m[6];
  3180. var tm7 = this.m[7];
  3181. var tm8 = this.m[8];
  3182. var tm9 = this.m[9];
  3183. var tm10 = this.m[10];
  3184. var tm11 = this.m[11];
  3185. var tm12 = this.m[12];
  3186. var tm13 = this.m[13];
  3187. var tm14 = this.m[14];
  3188. var tm15 = this.m[15];
  3189. var om0 = other.m[0];
  3190. var om1 = other.m[1];
  3191. var om2 = other.m[2];
  3192. var om3 = other.m[3];
  3193. var om4 = other.m[4];
  3194. var om5 = other.m[5];
  3195. var om6 = other.m[6];
  3196. var om7 = other.m[7];
  3197. var om8 = other.m[8];
  3198. var om9 = other.m[9];
  3199. var om10 = other.m[10];
  3200. var om11 = other.m[11];
  3201. var om12 = other.m[12];
  3202. var om13 = other.m[13];
  3203. var om14 = other.m[14];
  3204. var om15 = other.m[15];
  3205. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  3206. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  3207. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3208. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3209. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3210. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3211. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3212. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3213. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3214. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3215. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3216. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3217. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3218. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3219. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3220. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3221. return this;
  3222. };
  3223. /**
  3224. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3225. */
  3226. Matrix.prototype.equals = function (value) {
  3227. return value &&
  3228. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3229. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3230. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3231. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3232. };
  3233. /**
  3234. * Returns a new Matrix from the current Matrix.
  3235. */
  3236. Matrix.prototype.clone = function () {
  3237. 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]);
  3238. };
  3239. /**
  3240. * Returns the string "Matrix"
  3241. */
  3242. Matrix.prototype.getClassName = function () {
  3243. return "Matrix";
  3244. };
  3245. /**
  3246. * Returns the Matrix hash code.
  3247. */
  3248. Matrix.prototype.getHashCode = function () {
  3249. var hash = this.m[0] || 0;
  3250. for (var i = 1; i < 16; i++) {
  3251. hash = (hash * 397) ^ (this.m[i] || 0);
  3252. }
  3253. return hash;
  3254. };
  3255. /**
  3256. * Decomposes the current Matrix into :
  3257. * - a scale vector3 passed as a reference to update,
  3258. * - a rotation quaternion passed as a reference to update,
  3259. * - a translation vector3 passed as a reference to update.
  3260. * Returns the boolean `true`.
  3261. */
  3262. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3263. translation.x = this.m[12];
  3264. translation.y = this.m[13];
  3265. translation.z = this.m[14];
  3266. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3267. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3268. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3269. if (this.determinant() <= 0) {
  3270. scale.y *= -1;
  3271. }
  3272. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3273. rotation.x = 0;
  3274. rotation.y = 0;
  3275. rotation.z = 0;
  3276. rotation.w = 1;
  3277. return false;
  3278. }
  3279. 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]);
  3280. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3281. return true;
  3282. };
  3283. /**
  3284. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3285. */
  3286. Matrix.prototype.getRotationMatrix = function () {
  3287. var result = Matrix.Identity();
  3288. this.getRotationMatrixToRef(result);
  3289. return result;
  3290. };
  3291. /**
  3292. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3293. * Returns the current Matrix.
  3294. */
  3295. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3296. var m = this.m;
  3297. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3298. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3299. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3300. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3301. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3302. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3303. 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);
  3304. return this;
  3305. };
  3306. // Statics
  3307. /**
  3308. * Returns a new Matrix set from the starting index of the passed array.
  3309. */
  3310. Matrix.FromArray = function (array, offset) {
  3311. var result = new Matrix();
  3312. if (!offset) {
  3313. offset = 0;
  3314. }
  3315. Matrix.FromArrayToRef(array, offset, result);
  3316. return result;
  3317. };
  3318. /**
  3319. * Sets the passed "result" matrix from the starting index of the passed array.
  3320. */
  3321. Matrix.FromArrayToRef = function (array, offset, result) {
  3322. for (var index = 0; index < 16; index++) {
  3323. result.m[index] = array[index + offset];
  3324. }
  3325. result._markAsUpdated();
  3326. };
  3327. /**
  3328. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3329. */
  3330. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3331. for (var index = 0; index < 16; index++) {
  3332. result.m[index] = array[index + offset] * scale;
  3333. }
  3334. result._markAsUpdated();
  3335. };
  3336. /**
  3337. * Sets the passed matrix "result" with the 16 passed floats.
  3338. */
  3339. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3340. result.m[0] = initialM11;
  3341. result.m[1] = initialM12;
  3342. result.m[2] = initialM13;
  3343. result.m[3] = initialM14;
  3344. result.m[4] = initialM21;
  3345. result.m[5] = initialM22;
  3346. result.m[6] = initialM23;
  3347. result.m[7] = initialM24;
  3348. result.m[8] = initialM31;
  3349. result.m[9] = initialM32;
  3350. result.m[10] = initialM33;
  3351. result.m[11] = initialM34;
  3352. result.m[12] = initialM41;
  3353. result.m[13] = initialM42;
  3354. result.m[14] = initialM43;
  3355. result.m[15] = initialM44;
  3356. result._markAsUpdated();
  3357. };
  3358. /**
  3359. * Returns the index-th row of the current matrix as a new Vector4.
  3360. */
  3361. Matrix.prototype.getRow = function (index) {
  3362. if (index < 0 || index > 3) {
  3363. return null;
  3364. }
  3365. var i = index * 4;
  3366. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3367. };
  3368. /**
  3369. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3370. * Returns the updated Matrix.
  3371. */
  3372. Matrix.prototype.setRow = function (index, row) {
  3373. if (index < 0 || index > 3) {
  3374. return this;
  3375. }
  3376. var i = index * 4;
  3377. this.m[i + 0] = row.x;
  3378. this.m[i + 1] = row.y;
  3379. this.m[i + 2] = row.z;
  3380. this.m[i + 3] = row.w;
  3381. this._markAsUpdated();
  3382. return this;
  3383. };
  3384. /**
  3385. * Compute the transpose of the matrix.
  3386. * Returns a new Matrix.
  3387. */
  3388. Matrix.prototype.transpose = function () {
  3389. return Matrix.Transpose(this);
  3390. };
  3391. /**
  3392. * Compute the transpose of the matrix.
  3393. * Returns the current matrix.
  3394. */
  3395. Matrix.prototype.transposeToRef = function (result) {
  3396. Matrix.TransposeToRef(this, result);
  3397. return this;
  3398. };
  3399. /**
  3400. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3401. * Returns the updated Matrix.
  3402. */
  3403. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3404. if (index < 0 || index > 3) {
  3405. return this;
  3406. }
  3407. var i = index * 4;
  3408. this.m[i + 0] = x;
  3409. this.m[i + 1] = y;
  3410. this.m[i + 2] = z;
  3411. this.m[i + 3] = w;
  3412. this._markAsUpdated();
  3413. return this;
  3414. };
  3415. Object.defineProperty(Matrix, "IdentityReadOnly", {
  3416. /**
  3417. * Static identity matrix to be used as readonly matrix
  3418. * Must not be updated.
  3419. */
  3420. get: function () {
  3421. return Matrix._identityReadOnly;
  3422. },
  3423. enumerable: true,
  3424. configurable: true
  3425. });
  3426. /**
  3427. * Returns a new Matrix set from the 16 passed floats.
  3428. */
  3429. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3430. var result = new Matrix();
  3431. result.m[0] = initialM11;
  3432. result.m[1] = initialM12;
  3433. result.m[2] = initialM13;
  3434. result.m[3] = initialM14;
  3435. result.m[4] = initialM21;
  3436. result.m[5] = initialM22;
  3437. result.m[6] = initialM23;
  3438. result.m[7] = initialM24;
  3439. result.m[8] = initialM31;
  3440. result.m[9] = initialM32;
  3441. result.m[10] = initialM33;
  3442. result.m[11] = initialM34;
  3443. result.m[12] = initialM41;
  3444. result.m[13] = initialM42;
  3445. result.m[14] = initialM43;
  3446. result.m[15] = initialM44;
  3447. return result;
  3448. };
  3449. /**
  3450. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3451. */
  3452. Matrix.Compose = function (scale, rotation, translation) {
  3453. var result = Matrix.Identity();
  3454. Matrix.ComposeToRef(scale, rotation, translation, result);
  3455. return result;
  3456. };
  3457. /**
  3458. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3459. */
  3460. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3461. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3462. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3463. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3464. result.setTranslation(translation);
  3465. };
  3466. /**
  3467. * Returns a new indentity Matrix.
  3468. */
  3469. Matrix.Identity = function () {
  3470. 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);
  3471. };
  3472. /**
  3473. * Sets the passed "result" as an identity matrix.
  3474. */
  3475. Matrix.IdentityToRef = function (result) {
  3476. 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);
  3477. };
  3478. /**
  3479. * Returns a new zero Matrix.
  3480. */
  3481. Matrix.Zero = function () {
  3482. 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);
  3483. };
  3484. /**
  3485. * Returns a new rotation matrix for "angle" radians around the X axis.
  3486. */
  3487. Matrix.RotationX = function (angle) {
  3488. var result = new Matrix();
  3489. Matrix.RotationXToRef(angle, result);
  3490. return result;
  3491. };
  3492. /**
  3493. * Returns a new Matrix as the passed inverted one.
  3494. */
  3495. Matrix.Invert = function (source) {
  3496. var result = new Matrix();
  3497. source.invertToRef(result);
  3498. return result;
  3499. };
  3500. /**
  3501. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3502. */
  3503. Matrix.RotationXToRef = function (angle, result) {
  3504. var s = Math.sin(angle);
  3505. var c = Math.cos(angle);
  3506. result.m[0] = 1.0;
  3507. result.m[15] = 1.0;
  3508. result.m[5] = c;
  3509. result.m[10] = c;
  3510. result.m[9] = -s;
  3511. result.m[6] = s;
  3512. result.m[1] = 0.0;
  3513. result.m[2] = 0.0;
  3514. result.m[3] = 0.0;
  3515. result.m[4] = 0.0;
  3516. result.m[7] = 0.0;
  3517. result.m[8] = 0.0;
  3518. result.m[11] = 0.0;
  3519. result.m[12] = 0.0;
  3520. result.m[13] = 0.0;
  3521. result.m[14] = 0.0;
  3522. result._markAsUpdated();
  3523. };
  3524. /**
  3525. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3526. */
  3527. Matrix.RotationY = function (angle) {
  3528. var result = new Matrix();
  3529. Matrix.RotationYToRef(angle, result);
  3530. return result;
  3531. };
  3532. /**
  3533. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3534. */
  3535. Matrix.RotationYToRef = function (angle, result) {
  3536. var s = Math.sin(angle);
  3537. var c = Math.cos(angle);
  3538. result.m[5] = 1.0;
  3539. result.m[15] = 1.0;
  3540. result.m[0] = c;
  3541. result.m[2] = -s;
  3542. result.m[8] = s;
  3543. result.m[10] = c;
  3544. result.m[1] = 0.0;
  3545. result.m[3] = 0.0;
  3546. result.m[4] = 0.0;
  3547. result.m[6] = 0.0;
  3548. result.m[7] = 0.0;
  3549. result.m[9] = 0.0;
  3550. result.m[11] = 0.0;
  3551. result.m[12] = 0.0;
  3552. result.m[13] = 0.0;
  3553. result.m[14] = 0.0;
  3554. result._markAsUpdated();
  3555. };
  3556. /**
  3557. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3558. */
  3559. Matrix.RotationZ = function (angle) {
  3560. var result = new Matrix();
  3561. Matrix.RotationZToRef(angle, result);
  3562. return result;
  3563. };
  3564. /**
  3565. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3566. */
  3567. Matrix.RotationZToRef = function (angle, result) {
  3568. var s = Math.sin(angle);
  3569. var c = Math.cos(angle);
  3570. result.m[10] = 1.0;
  3571. result.m[15] = 1.0;
  3572. result.m[0] = c;
  3573. result.m[1] = s;
  3574. result.m[4] = -s;
  3575. result.m[5] = c;
  3576. result.m[2] = 0.0;
  3577. result.m[3] = 0.0;
  3578. result.m[6] = 0.0;
  3579. result.m[7] = 0.0;
  3580. result.m[8] = 0.0;
  3581. result.m[9] = 0.0;
  3582. result.m[11] = 0.0;
  3583. result.m[12] = 0.0;
  3584. result.m[13] = 0.0;
  3585. result.m[14] = 0.0;
  3586. result._markAsUpdated();
  3587. };
  3588. /**
  3589. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3590. */
  3591. Matrix.RotationAxis = function (axis, angle) {
  3592. var result = Matrix.Zero();
  3593. Matrix.RotationAxisToRef(axis, angle, result);
  3594. return result;
  3595. };
  3596. /**
  3597. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3598. */
  3599. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3600. var s = Math.sin(-angle);
  3601. var c = Math.cos(-angle);
  3602. var c1 = 1 - c;
  3603. axis.normalize();
  3604. result.m[0] = (axis.x * axis.x) * c1 + c;
  3605. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3606. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3607. result.m[3] = 0.0;
  3608. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3609. result.m[5] = (axis.y * axis.y) * c1 + c;
  3610. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3611. result.m[7] = 0.0;
  3612. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3613. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3614. result.m[10] = (axis.z * axis.z) * c1 + c;
  3615. result.m[11] = 0.0;
  3616. result.m[15] = 1.0;
  3617. result._markAsUpdated();
  3618. };
  3619. /**
  3620. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3621. */
  3622. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3623. var result = new Matrix();
  3624. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3625. return result;
  3626. };
  3627. /**
  3628. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3629. */
  3630. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3631. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3632. this._tempQuaternion.toRotationMatrix(result);
  3633. };
  3634. /**
  3635. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3636. */
  3637. Matrix.Scaling = function (x, y, z) {
  3638. var result = Matrix.Zero();
  3639. Matrix.ScalingToRef(x, y, z, result);
  3640. return result;
  3641. };
  3642. /**
  3643. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3644. */
  3645. Matrix.ScalingToRef = function (x, y, z, result) {
  3646. result.m[0] = x;
  3647. result.m[1] = 0.0;
  3648. result.m[2] = 0.0;
  3649. result.m[3] = 0.0;
  3650. result.m[4] = 0.0;
  3651. result.m[5] = y;
  3652. result.m[6] = 0.0;
  3653. result.m[7] = 0.0;
  3654. result.m[8] = 0.0;
  3655. result.m[9] = 0.0;
  3656. result.m[10] = z;
  3657. result.m[11] = 0.0;
  3658. result.m[12] = 0.0;
  3659. result.m[13] = 0.0;
  3660. result.m[14] = 0.0;
  3661. result.m[15] = 1.0;
  3662. result._markAsUpdated();
  3663. };
  3664. /**
  3665. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3666. */
  3667. Matrix.Translation = function (x, y, z) {
  3668. var result = Matrix.Identity();
  3669. Matrix.TranslationToRef(x, y, z, result);
  3670. return result;
  3671. };
  3672. /**
  3673. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3674. */
  3675. Matrix.TranslationToRef = function (x, y, z, result) {
  3676. 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);
  3677. };
  3678. /**
  3679. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3680. */
  3681. Matrix.Lerp = function (startValue, endValue, gradient) {
  3682. var result = Matrix.Zero();
  3683. for (var index = 0; index < 16; index++) {
  3684. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3685. }
  3686. result._markAsUpdated();
  3687. return result;
  3688. };
  3689. /**
  3690. * Returns a new Matrix whose values are computed by :
  3691. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3692. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3693. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3694. */
  3695. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3696. var startScale = new Vector3(0, 0, 0);
  3697. var startRotation = new Quaternion();
  3698. var startTranslation = new Vector3(0, 0, 0);
  3699. startValue.decompose(startScale, startRotation, startTranslation);
  3700. var endScale = new Vector3(0, 0, 0);
  3701. var endRotation = new Quaternion();
  3702. var endTranslation = new Vector3(0, 0, 0);
  3703. endValue.decompose(endScale, endRotation, endTranslation);
  3704. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3705. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3706. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3707. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3708. };
  3709. /**
  3710. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3711. * This methods works for a Left-Handed system.
  3712. */
  3713. Matrix.LookAtLH = function (eye, target, up) {
  3714. var result = Matrix.Zero();
  3715. Matrix.LookAtLHToRef(eye, target, up, result);
  3716. return result;
  3717. };
  3718. /**
  3719. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3720. * This methods works for a Left-Handed system.
  3721. */
  3722. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3723. // Z axis
  3724. target.subtractToRef(eye, this._zAxis);
  3725. this._zAxis.normalize();
  3726. // X axis
  3727. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3728. if (this._xAxis.lengthSquared() === 0) {
  3729. this._xAxis.x = 1.0;
  3730. }
  3731. else {
  3732. this._xAxis.normalize();
  3733. }
  3734. // Y axis
  3735. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3736. this._yAxis.normalize();
  3737. // Eye angles
  3738. var ex = -Vector3.Dot(this._xAxis, eye);
  3739. var ey = -Vector3.Dot(this._yAxis, eye);
  3740. var ez = -Vector3.Dot(this._zAxis, eye);
  3741. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  3742. };
  3743. /**
  3744. * Returns a new 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".
  3745. * This methods works for a Right-Handed system.
  3746. */
  3747. Matrix.LookAtRH = function (eye, target, up) {
  3748. var result = Matrix.Zero();
  3749. Matrix.LookAtRHToRef(eye, target, up, result);
  3750. return result;
  3751. };
  3752. /**
  3753. * 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".
  3754. * This methods works for a Left-Handed system.
  3755. */
  3756. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3757. // Z axis
  3758. eye.subtractToRef(target, this._zAxis);
  3759. this._zAxis.normalize();
  3760. // X axis
  3761. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3762. if (this._xAxis.lengthSquared() === 0) {
  3763. this._xAxis.x = 1.0;
  3764. }
  3765. else {
  3766. this._xAxis.normalize();
  3767. }
  3768. // Y axis
  3769. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3770. this._yAxis.normalize();
  3771. // Eye angles
  3772. var ex = -Vector3.Dot(this._xAxis, eye);
  3773. var ey = -Vector3.Dot(this._yAxis, eye);
  3774. var ez = -Vector3.Dot(this._zAxis, eye);
  3775. 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);
  3776. };
  3777. /**
  3778. * 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.
  3779. */
  3780. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3781. var matrix = Matrix.Zero();
  3782. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3783. return matrix;
  3784. };
  3785. /**
  3786. * 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.
  3787. */
  3788. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3789. var n = znear;
  3790. var f = zfar;
  3791. var a = 2.0 / width;
  3792. var b = 2.0 / height;
  3793. var c = 2.0 / (f - n);
  3794. var d = -(f + n) / (f - n);
  3795. 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);
  3796. };
  3797. /**
  3798. * 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.
  3799. */
  3800. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3801. var matrix = Matrix.Zero();
  3802. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3803. return matrix;
  3804. };
  3805. /**
  3806. * 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.
  3807. */
  3808. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3809. var n = znear;
  3810. var f = zfar;
  3811. var a = 2.0 / (right - left);
  3812. var b = 2.0 / (top - bottom);
  3813. var c = 2.0 / (f - n);
  3814. var d = -(f + n) / (f - n);
  3815. var i0 = (left + right) / (left - right);
  3816. var i1 = (top + bottom) / (bottom - top);
  3817. 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);
  3818. };
  3819. /**
  3820. * 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.
  3821. */
  3822. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3823. var matrix = Matrix.Zero();
  3824. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3825. return matrix;
  3826. };
  3827. /**
  3828. * 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.
  3829. */
  3830. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3831. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3832. result.m[10] *= -1.0;
  3833. };
  3834. /**
  3835. * 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.
  3836. */
  3837. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3838. var matrix = Matrix.Zero();
  3839. var n = znear;
  3840. var f = zfar;
  3841. var a = 2.0 * n / width;
  3842. var b = 2.0 * n / height;
  3843. var c = (f + n) / (f - n);
  3844. var d = -2.0 * f * n / (f - n);
  3845. 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);
  3846. return matrix;
  3847. };
  3848. /**
  3849. * 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.
  3850. */
  3851. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3852. var matrix = Matrix.Zero();
  3853. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3854. return matrix;
  3855. };
  3856. /**
  3857. * 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.
  3858. */
  3859. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3860. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3861. var n = znear;
  3862. var f = zfar;
  3863. var t = 1.0 / (Math.tan(fov * 0.5));
  3864. var a = isVerticalFovFixed ? (t / aspect) : t;
  3865. var b = isVerticalFovFixed ? t : (t * aspect);
  3866. var c = (f + n) / (f - n);
  3867. var d = -2.0 * f * n / (f - n);
  3868. 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);
  3869. };
  3870. /**
  3871. * 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.
  3872. */
  3873. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3874. var matrix = Matrix.Zero();
  3875. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3876. return matrix;
  3877. };
  3878. /**
  3879. * 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.
  3880. */
  3881. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3882. //alternatively this could be expressed as:
  3883. // m = PerspectiveFovLHToRef
  3884. // m[10] *= -1.0;
  3885. // m[11] *= -1.0;
  3886. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3887. var n = znear;
  3888. var f = zfar;
  3889. var t = 1.0 / (Math.tan(fov * 0.5));
  3890. var a = isVerticalFovFixed ? (t / aspect) : t;
  3891. var b = isVerticalFovFixed ? t : (t * aspect);
  3892. var c = -(f + n) / (f - n);
  3893. var d = -2 * f * n / (f - n);
  3894. 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);
  3895. };
  3896. /**
  3897. * 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.
  3898. */
  3899. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3900. if (rightHanded === void 0) { rightHanded = false; }
  3901. var rightHandedFactor = rightHanded ? -1 : 1;
  3902. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3903. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3904. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3905. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3906. var xScale = 2.0 / (leftTan + rightTan);
  3907. var yScale = 2.0 / (upTan + downTan);
  3908. result.m[0] = xScale;
  3909. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3910. result.m[5] = yScale;
  3911. result.m[6] = result.m[7] = 0.0;
  3912. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3913. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3914. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3915. result.m[10] = -zfar / (znear - zfar);
  3916. result.m[11] = 1.0 * rightHandedFactor;
  3917. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3918. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3919. // result.m[14] = (znear * zfar) / (znear - zfar);
  3920. result._markAsUpdated();
  3921. };
  3922. /**
  3923. * Returns the final transformation matrix : world * view * projection * viewport
  3924. */
  3925. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3926. var cw = viewport.width;
  3927. var ch = viewport.height;
  3928. var cx = viewport.x;
  3929. var cy = viewport.y;
  3930. 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);
  3931. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3932. };
  3933. /**
  3934. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3935. */
  3936. Matrix.GetAsMatrix2x2 = function (matrix) {
  3937. return new Float32Array([
  3938. matrix.m[0], matrix.m[1],
  3939. matrix.m[4], matrix.m[5]
  3940. ]);
  3941. };
  3942. /**
  3943. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3944. */
  3945. Matrix.GetAsMatrix3x3 = function (matrix) {
  3946. return new Float32Array([
  3947. matrix.m[0], matrix.m[1], matrix.m[2],
  3948. matrix.m[4], matrix.m[5], matrix.m[6],
  3949. matrix.m[8], matrix.m[9], matrix.m[10]
  3950. ]);
  3951. };
  3952. /**
  3953. * Compute the transpose of the passed Matrix.
  3954. * Returns a new Matrix.
  3955. */
  3956. Matrix.Transpose = function (matrix) {
  3957. var result = new Matrix();
  3958. Matrix.TransposeToRef(matrix, result);
  3959. return result;
  3960. };
  3961. /**
  3962. * Compute the transpose of the passed Matrix and store it in the result matrix.
  3963. */
  3964. Matrix.TransposeToRef = function (matrix, result) {
  3965. result.m[0] = matrix.m[0];
  3966. result.m[1] = matrix.m[4];
  3967. result.m[2] = matrix.m[8];
  3968. result.m[3] = matrix.m[12];
  3969. result.m[4] = matrix.m[1];
  3970. result.m[5] = matrix.m[5];
  3971. result.m[6] = matrix.m[9];
  3972. result.m[7] = matrix.m[13];
  3973. result.m[8] = matrix.m[2];
  3974. result.m[9] = matrix.m[6];
  3975. result.m[10] = matrix.m[10];
  3976. result.m[11] = matrix.m[14];
  3977. result.m[12] = matrix.m[3];
  3978. result.m[13] = matrix.m[7];
  3979. result.m[14] = matrix.m[11];
  3980. result.m[15] = matrix.m[15];
  3981. };
  3982. /**
  3983. * Returns a new Matrix as the reflection matrix across the passed plane.
  3984. */
  3985. Matrix.Reflection = function (plane) {
  3986. var matrix = new Matrix();
  3987. Matrix.ReflectionToRef(plane, matrix);
  3988. return matrix;
  3989. };
  3990. /**
  3991. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3992. */
  3993. Matrix.ReflectionToRef = function (plane, result) {
  3994. plane.normalize();
  3995. var x = plane.normal.x;
  3996. var y = plane.normal.y;
  3997. var z = plane.normal.z;
  3998. var temp = -2 * x;
  3999. var temp2 = -2 * y;
  4000. var temp3 = -2 * z;
  4001. result.m[0] = (temp * x) + 1;
  4002. result.m[1] = temp2 * x;
  4003. result.m[2] = temp3 * x;
  4004. result.m[3] = 0.0;
  4005. result.m[4] = temp * y;
  4006. result.m[5] = (temp2 * y) + 1;
  4007. result.m[6] = temp3 * y;
  4008. result.m[7] = 0.0;
  4009. result.m[8] = temp * z;
  4010. result.m[9] = temp2 * z;
  4011. result.m[10] = (temp3 * z) + 1;
  4012. result.m[11] = 0.0;
  4013. result.m[12] = temp * plane.d;
  4014. result.m[13] = temp2 * plane.d;
  4015. result.m[14] = temp3 * plane.d;
  4016. result.m[15] = 1.0;
  4017. result._markAsUpdated();
  4018. };
  4019. /**
  4020. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  4021. */
  4022. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  4023. result.m[0] = xaxis.x;
  4024. result.m[1] = xaxis.y;
  4025. result.m[2] = xaxis.z;
  4026. result.m[3] = 0.0;
  4027. result.m[4] = yaxis.x;
  4028. result.m[5] = yaxis.y;
  4029. result.m[6] = yaxis.z;
  4030. result.m[7] = 0.0;
  4031. result.m[8] = zaxis.x;
  4032. result.m[9] = zaxis.y;
  4033. result.m[10] = zaxis.z;
  4034. result.m[11] = 0.0;
  4035. result.m[12] = 0.0;
  4036. result.m[13] = 0.0;
  4037. result.m[14] = 0.0;
  4038. result.m[15] = 1.0;
  4039. result._markAsUpdated();
  4040. };
  4041. /**
  4042. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  4043. */
  4044. Matrix.FromQuaternionToRef = function (quat, result) {
  4045. var xx = quat.x * quat.x;
  4046. var yy = quat.y * quat.y;
  4047. var zz = quat.z * quat.z;
  4048. var xy = quat.x * quat.y;
  4049. var zw = quat.z * quat.w;
  4050. var zx = quat.z * quat.x;
  4051. var yw = quat.y * quat.w;
  4052. var yz = quat.y * quat.z;
  4053. var xw = quat.x * quat.w;
  4054. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4055. result.m[1] = 2.0 * (xy + zw);
  4056. result.m[2] = 2.0 * (zx - yw);
  4057. result.m[3] = 0.0;
  4058. result.m[4] = 2.0 * (xy - zw);
  4059. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4060. result.m[6] = 2.0 * (yz + xw);
  4061. result.m[7] = 0.0;
  4062. result.m[8] = 2.0 * (zx + yw);
  4063. result.m[9] = 2.0 * (yz - xw);
  4064. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4065. result.m[11] = 0.0;
  4066. result.m[12] = 0.0;
  4067. result.m[13] = 0.0;
  4068. result.m[14] = 0.0;
  4069. result.m[15] = 1.0;
  4070. result._markAsUpdated();
  4071. };
  4072. Matrix._tempQuaternion = new Quaternion();
  4073. Matrix._xAxis = Vector3.Zero();
  4074. Matrix._yAxis = Vector3.Zero();
  4075. Matrix._zAxis = Vector3.Zero();
  4076. Matrix._updateFlagSeed = 0;
  4077. Matrix._identityReadOnly = Matrix.Identity();
  4078. return Matrix;
  4079. }());
  4080. BABYLON.Matrix = Matrix;
  4081. var Plane = /** @class */ (function () {
  4082. /**
  4083. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  4084. */
  4085. function Plane(a, b, c, d) {
  4086. this.normal = new Vector3(a, b, c);
  4087. this.d = d;
  4088. }
  4089. /**
  4090. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4091. */
  4092. Plane.prototype.asArray = function () {
  4093. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4094. };
  4095. // Methods
  4096. /**
  4097. * Returns a new plane copied from the current Plane.
  4098. */
  4099. Plane.prototype.clone = function () {
  4100. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4101. };
  4102. /**
  4103. * Returns the string "Plane".
  4104. */
  4105. Plane.prototype.getClassName = function () {
  4106. return "Plane";
  4107. };
  4108. /**
  4109. * Returns the Plane hash code.
  4110. */
  4111. Plane.prototype.getHashCode = function () {
  4112. var hash = this.normal.getHashCode();
  4113. hash = (hash * 397) ^ (this.d || 0);
  4114. return hash;
  4115. };
  4116. /**
  4117. * Normalize the current Plane in place.
  4118. * Returns the updated Plane.
  4119. */
  4120. Plane.prototype.normalize = function () {
  4121. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  4122. var magnitude = 0.0;
  4123. if (norm !== 0) {
  4124. magnitude = 1.0 / norm;
  4125. }
  4126. this.normal.x *= magnitude;
  4127. this.normal.y *= magnitude;
  4128. this.normal.z *= magnitude;
  4129. this.d *= magnitude;
  4130. return this;
  4131. };
  4132. /**
  4133. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  4134. */
  4135. Plane.prototype.transform = function (transformation) {
  4136. var transposedMatrix = Matrix.Transpose(transformation);
  4137. var x = this.normal.x;
  4138. var y = this.normal.y;
  4139. var z = this.normal.z;
  4140. var d = this.d;
  4141. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  4142. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  4143. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  4144. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  4145. return new Plane(normalX, normalY, normalZ, finalD);
  4146. };
  4147. /**
  4148. * Returns the dot product (float) of the point coordinates and the plane normal.
  4149. */
  4150. Plane.prototype.dotCoordinate = function (point) {
  4151. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  4152. };
  4153. /**
  4154. * Updates the current Plane from the plane defined by the three passed points.
  4155. * Returns the updated Plane.
  4156. */
  4157. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  4158. var x1 = point2.x - point1.x;
  4159. var y1 = point2.y - point1.y;
  4160. var z1 = point2.z - point1.z;
  4161. var x2 = point3.x - point1.x;
  4162. var y2 = point3.y - point1.y;
  4163. var z2 = point3.z - point1.z;
  4164. var yz = (y1 * z2) - (z1 * y2);
  4165. var xz = (z1 * x2) - (x1 * z2);
  4166. var xy = (x1 * y2) - (y1 * x2);
  4167. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  4168. var invPyth;
  4169. if (pyth !== 0) {
  4170. invPyth = 1.0 / pyth;
  4171. }
  4172. else {
  4173. invPyth = 0.0;
  4174. }
  4175. this.normal.x = yz * invPyth;
  4176. this.normal.y = xz * invPyth;
  4177. this.normal.z = xy * invPyth;
  4178. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  4179. return this;
  4180. };
  4181. /**
  4182. * Boolean : True is the vector "direction" is the same side than the plane normal.
  4183. */
  4184. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  4185. var dot = Vector3.Dot(this.normal, direction);
  4186. return (dot <= epsilon);
  4187. };
  4188. /**
  4189. * Returns the signed distance (float) from the passed point to the Plane.
  4190. */
  4191. Plane.prototype.signedDistanceTo = function (point) {
  4192. return Vector3.Dot(point, this.normal) + this.d;
  4193. };
  4194. // Statics
  4195. /**
  4196. * Returns a new Plane from the passed array.
  4197. */
  4198. Plane.FromArray = function (array) {
  4199. return new Plane(array[0], array[1], array[2], array[3]);
  4200. };
  4201. /**
  4202. * Returns a new Plane defined by the three passed points.
  4203. */
  4204. Plane.FromPoints = function (point1, point2, point3) {
  4205. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4206. result.copyFromPoints(point1, point2, point3);
  4207. return result;
  4208. };
  4209. /**
  4210. * Returns a new Plane the normal vector to this plane at the passed origin point.
  4211. * Note : the vector "normal" is updated because normalized.
  4212. */
  4213. Plane.FromPositionAndNormal = function (origin, normal) {
  4214. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4215. normal.normalize();
  4216. result.normal = normal;
  4217. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4218. return result;
  4219. };
  4220. /**
  4221. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  4222. */
  4223. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  4224. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4225. return Vector3.Dot(point, normal) + d;
  4226. };
  4227. return Plane;
  4228. }());
  4229. BABYLON.Plane = Plane;
  4230. var Viewport = /** @class */ (function () {
  4231. /**
  4232. * Creates a Viewport object located at (x, y) and sized (width, height).
  4233. */
  4234. function Viewport(x, y, width, height) {
  4235. this.x = x;
  4236. this.y = y;
  4237. this.width = width;
  4238. this.height = height;
  4239. }
  4240. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  4241. if (renderWidthOrEngine.getRenderWidth) {
  4242. var engine = renderWidthOrEngine;
  4243. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4244. }
  4245. var renderWidth = renderWidthOrEngine;
  4246. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4247. };
  4248. /**
  4249. * Returns a new Viewport copied from the current one.
  4250. */
  4251. Viewport.prototype.clone = function () {
  4252. return new Viewport(this.x, this.y, this.width, this.height);
  4253. };
  4254. return Viewport;
  4255. }());
  4256. BABYLON.Viewport = Viewport;
  4257. var Frustum = /** @class */ (function () {
  4258. function Frustum() {
  4259. }
  4260. /**
  4261. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4262. */
  4263. Frustum.GetPlanes = function (transform) {
  4264. var frustumPlanes = [];
  4265. for (var index = 0; index < 6; index++) {
  4266. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4267. }
  4268. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4269. return frustumPlanes;
  4270. };
  4271. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  4272. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  4273. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  4274. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  4275. frustumPlane.d = transform.m[15] + transform.m[14];
  4276. frustumPlane.normalize();
  4277. };
  4278. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  4279. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  4280. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  4281. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  4282. frustumPlane.d = transform.m[15] - transform.m[14];
  4283. frustumPlane.normalize();
  4284. };
  4285. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  4286. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  4287. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  4288. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  4289. frustumPlane.d = transform.m[15] + transform.m[12];
  4290. frustumPlane.normalize();
  4291. };
  4292. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  4293. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  4294. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  4295. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  4296. frustumPlane.d = transform.m[15] - transform.m[12];
  4297. frustumPlane.normalize();
  4298. };
  4299. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  4300. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  4301. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  4302. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  4303. frustumPlane.d = transform.m[15] - transform.m[13];
  4304. frustumPlane.normalize();
  4305. };
  4306. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  4307. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  4308. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  4309. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  4310. frustumPlane.d = transform.m[15] + transform.m[13];
  4311. frustumPlane.normalize();
  4312. };
  4313. /**
  4314. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4315. */
  4316. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4317. // Near
  4318. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  4319. // Far
  4320. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  4321. // Left
  4322. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  4323. // Right
  4324. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  4325. // Top
  4326. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  4327. // Bottom
  4328. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  4329. };
  4330. return Frustum;
  4331. }());
  4332. BABYLON.Frustum = Frustum;
  4333. var Space;
  4334. (function (Space) {
  4335. Space[Space["LOCAL"] = 0] = "LOCAL";
  4336. Space[Space["WORLD"] = 1] = "WORLD";
  4337. Space[Space["BONE"] = 2] = "BONE";
  4338. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4339. var Axis = /** @class */ (function () {
  4340. function Axis() {
  4341. }
  4342. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4343. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4344. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4345. return Axis;
  4346. }());
  4347. BABYLON.Axis = Axis;
  4348. ;
  4349. var BezierCurve = /** @class */ (function () {
  4350. function BezierCurve() {
  4351. }
  4352. /**
  4353. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4354. */
  4355. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4356. // Extract X (which is equal to time here)
  4357. var f0 = 1 - 3 * x2 + 3 * x1;
  4358. var f1 = 3 * x2 - 6 * x1;
  4359. var f2 = 3 * x1;
  4360. var refinedT = t;
  4361. for (var i = 0; i < 5; i++) {
  4362. var refinedT2 = refinedT * refinedT;
  4363. var refinedT3 = refinedT2 * refinedT;
  4364. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4365. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4366. refinedT -= (x - t) * slope;
  4367. refinedT = Math.min(1, Math.max(0, refinedT));
  4368. }
  4369. // Resolve cubic bezier for the given x
  4370. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4371. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4372. Math.pow(refinedT, 3);
  4373. };
  4374. return BezierCurve;
  4375. }());
  4376. BABYLON.BezierCurve = BezierCurve;
  4377. var Orientation;
  4378. (function (Orientation) {
  4379. Orientation[Orientation["CW"] = 0] = "CW";
  4380. Orientation[Orientation["CCW"] = 1] = "CCW";
  4381. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4382. var Angle = /** @class */ (function () {
  4383. /**
  4384. * Creates an Angle object of "radians" radians (float).
  4385. */
  4386. function Angle(radians) {
  4387. var _this = this;
  4388. /**
  4389. * Returns the Angle value in degrees (float).
  4390. */
  4391. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4392. /**
  4393. * Returns the Angle value in radians (float).
  4394. */
  4395. this.radians = function () { return _this._radians; };
  4396. this._radians = radians;
  4397. if (this._radians < 0.0)
  4398. this._radians += (2.0 * Math.PI);
  4399. }
  4400. /**
  4401. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4402. */
  4403. Angle.BetweenTwoPoints = function (a, b) {
  4404. var delta = b.subtract(a);
  4405. var theta = Math.atan2(delta.y, delta.x);
  4406. return new Angle(theta);
  4407. };
  4408. /**
  4409. * Returns a new Angle object from the passed float in radians.
  4410. */
  4411. Angle.FromRadians = function (radians) {
  4412. return new Angle(radians);
  4413. };
  4414. /**
  4415. * Returns a new Angle object from the passed float in degrees.
  4416. */
  4417. Angle.FromDegrees = function (degrees) {
  4418. return new Angle(degrees * Math.PI / 180.0);
  4419. };
  4420. return Angle;
  4421. }());
  4422. BABYLON.Angle = Angle;
  4423. var Arc2 = /** @class */ (function () {
  4424. /**
  4425. * Creates an Arc object from the three passed points : start, middle and end.
  4426. */
  4427. function Arc2(startPoint, midPoint, endPoint) {
  4428. this.startPoint = startPoint;
  4429. this.midPoint = midPoint;
  4430. this.endPoint = endPoint;
  4431. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4432. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4433. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4434. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4435. 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);
  4436. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4437. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4438. var a1 = this.startAngle.degrees();
  4439. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4440. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4441. // angles correction
  4442. if (a2 - a1 > +180.0)
  4443. a2 -= 360.0;
  4444. if (a2 - a1 < -180.0)
  4445. a2 += 360.0;
  4446. if (a3 - a2 > +180.0)
  4447. a3 -= 360.0;
  4448. if (a3 - a2 < -180.0)
  4449. a3 += 360.0;
  4450. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4451. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4452. }
  4453. return Arc2;
  4454. }());
  4455. BABYLON.Arc2 = Arc2;
  4456. var Path2 = /** @class */ (function () {
  4457. /**
  4458. * Creates a Path2 object from the starting 2D coordinates x and y.
  4459. */
  4460. function Path2(x, y) {
  4461. this._points = new Array();
  4462. this._length = 0.0;
  4463. this.closed = false;
  4464. this._points.push(new Vector2(x, y));
  4465. }
  4466. /**
  4467. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4468. * Returns the updated Path2.
  4469. */
  4470. Path2.prototype.addLineTo = function (x, y) {
  4471. if (this.closed) {
  4472. //Tools.Error("cannot add lines to closed paths");
  4473. return this;
  4474. }
  4475. var newPoint = new Vector2(x, y);
  4476. var previousPoint = this._points[this._points.length - 1];
  4477. this._points.push(newPoint);
  4478. this._length += newPoint.subtract(previousPoint).length();
  4479. return this;
  4480. };
  4481. /**
  4482. * 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.
  4483. * Returns the updated Path2.
  4484. */
  4485. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4486. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4487. if (this.closed) {
  4488. //Tools.Error("cannot add arcs to closed paths");
  4489. return this;
  4490. }
  4491. var startPoint = this._points[this._points.length - 1];
  4492. var midPoint = new Vector2(midX, midY);
  4493. var endPoint = new Vector2(endX, endY);
  4494. var arc = new Arc2(startPoint, midPoint, endPoint);
  4495. var increment = arc.angle.radians() / numberOfSegments;
  4496. if (arc.orientation === Orientation.CW)
  4497. increment *= -1;
  4498. var currentAngle = arc.startAngle.radians() + increment;
  4499. for (var i = 0; i < numberOfSegments; i++) {
  4500. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4501. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4502. this.addLineTo(x, y);
  4503. currentAngle += increment;
  4504. }
  4505. return this;
  4506. };
  4507. /**
  4508. * Closes the Path2.
  4509. * Returns the Path2.
  4510. */
  4511. Path2.prototype.close = function () {
  4512. this.closed = true;
  4513. return this;
  4514. };
  4515. /**
  4516. * Returns the Path2 total length (float).
  4517. */
  4518. Path2.prototype.length = function () {
  4519. var result = this._length;
  4520. if (!this.closed) {
  4521. var lastPoint = this._points[this._points.length - 1];
  4522. var firstPoint = this._points[0];
  4523. result += (firstPoint.subtract(lastPoint).length());
  4524. }
  4525. return result;
  4526. };
  4527. /**
  4528. * Returns the Path2 internal array of points.
  4529. */
  4530. Path2.prototype.getPoints = function () {
  4531. return this._points;
  4532. };
  4533. /**
  4534. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4535. */
  4536. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4537. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4538. //Tools.Error("normalized length position should be between 0 and 1.");
  4539. return Vector2.Zero();
  4540. }
  4541. var lengthPosition = normalizedLengthPosition * this.length();
  4542. var previousOffset = 0;
  4543. for (var i = 0; i < this._points.length; i++) {
  4544. var j = (i + 1) % this._points.length;
  4545. var a = this._points[i];
  4546. var b = this._points[j];
  4547. var bToA = b.subtract(a);
  4548. var nextOffset = (bToA.length() + previousOffset);
  4549. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4550. var dir = bToA.normalize();
  4551. var localOffset = lengthPosition - previousOffset;
  4552. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4553. }
  4554. previousOffset = nextOffset;
  4555. }
  4556. //Tools.Error("internal error");
  4557. return Vector2.Zero();
  4558. };
  4559. /**
  4560. * Returns a new Path2 starting at the coordinates (x, y).
  4561. */
  4562. Path2.StartingAt = function (x, y) {
  4563. return new Path2(x, y);
  4564. };
  4565. return Path2;
  4566. }());
  4567. BABYLON.Path2 = Path2;
  4568. var Path3D = /** @class */ (function () {
  4569. /**
  4570. * new Path3D(path, normal, raw)
  4571. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4572. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4573. * path : an array of Vector3, the curve axis of the Path3D
  4574. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4575. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4576. */
  4577. function Path3D(path, firstNormal, raw) {
  4578. if (firstNormal === void 0) { firstNormal = null; }
  4579. this.path = path;
  4580. this._curve = new Array();
  4581. this._distances = new Array();
  4582. this._tangents = new Array();
  4583. this._normals = new Array();
  4584. this._binormals = new Array();
  4585. for (var p = 0; p < path.length; p++) {
  4586. this._curve[p] = path[p].clone(); // hard copy
  4587. }
  4588. this._raw = raw || false;
  4589. this._compute(firstNormal);
  4590. }
  4591. /**
  4592. * Returns the Path3D array of successive Vector3 designing its curve.
  4593. */
  4594. Path3D.prototype.getCurve = function () {
  4595. return this._curve;
  4596. };
  4597. /**
  4598. * Returns an array populated with tangent vectors on each Path3D curve point.
  4599. */
  4600. Path3D.prototype.getTangents = function () {
  4601. return this._tangents;
  4602. };
  4603. /**
  4604. * Returns an array populated with normal vectors on each Path3D curve point.
  4605. */
  4606. Path3D.prototype.getNormals = function () {
  4607. return this._normals;
  4608. };
  4609. /**
  4610. * Returns an array populated with binormal vectors on each Path3D curve point.
  4611. */
  4612. Path3D.prototype.getBinormals = function () {
  4613. return this._binormals;
  4614. };
  4615. /**
  4616. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4617. */
  4618. Path3D.prototype.getDistances = function () {
  4619. return this._distances;
  4620. };
  4621. /**
  4622. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4623. * Returns the same object updated.
  4624. */
  4625. Path3D.prototype.update = function (path, firstNormal) {
  4626. if (firstNormal === void 0) { firstNormal = null; }
  4627. for (var p = 0; p < path.length; p++) {
  4628. this._curve[p].x = path[p].x;
  4629. this._curve[p].y = path[p].y;
  4630. this._curve[p].z = path[p].z;
  4631. }
  4632. this._compute(firstNormal);
  4633. return this;
  4634. };
  4635. // private function compute() : computes tangents, normals and binormals
  4636. Path3D.prototype._compute = function (firstNormal) {
  4637. var l = this._curve.length;
  4638. // first and last tangents
  4639. this._tangents[0] = this._getFirstNonNullVector(0);
  4640. if (!this._raw) {
  4641. this._tangents[0].normalize();
  4642. }
  4643. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4644. if (!this._raw) {
  4645. this._tangents[l - 1].normalize();
  4646. }
  4647. // normals and binormals at first point : arbitrary vector with _normalVector()
  4648. var tg0 = this._tangents[0];
  4649. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4650. this._normals[0] = pp0;
  4651. if (!this._raw) {
  4652. this._normals[0].normalize();
  4653. }
  4654. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4655. if (!this._raw) {
  4656. this._binormals[0].normalize();
  4657. }
  4658. this._distances[0] = 0.0;
  4659. // normals and binormals : next points
  4660. var prev; // previous vector (segment)
  4661. var cur; // current vector (segment)
  4662. var curTang; // current tangent
  4663. // previous normal
  4664. var prevBinor; // previous binormal
  4665. for (var i = 1; i < l; i++) {
  4666. // tangents
  4667. prev = this._getLastNonNullVector(i);
  4668. if (i < l - 1) {
  4669. cur = this._getFirstNonNullVector(i);
  4670. this._tangents[i] = prev.add(cur);
  4671. this._tangents[i].normalize();
  4672. }
  4673. this._distances[i] = this._distances[i - 1] + prev.length();
  4674. // normals and binormals
  4675. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4676. curTang = this._tangents[i];
  4677. prevBinor = this._binormals[i - 1];
  4678. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4679. if (!this._raw) {
  4680. this._normals[i].normalize();
  4681. }
  4682. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4683. if (!this._raw) {
  4684. this._binormals[i].normalize();
  4685. }
  4686. }
  4687. };
  4688. // private function getFirstNonNullVector(index)
  4689. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4690. Path3D.prototype._getFirstNonNullVector = function (index) {
  4691. var i = 1;
  4692. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4693. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4694. i++;
  4695. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4696. }
  4697. return nNVector;
  4698. };
  4699. // private function getLastNonNullVector(index)
  4700. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4701. Path3D.prototype._getLastNonNullVector = function (index) {
  4702. var i = 1;
  4703. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4704. while (nLVector.length() === 0 && index > i + 1) {
  4705. i++;
  4706. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4707. }
  4708. return nLVector;
  4709. };
  4710. // private function normalVector(v0, vt, va) :
  4711. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4712. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4713. Path3D.prototype._normalVector = function (v0, vt, va) {
  4714. var normal0;
  4715. var tgl = vt.length();
  4716. if (tgl === 0.0) {
  4717. tgl = 1.0;
  4718. }
  4719. if (va === undefined || va === null) {
  4720. var point;
  4721. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4722. point = new Vector3(0.0, -1.0, 0.0);
  4723. }
  4724. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4725. point = new Vector3(1.0, 0.0, 0.0);
  4726. }
  4727. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4728. point = new Vector3(0.0, 0.0, 1.0);
  4729. }
  4730. else {
  4731. point = Vector3.Zero();
  4732. }
  4733. normal0 = Vector3.Cross(vt, point);
  4734. }
  4735. else {
  4736. normal0 = Vector3.Cross(vt, va);
  4737. Vector3.CrossToRef(normal0, vt, normal0);
  4738. }
  4739. normal0.normalize();
  4740. return normal0;
  4741. };
  4742. return Path3D;
  4743. }());
  4744. BABYLON.Path3D = Path3D;
  4745. var Curve3 = /** @class */ (function () {
  4746. /**
  4747. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4748. * A Curve3 is designed from a series of successive Vector3.
  4749. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4750. */
  4751. function Curve3(points) {
  4752. this._length = 0.0;
  4753. this._points = points;
  4754. this._length = this._computeLength(points);
  4755. }
  4756. /**
  4757. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4758. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4759. * @param v1 (Vector3) the control point
  4760. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4761. * @param nbPoints (integer) the wanted number of points in the curve
  4762. */
  4763. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4764. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4765. var bez = new Array();
  4766. var equation = function (t, val0, val1, val2) {
  4767. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4768. return res;
  4769. };
  4770. for (var i = 0; i <= nbPoints; i++) {
  4771. 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)));
  4772. }
  4773. return new Curve3(bez);
  4774. };
  4775. /**
  4776. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4777. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4778. * @param v1 (Vector3) the first control point
  4779. * @param v2 (Vector3) the second control point
  4780. * @param v3 (Vector3) the end point of the Cubic Bezier
  4781. * @param nbPoints (integer) the wanted number of points in the curve
  4782. */
  4783. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4784. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4785. var bez = new Array();
  4786. var equation = function (t, val0, val1, val2, val3) {
  4787. 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;
  4788. return res;
  4789. };
  4790. for (var i = 0; i <= nbPoints; i++) {
  4791. 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)));
  4792. }
  4793. return new Curve3(bez);
  4794. };
  4795. /**
  4796. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4797. * @param p1 (Vector3) the origin point of the Hermite Spline
  4798. * @param t1 (Vector3) the tangent vector at the origin point
  4799. * @param p2 (Vector3) the end point of the Hermite Spline
  4800. * @param t2 (Vector3) the tangent vector at the end point
  4801. * @param nbPoints (integer) the wanted number of points in the curve
  4802. */
  4803. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4804. var hermite = new Array();
  4805. var step = 1.0 / nbPoints;
  4806. for (var i = 0; i <= nbPoints; i++) {
  4807. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4808. }
  4809. return new Curve3(hermite);
  4810. };
  4811. /**
  4812. * Returns a Curve3 object along a CatmullRom Spline curve :
  4813. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4814. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4815. */
  4816. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4817. var totalPoints = new Array();
  4818. totalPoints.push(points[0].clone());
  4819. Array.prototype.push.apply(totalPoints, points);
  4820. totalPoints.push(points[points.length - 1].clone());
  4821. var catmullRom = new Array();
  4822. var step = 1.0 / nbPoints;
  4823. var amount = 0.0;
  4824. for (var i = 0; i < totalPoints.length - 3; i++) {
  4825. amount = 0;
  4826. for (var c = 0; c < nbPoints; c++) {
  4827. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4828. amount += step;
  4829. }
  4830. }
  4831. i--;
  4832. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4833. return new Curve3(catmullRom);
  4834. };
  4835. /**
  4836. * Returns the Curve3 stored array of successive Vector3
  4837. */
  4838. Curve3.prototype.getPoints = function () {
  4839. return this._points;
  4840. };
  4841. /**
  4842. * Returns the computed length (float) of the curve.
  4843. */
  4844. Curve3.prototype.length = function () {
  4845. return this._length;
  4846. };
  4847. /**
  4848. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4849. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4850. * curveA and curveB keep unchanged.
  4851. */
  4852. Curve3.prototype.continue = function (curve) {
  4853. var lastPoint = this._points[this._points.length - 1];
  4854. var continuedPoints = this._points.slice();
  4855. var curvePoints = curve.getPoints();
  4856. for (var i = 1; i < curvePoints.length; i++) {
  4857. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4858. }
  4859. var continuedCurve = new Curve3(continuedPoints);
  4860. return continuedCurve;
  4861. };
  4862. Curve3.prototype._computeLength = function (path) {
  4863. var l = 0;
  4864. for (var i = 1; i < path.length; i++) {
  4865. l += (path[i].subtract(path[i - 1])).length();
  4866. }
  4867. return l;
  4868. };
  4869. return Curve3;
  4870. }());
  4871. BABYLON.Curve3 = Curve3;
  4872. // Vertex formats
  4873. var PositionNormalVertex = /** @class */ (function () {
  4874. function PositionNormalVertex(position, normal) {
  4875. if (position === void 0) { position = Vector3.Zero(); }
  4876. if (normal === void 0) { normal = Vector3.Up(); }
  4877. this.position = position;
  4878. this.normal = normal;
  4879. }
  4880. PositionNormalVertex.prototype.clone = function () {
  4881. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4882. };
  4883. return PositionNormalVertex;
  4884. }());
  4885. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4886. var PositionNormalTextureVertex = /** @class */ (function () {
  4887. function PositionNormalTextureVertex(position, normal, uv) {
  4888. if (position === void 0) { position = Vector3.Zero(); }
  4889. if (normal === void 0) { normal = Vector3.Up(); }
  4890. if (uv === void 0) { uv = Vector2.Zero(); }
  4891. this.position = position;
  4892. this.normal = normal;
  4893. this.uv = uv;
  4894. }
  4895. PositionNormalTextureVertex.prototype.clone = function () {
  4896. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4897. };
  4898. return PositionNormalTextureVertex;
  4899. }());
  4900. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4901. // Temporary pre-allocated objects for engine internal use
  4902. // usage in any internal function :
  4903. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4904. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4905. var Tmp = /** @class */ (function () {
  4906. function Tmp() {
  4907. }
  4908. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4909. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4910. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4911. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4912. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4913. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4914. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4915. Matrix.Zero(), Matrix.Zero(),
  4916. Matrix.Zero(), Matrix.Zero(),
  4917. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4918. return Tmp;
  4919. }());
  4920. BABYLON.Tmp = Tmp;
  4921. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4922. var MathTmp = /** @class */ (function () {
  4923. function MathTmp() {
  4924. }
  4925. MathTmp.Vector3 = [Vector3.Zero()];
  4926. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4927. MathTmp.Quaternion = [Quaternion.Zero()];
  4928. return MathTmp;
  4929. }());
  4930. })(BABYLON || (BABYLON = {}));
  4931. //# sourceMappingURL=babylon.math.js.map
  4932. var BABYLON;
  4933. (function (BABYLON) {
  4934. var Scalar = /** @class */ (function () {
  4935. function Scalar() {
  4936. }
  4937. /**
  4938. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  4939. */
  4940. Scalar.WithinEpsilon = function (a, b, epsilon) {
  4941. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4942. var num = a - b;
  4943. return -epsilon <= num && num <= epsilon;
  4944. };
  4945. /**
  4946. * Returns a string : the upper case translation of the number i to hexadecimal.
  4947. */
  4948. Scalar.ToHex = function (i) {
  4949. var str = i.toString(16);
  4950. if (i <= 15) {
  4951. return ("0" + str).toUpperCase();
  4952. }
  4953. return str.toUpperCase();
  4954. };
  4955. /**
  4956. * Returns -1 if value is negative and +1 is value is positive.
  4957. * Returns the value itself if it's equal to zero.
  4958. */
  4959. Scalar.Sign = function (value) {
  4960. value = +value; // convert to a number
  4961. if (value === 0 || isNaN(value))
  4962. return value;
  4963. return value > 0 ? 1 : -1;
  4964. };
  4965. /**
  4966. * Returns the value itself if it's between min and max.
  4967. * Returns min if the value is lower than min.
  4968. * Returns max if the value is greater than max.
  4969. */
  4970. Scalar.Clamp = function (value, min, max) {
  4971. if (min === void 0) { min = 0; }
  4972. if (max === void 0) { max = 1; }
  4973. return Math.min(max, Math.max(min, value));
  4974. };
  4975. /**
  4976. * Returns the log2 of value.
  4977. */
  4978. Scalar.Log2 = function (value) {
  4979. return Math.log(value) * Math.LOG2E;
  4980. };
  4981. /**
  4982. * Loops the value, so that it is never larger than length and never smaller than 0.
  4983. *
  4984. * This is similar to the modulo operator but it works with floating point numbers.
  4985. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  4986. * With t = 5 and length = 2.5, the result would be 0.0.
  4987. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  4988. */
  4989. Scalar.Repeat = function (value, length) {
  4990. return value - Math.floor(value / length) * length;
  4991. };
  4992. /**
  4993. * Normalize the value between 0.0 and 1.0 using min and max values
  4994. */
  4995. Scalar.Normalize = function (value, min, max) {
  4996. return (value - min) / (max - min);
  4997. };
  4998. /**
  4999. * Denormalize the value from 0.0 and 1.0 using min and max values
  5000. */
  5001. Scalar.Denormalize = function (normalized, min, max) {
  5002. return (normalized * (max - min) + min);
  5003. };
  5004. /**
  5005. * Calculates the shortest difference between two given angles given in degrees.
  5006. */
  5007. Scalar.DeltaAngle = function (current, target) {
  5008. var num = Scalar.Repeat(target - current, 360.0);
  5009. if (num > 180.0) {
  5010. num -= 360.0;
  5011. }
  5012. return num;
  5013. };
  5014. /**
  5015. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  5016. *
  5017. * The returned value will move back and forth between 0 and length
  5018. */
  5019. Scalar.PingPong = function (tx, length) {
  5020. var t = Scalar.Repeat(tx, length * 2.0);
  5021. return length - Math.abs(t - length);
  5022. };
  5023. /**
  5024. * Interpolates between min and max with smoothing at the limits.
  5025. *
  5026. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  5027. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  5028. */
  5029. Scalar.SmoothStep = function (from, to, tx) {
  5030. var t = Scalar.Clamp(tx);
  5031. t = -2.0 * t * t * t + 3.0 * t * t;
  5032. return to * t + from * (1.0 - t);
  5033. };
  5034. /**
  5035. * Moves a value current towards target.
  5036. *
  5037. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  5038. * Negative values of maxDelta pushes the value away from target.
  5039. */
  5040. Scalar.MoveTowards = function (current, target, maxDelta) {
  5041. var result = 0;
  5042. if (Math.abs(target - current) <= maxDelta) {
  5043. result = target;
  5044. }
  5045. else {
  5046. result = current + Scalar.Sign(target - current) * maxDelta;
  5047. }
  5048. return result;
  5049. };
  5050. /**
  5051. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5052. *
  5053. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  5054. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  5055. */
  5056. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  5057. var num = Scalar.DeltaAngle(current, target);
  5058. var result = 0;
  5059. if (-maxDelta < num && num < maxDelta) {
  5060. result = target;
  5061. }
  5062. else {
  5063. target = current + num;
  5064. result = Scalar.MoveTowards(current, target, maxDelta);
  5065. }
  5066. return result;
  5067. };
  5068. /**
  5069. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  5070. */
  5071. Scalar.Lerp = function (start, end, amount) {
  5072. return start + ((end - start) * amount);
  5073. };
  5074. /**
  5075. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5076. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  5077. */
  5078. Scalar.LerpAngle = function (start, end, amount) {
  5079. var num = Scalar.Repeat(end - start, 360.0);
  5080. if (num > 180.0) {
  5081. num -= 360.0;
  5082. }
  5083. return start + num * Scalar.Clamp(amount);
  5084. };
  5085. /**
  5086. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  5087. */
  5088. Scalar.InverseLerp = function (a, b, value) {
  5089. var result = 0;
  5090. if (a != b) {
  5091. result = Scalar.Clamp((value - a) / (b - a));
  5092. }
  5093. else {
  5094. result = 0.0;
  5095. }
  5096. return result;
  5097. };
  5098. /**
  5099. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  5100. */
  5101. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5102. var squared = amount * amount;
  5103. var cubed = amount * squared;
  5104. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5105. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5106. var part3 = (cubed - (2.0 * squared)) + amount;
  5107. var part4 = cubed - squared;
  5108. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  5109. };
  5110. /**
  5111. * Returns a random float number between and min and max values
  5112. */
  5113. Scalar.RandomRange = function (min, max) {
  5114. if (min === max)
  5115. return min;
  5116. return ((Math.random() * (max - min)) + min);
  5117. };
  5118. /**
  5119. * This function returns percentage of a number in a given range.
  5120. *
  5121. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5122. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5123. */
  5124. Scalar.RangeToPercent = function (number, min, max) {
  5125. return ((number - min) / (max - min));
  5126. };
  5127. /**
  5128. * This function returns number that corresponds to the percentage in a given range.
  5129. *
  5130. * PercentToRange(0.34,0,100) will return 34.
  5131. */
  5132. Scalar.PercentToRange = function (percent, min, max) {
  5133. return ((max - min) * percent + min);
  5134. };
  5135. /**
  5136. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  5137. * @param angle The angle to normalize in radian.
  5138. * @return The converted angle.
  5139. */
  5140. Scalar.NormalizeRadians = function (angle) {
  5141. // More precise but slower version kept for reference.
  5142. // angle = angle % Tools.TwoPi;
  5143. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  5144. //if (angle > Math.PI) {
  5145. // angle -= Tools.TwoPi;
  5146. //}
  5147. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  5148. return angle;
  5149. };
  5150. /**
  5151. * Two pi constants convenient for computation.
  5152. */
  5153. Scalar.TwoPi = Math.PI * 2;
  5154. return Scalar;
  5155. }());
  5156. BABYLON.Scalar = Scalar;
  5157. })(BABYLON || (BABYLON = {}));
  5158. //# sourceMappingURL=babylon.math.scalar.js.map
  5159. //# sourceMappingURL=babylon.mixins.js.map
  5160. var BABYLON;
  5161. (function (BABYLON) {
  5162. var __decoratorInitialStore = {};
  5163. var __mergedStore = {};
  5164. var _copySource = function (creationFunction, source, instanciate) {
  5165. var destination = creationFunction();
  5166. // Tags
  5167. if (BABYLON.Tags) {
  5168. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5169. }
  5170. var classStore = getMergedStore(destination);
  5171. // Properties
  5172. for (var property in classStore) {
  5173. var propertyDescriptor = classStore[property];
  5174. var sourceProperty = source[property];
  5175. var propertyType = propertyDescriptor.type;
  5176. if (sourceProperty !== undefined && sourceProperty !== null) {
  5177. switch (propertyType) {
  5178. case 0: // Value
  5179. case 6:// Mesh reference
  5180. destination[property] = sourceProperty;
  5181. break;
  5182. case 1:// Texture
  5183. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  5184. break;
  5185. case 2: // Color3
  5186. case 3: // FresnelParameters
  5187. case 4: // Vector2
  5188. case 5: // Vector3
  5189. case 7: // Color Curves
  5190. case 10:// Quaternion
  5191. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  5192. break;
  5193. }
  5194. }
  5195. }
  5196. return destination;
  5197. };
  5198. function getDirectStore(target) {
  5199. var classKey = target.getClassName();
  5200. if (!__decoratorInitialStore[classKey]) {
  5201. __decoratorInitialStore[classKey] = {};
  5202. }
  5203. return __decoratorInitialStore[classKey];
  5204. }
  5205. /**
  5206. * Return the list of properties flagged as serializable
  5207. * @param target: host object
  5208. */
  5209. function getMergedStore(target) {
  5210. var classKey = target.getClassName();
  5211. if (__mergedStore[classKey]) {
  5212. return __mergedStore[classKey];
  5213. }
  5214. __mergedStore[classKey] = {};
  5215. var store = __mergedStore[classKey];
  5216. var currentTarget = target;
  5217. var currentKey = classKey;
  5218. while (currentKey) {
  5219. var initialStore = __decoratorInitialStore[currentKey];
  5220. for (var property in initialStore) {
  5221. store[property] = initialStore[property];
  5222. }
  5223. var parent_1 = void 0;
  5224. var done = false;
  5225. do {
  5226. parent_1 = Object.getPrototypeOf(currentTarget);
  5227. if (!parent_1.getClassName) {
  5228. done = true;
  5229. break;
  5230. }
  5231. if (parent_1.getClassName() !== currentKey) {
  5232. break;
  5233. }
  5234. currentTarget = parent_1;
  5235. } while (parent_1);
  5236. if (done) {
  5237. break;
  5238. }
  5239. currentKey = parent_1.getClassName();
  5240. currentTarget = parent_1;
  5241. }
  5242. return store;
  5243. }
  5244. function generateSerializableMember(type, sourceName) {
  5245. return function (target, propertyKey) {
  5246. var classStore = getDirectStore(target);
  5247. if (!classStore[propertyKey]) {
  5248. classStore[propertyKey] = { type: type, sourceName: sourceName };
  5249. }
  5250. };
  5251. }
  5252. function generateExpandMember(setCallback, targetKey) {
  5253. if (targetKey === void 0) { targetKey = null; }
  5254. return function (target, propertyKey) {
  5255. var key = targetKey || ("_" + propertyKey);
  5256. Object.defineProperty(target, propertyKey, {
  5257. get: function () {
  5258. return this[key];
  5259. },
  5260. set: function (value) {
  5261. if (this[key] === value) {
  5262. return;
  5263. }
  5264. this[key] = value;
  5265. target[setCallback].apply(this);
  5266. },
  5267. enumerable: true,
  5268. configurable: true
  5269. });
  5270. };
  5271. }
  5272. function expandToProperty(callback, targetKey) {
  5273. if (targetKey === void 0) { targetKey = null; }
  5274. return generateExpandMember(callback, targetKey);
  5275. }
  5276. BABYLON.expandToProperty = expandToProperty;
  5277. function serialize(sourceName) {
  5278. return generateSerializableMember(0, sourceName); // value member
  5279. }
  5280. BABYLON.serialize = serialize;
  5281. function serializeAsTexture(sourceName) {
  5282. return generateSerializableMember(1, sourceName); // texture member
  5283. }
  5284. BABYLON.serializeAsTexture = serializeAsTexture;
  5285. function serializeAsColor3(sourceName) {
  5286. return generateSerializableMember(2, sourceName); // color3 member
  5287. }
  5288. BABYLON.serializeAsColor3 = serializeAsColor3;
  5289. function serializeAsFresnelParameters(sourceName) {
  5290. return generateSerializableMember(3, sourceName); // fresnel parameters member
  5291. }
  5292. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  5293. function serializeAsVector2(sourceName) {
  5294. return generateSerializableMember(4, sourceName); // vector2 member
  5295. }
  5296. BABYLON.serializeAsVector2 = serializeAsVector2;
  5297. function serializeAsVector3(sourceName) {
  5298. return generateSerializableMember(5, sourceName); // vector3 member
  5299. }
  5300. BABYLON.serializeAsVector3 = serializeAsVector3;
  5301. function serializeAsMeshReference(sourceName) {
  5302. return generateSerializableMember(6, sourceName); // mesh reference member
  5303. }
  5304. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  5305. function serializeAsColorCurves(sourceName) {
  5306. return generateSerializableMember(7, sourceName); // color curves
  5307. }
  5308. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  5309. function serializeAsColor4(sourceName) {
  5310. return generateSerializableMember(8, sourceName); // color 4
  5311. }
  5312. BABYLON.serializeAsColor4 = serializeAsColor4;
  5313. function serializeAsImageProcessingConfiguration(sourceName) {
  5314. return generateSerializableMember(9, sourceName); // image processing
  5315. }
  5316. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  5317. function serializeAsQuaternion(sourceName) {
  5318. return generateSerializableMember(10, sourceName); // quaternion member
  5319. }
  5320. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  5321. var SerializationHelper = /** @class */ (function () {
  5322. function SerializationHelper() {
  5323. }
  5324. SerializationHelper.Serialize = function (entity, serializationObject) {
  5325. if (!serializationObject) {
  5326. serializationObject = {};
  5327. }
  5328. // Tags
  5329. if (BABYLON.Tags) {
  5330. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  5331. }
  5332. var serializedProperties = getMergedStore(entity);
  5333. // Properties
  5334. for (var property in serializedProperties) {
  5335. var propertyDescriptor = serializedProperties[property];
  5336. var targetPropertyName = propertyDescriptor.sourceName || property;
  5337. var propertyType = propertyDescriptor.type;
  5338. var sourceProperty = entity[property];
  5339. if (sourceProperty !== undefined && sourceProperty !== null) {
  5340. switch (propertyType) {
  5341. case 0:// Value
  5342. serializationObject[targetPropertyName] = sourceProperty;
  5343. break;
  5344. case 1:// Texture
  5345. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5346. break;
  5347. case 2:// Color3
  5348. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5349. break;
  5350. case 3:// FresnelParameters
  5351. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5352. break;
  5353. case 4:// Vector2
  5354. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5355. break;
  5356. case 5:// Vector3
  5357. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5358. break;
  5359. case 6:// Mesh reference
  5360. serializationObject[targetPropertyName] = sourceProperty.id;
  5361. break;
  5362. case 7:// Color Curves
  5363. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5364. break;
  5365. case 8:// Color 4
  5366. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5367. break;
  5368. case 9:// Image Processing
  5369. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5370. break;
  5371. }
  5372. }
  5373. }
  5374. return serializationObject;
  5375. };
  5376. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  5377. if (rootUrl === void 0) { rootUrl = null; }
  5378. var destination = creationFunction();
  5379. if (!rootUrl) {
  5380. rootUrl = "";
  5381. }
  5382. // Tags
  5383. if (BABYLON.Tags) {
  5384. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5385. }
  5386. var classStore = getMergedStore(destination);
  5387. // Properties
  5388. for (var property in classStore) {
  5389. var propertyDescriptor = classStore[property];
  5390. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5391. var propertyType = propertyDescriptor.type;
  5392. if (sourceProperty !== undefined && sourceProperty !== null) {
  5393. var dest = destination;
  5394. switch (propertyType) {
  5395. case 0:// Value
  5396. dest[property] = sourceProperty;
  5397. break;
  5398. case 1:// Texture
  5399. if (scene) {
  5400. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5401. }
  5402. break;
  5403. case 2:// Color3
  5404. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  5405. break;
  5406. case 3:// FresnelParameters
  5407. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5408. break;
  5409. case 4:// Vector2
  5410. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5411. break;
  5412. case 5:// Vector3
  5413. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5414. break;
  5415. case 6:// Mesh reference
  5416. if (scene) {
  5417. dest[property] = scene.getLastMeshByID(sourceProperty);
  5418. }
  5419. break;
  5420. case 7:// Color Curves
  5421. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5422. break;
  5423. case 8:// Color 4
  5424. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  5425. break;
  5426. case 9:// Image Processing
  5427. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5428. break;
  5429. }
  5430. }
  5431. }
  5432. return destination;
  5433. };
  5434. SerializationHelper.Clone = function (creationFunction, source) {
  5435. return _copySource(creationFunction, source, false);
  5436. };
  5437. SerializationHelper.Instanciate = function (creationFunction, source) {
  5438. return _copySource(creationFunction, source, true);
  5439. };
  5440. return SerializationHelper;
  5441. }());
  5442. BABYLON.SerializationHelper = SerializationHelper;
  5443. })(BABYLON || (BABYLON = {}));
  5444. //# sourceMappingURL=babylon.decorators.js.map
  5445. var BABYLON;
  5446. (function (BABYLON) {
  5447. /**
  5448. * A class serves as a medium between the observable and its observers
  5449. */
  5450. var EventState = /** @class */ (function () {
  5451. /**
  5452. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5453. */
  5454. function EventState(mask, skipNextObservers, target, currentTarget) {
  5455. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5456. this.initalize(mask, skipNextObservers, target, currentTarget);
  5457. }
  5458. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  5459. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5460. this.mask = mask;
  5461. this.skipNextObservers = skipNextObservers;
  5462. this.target = target;
  5463. this.currentTarget = currentTarget;
  5464. return this;
  5465. };
  5466. return EventState;
  5467. }());
  5468. BABYLON.EventState = EventState;
  5469. /**
  5470. * Represent an Observer registered to a given Observable object.
  5471. */
  5472. var Observer = /** @class */ (function () {
  5473. function Observer(callback, mask, scope) {
  5474. if (scope === void 0) { scope = null; }
  5475. this.callback = callback;
  5476. this.mask = mask;
  5477. this.scope = scope;
  5478. }
  5479. return Observer;
  5480. }());
  5481. BABYLON.Observer = Observer;
  5482. /**
  5483. * Represent a list of observers registered to multiple Observables object.
  5484. */
  5485. var MultiObserver = /** @class */ (function () {
  5486. function MultiObserver() {
  5487. }
  5488. MultiObserver.prototype.dispose = function () {
  5489. if (this._observers && this._observables) {
  5490. for (var index = 0; index < this._observers.length; index++) {
  5491. this._observables[index].remove(this._observers[index]);
  5492. }
  5493. }
  5494. this._observers = null;
  5495. this._observables = null;
  5496. };
  5497. MultiObserver.Watch = function (observables, callback, mask, scope) {
  5498. if (mask === void 0) { mask = -1; }
  5499. if (scope === void 0) { scope = null; }
  5500. var result = new MultiObserver();
  5501. result._observers = new Array();
  5502. result._observables = observables;
  5503. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  5504. var observable = observables_1[_i];
  5505. var observer = observable.add(callback, mask, false, scope);
  5506. if (observer) {
  5507. result._observers.push(observer);
  5508. }
  5509. }
  5510. return result;
  5511. };
  5512. return MultiObserver;
  5513. }());
  5514. BABYLON.MultiObserver = MultiObserver;
  5515. /**
  5516. * The Observable class is a simple implementation of the Observable pattern.
  5517. * 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.
  5518. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5519. * 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).
  5520. * 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.
  5521. */
  5522. var Observable = /** @class */ (function () {
  5523. function Observable(onObserverAdded) {
  5524. this._observers = new Array();
  5525. this._eventState = new EventState(0);
  5526. if (onObserverAdded) {
  5527. this._onObserverAdded = onObserverAdded;
  5528. }
  5529. }
  5530. /**
  5531. * Create a new Observer with the specified callback
  5532. * @param callback the callback that will be executed for that Observer
  5533. * @param mask the mask used to filter observers
  5534. * @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.
  5535. * @param scope optional scope for the callback to be called from
  5536. */
  5537. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  5538. if (mask === void 0) { mask = -1; }
  5539. if (insertFirst === void 0) { insertFirst = false; }
  5540. if (scope === void 0) { scope = null; }
  5541. if (!callback) {
  5542. return null;
  5543. }
  5544. var observer = new Observer(callback, mask, scope);
  5545. if (insertFirst) {
  5546. this._observers.unshift(observer);
  5547. }
  5548. else {
  5549. this._observers.push(observer);
  5550. }
  5551. if (this._onObserverAdded) {
  5552. this._onObserverAdded(observer);
  5553. }
  5554. return observer;
  5555. };
  5556. /**
  5557. * Remove an Observer from the Observable object
  5558. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5559. */
  5560. Observable.prototype.remove = function (observer) {
  5561. if (!observer) {
  5562. return false;
  5563. }
  5564. var index = this._observers.indexOf(observer);
  5565. if (index !== -1) {
  5566. this._observers.splice(index, 1);
  5567. return true;
  5568. }
  5569. return false;
  5570. };
  5571. /**
  5572. * Remove a callback from the Observable object
  5573. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5574. */
  5575. Observable.prototype.removeCallback = function (callback) {
  5576. for (var index = 0; index < this._observers.length; index++) {
  5577. if (this._observers[index].callback === callback) {
  5578. this._observers.splice(index, 1);
  5579. return true;
  5580. }
  5581. }
  5582. return false;
  5583. };
  5584. /**
  5585. * Notify all Observers by calling their respective callback with the given data
  5586. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5587. * @param eventData
  5588. * @param mask
  5589. */
  5590. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  5591. if (mask === void 0) { mask = -1; }
  5592. if (!this._observers.length) {
  5593. return true;
  5594. }
  5595. var state = this._eventState;
  5596. state.mask = mask;
  5597. state.target = target;
  5598. state.currentTarget = currentTarget;
  5599. state.skipNextObservers = false;
  5600. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5601. var obs = _a[_i];
  5602. if (obs.mask & mask) {
  5603. if (obs.scope) {
  5604. obs.callback.apply(obs.scope, [eventData, state]);
  5605. }
  5606. else {
  5607. obs.callback(eventData, state);
  5608. }
  5609. }
  5610. if (state.skipNextObservers) {
  5611. return false;
  5612. }
  5613. }
  5614. return true;
  5615. };
  5616. /**
  5617. * Notify a specific observer
  5618. * @param eventData
  5619. * @param mask
  5620. */
  5621. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  5622. if (mask === void 0) { mask = -1; }
  5623. var state = this._eventState;
  5624. state.mask = mask;
  5625. state.skipNextObservers = false;
  5626. observer.callback(eventData, state);
  5627. };
  5628. /**
  5629. * return true is the Observable has at least one Observer registered
  5630. */
  5631. Observable.prototype.hasObservers = function () {
  5632. return this._observers.length > 0;
  5633. };
  5634. /**
  5635. * Clear the list of observers
  5636. */
  5637. Observable.prototype.clear = function () {
  5638. this._observers = new Array();
  5639. this._onObserverAdded = null;
  5640. };
  5641. /**
  5642. * Clone the current observable
  5643. */
  5644. Observable.prototype.clone = function () {
  5645. var result = new Observable();
  5646. result._observers = this._observers.slice(0);
  5647. return result;
  5648. };
  5649. /**
  5650. * Does this observable handles observer registered with a given mask
  5651. * @param {number} trigger - the mask to be tested
  5652. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5653. **/
  5654. Observable.prototype.hasSpecificMask = function (mask) {
  5655. if (mask === void 0) { mask = -1; }
  5656. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5657. var obs = _a[_i];
  5658. if (obs.mask & mask || obs.mask === mask) {
  5659. return true;
  5660. }
  5661. }
  5662. return false;
  5663. };
  5664. return Observable;
  5665. }());
  5666. BABYLON.Observable = Observable;
  5667. })(BABYLON || (BABYLON = {}));
  5668. //# sourceMappingURL=babylon.observable.js.map
  5669. var BABYLON;
  5670. (function (BABYLON) {
  5671. var SmartArray = /** @class */ (function () {
  5672. function SmartArray(capacity) {
  5673. this.length = 0;
  5674. this.data = new Array(capacity);
  5675. this._id = SmartArray._GlobalId++;
  5676. }
  5677. SmartArray.prototype.push = function (value) {
  5678. this.data[this.length++] = value;
  5679. if (this.length > this.data.length) {
  5680. this.data.length *= 2;
  5681. }
  5682. };
  5683. SmartArray.prototype.forEach = function (func) {
  5684. for (var index = 0; index < this.length; index++) {
  5685. func(this.data[index]);
  5686. }
  5687. };
  5688. SmartArray.prototype.sort = function (compareFn) {
  5689. this.data.sort(compareFn);
  5690. };
  5691. SmartArray.prototype.reset = function () {
  5692. this.length = 0;
  5693. };
  5694. SmartArray.prototype.dispose = function () {
  5695. this.reset();
  5696. if (this.data) {
  5697. this.data.length = 0;
  5698. this.data = [];
  5699. }
  5700. };
  5701. SmartArray.prototype.concat = function (array) {
  5702. if (array.length === 0) {
  5703. return;
  5704. }
  5705. if (this.length + array.length > this.data.length) {
  5706. this.data.length = (this.length + array.length) * 2;
  5707. }
  5708. for (var index = 0; index < array.length; index++) {
  5709. this.data[this.length++] = (array.data || array)[index];
  5710. }
  5711. };
  5712. SmartArray.prototype.indexOf = function (value) {
  5713. var position = this.data.indexOf(value);
  5714. if (position >= this.length) {
  5715. return -1;
  5716. }
  5717. return position;
  5718. };
  5719. SmartArray.prototype.contains = function (value) {
  5720. return this.data.indexOf(value) !== -1;
  5721. };
  5722. // Statics
  5723. SmartArray._GlobalId = 0;
  5724. return SmartArray;
  5725. }());
  5726. BABYLON.SmartArray = SmartArray;
  5727. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  5728. __extends(SmartArrayNoDuplicate, _super);
  5729. function SmartArrayNoDuplicate() {
  5730. var _this = _super !== null && _super.apply(this, arguments) || this;
  5731. _this._duplicateId = 0;
  5732. return _this;
  5733. }
  5734. SmartArrayNoDuplicate.prototype.push = function (value) {
  5735. _super.prototype.push.call(this, value);
  5736. if (!value.__smartArrayFlags) {
  5737. value.__smartArrayFlags = {};
  5738. }
  5739. value.__smartArrayFlags[this._id] = this._duplicateId;
  5740. };
  5741. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  5742. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5743. return false;
  5744. }
  5745. this.push(value);
  5746. return true;
  5747. };
  5748. SmartArrayNoDuplicate.prototype.reset = function () {
  5749. _super.prototype.reset.call(this);
  5750. this._duplicateId++;
  5751. };
  5752. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  5753. if (array.length === 0) {
  5754. return;
  5755. }
  5756. if (this.length + array.length > this.data.length) {
  5757. this.data.length = (this.length + array.length) * 2;
  5758. }
  5759. for (var index = 0; index < array.length; index++) {
  5760. var item = (array.data || array)[index];
  5761. this.pushNoDuplicate(item);
  5762. }
  5763. };
  5764. return SmartArrayNoDuplicate;
  5765. }(SmartArray));
  5766. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  5767. })(BABYLON || (BABYLON = {}));
  5768. //# sourceMappingURL=babylon.smartArray.js.map
  5769. var BABYLON;
  5770. (function (BABYLON) {
  5771. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  5772. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  5773. var LoadFileError = /** @class */ (function (_super) {
  5774. __extends(LoadFileError, _super);
  5775. function LoadFileError(message, request) {
  5776. var _this = _super.call(this, message) || this;
  5777. _this.request = request;
  5778. _this.name = "LoadFileError";
  5779. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  5780. return _this;
  5781. }
  5782. // Polyfill for Object.setPrototypeOf if necessary.
  5783. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  5784. return LoadFileError;
  5785. }(Error));
  5786. BABYLON.LoadFileError = LoadFileError;
  5787. var RetryStrategy = /** @class */ (function () {
  5788. function RetryStrategy() {
  5789. }
  5790. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  5791. if (maxRetries === void 0) { maxRetries = 3; }
  5792. if (baseInterval === void 0) { baseInterval = 500; }
  5793. return function (url, request, retryIndex) {
  5794. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  5795. return -1;
  5796. }
  5797. return Math.pow(2, retryIndex) * baseInterval;
  5798. };
  5799. };
  5800. return RetryStrategy;
  5801. }());
  5802. BABYLON.RetryStrategy = RetryStrategy;
  5803. // Screenshots
  5804. var screenshotCanvas;
  5805. var cloneValue = function (source, destinationObject) {
  5806. if (!source)
  5807. return null;
  5808. if (source instanceof BABYLON.Mesh) {
  5809. return null;
  5810. }
  5811. if (source instanceof BABYLON.SubMesh) {
  5812. return source.clone(destinationObject);
  5813. }
  5814. else if (source.clone) {
  5815. return source.clone();
  5816. }
  5817. return null;
  5818. };
  5819. var Tools = /** @class */ (function () {
  5820. function Tools() {
  5821. }
  5822. /**
  5823. * Interpolates between a and b via alpha
  5824. * @param a The lower value (returned when alpha = 0)
  5825. * @param b The upper value (returned when alpha = 1)
  5826. * @param alpha The interpolation-factor
  5827. * @return The mixed value
  5828. */
  5829. Tools.Mix = function (a, b, alpha) {
  5830. return a * (1 - alpha) + b * alpha;
  5831. };
  5832. Tools.Instantiate = function (className) {
  5833. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  5834. return Tools.RegisteredExternalClasses[className];
  5835. }
  5836. var arr = className.split(".");
  5837. var fn = (window || this);
  5838. for (var i = 0, len = arr.length; i < len; i++) {
  5839. fn = fn[arr[i]];
  5840. }
  5841. if (typeof fn !== "function") {
  5842. return null;
  5843. }
  5844. return fn;
  5845. };
  5846. Tools.SetImmediate = function (action) {
  5847. if (window.setImmediate) {
  5848. window.setImmediate(action);
  5849. }
  5850. else {
  5851. setTimeout(action, 1);
  5852. }
  5853. };
  5854. Tools.IsExponentOfTwo = function (value) {
  5855. var count = 1;
  5856. do {
  5857. count *= 2;
  5858. } while (count < value);
  5859. return count === value;
  5860. };
  5861. /**
  5862. * Find the next highest power of two.
  5863. * @param x Number to start search from.
  5864. * @return Next highest power of two.
  5865. */
  5866. Tools.CeilingPOT = function (x) {
  5867. x--;
  5868. x |= x >> 1;
  5869. x |= x >> 2;
  5870. x |= x >> 4;
  5871. x |= x >> 8;
  5872. x |= x >> 16;
  5873. x++;
  5874. return x;
  5875. };
  5876. /**
  5877. * Find the next lowest power of two.
  5878. * @param x Number to start search from.
  5879. * @return Next lowest power of two.
  5880. */
  5881. Tools.FloorPOT = function (x) {
  5882. x = x | (x >> 1);
  5883. x = x | (x >> 2);
  5884. x = x | (x >> 4);
  5885. x = x | (x >> 8);
  5886. x = x | (x >> 16);
  5887. return x - (x >> 1);
  5888. };
  5889. /**
  5890. * Find the nearest power of two.
  5891. * @param x Number to start search from.
  5892. * @return Next nearest power of two.
  5893. */
  5894. Tools.NearestPOT = function (x) {
  5895. var c = Tools.CeilingPOT(x);
  5896. var f = Tools.FloorPOT(x);
  5897. return (c - x) > (x - f) ? f : c;
  5898. };
  5899. Tools.GetExponentOfTwo = function (value, max, mode) {
  5900. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5901. var pot;
  5902. switch (mode) {
  5903. case BABYLON.Engine.SCALEMODE_FLOOR:
  5904. pot = Tools.FloorPOT(value);
  5905. break;
  5906. case BABYLON.Engine.SCALEMODE_NEAREST:
  5907. pot = Tools.NearestPOT(value);
  5908. break;
  5909. case BABYLON.Engine.SCALEMODE_CEILING:
  5910. default:
  5911. pot = Tools.CeilingPOT(value);
  5912. break;
  5913. }
  5914. return Math.min(pot, max);
  5915. };
  5916. Tools.GetFilename = function (path) {
  5917. var index = path.lastIndexOf("/");
  5918. if (index < 0)
  5919. return path;
  5920. return path.substring(index + 1);
  5921. };
  5922. Tools.GetFolderPath = function (uri) {
  5923. var index = uri.lastIndexOf("/");
  5924. if (index < 0)
  5925. return "";
  5926. return uri.substring(0, index + 1);
  5927. };
  5928. Tools.GetDOMTextContent = function (element) {
  5929. var result = "";
  5930. var child = element.firstChild;
  5931. while (child) {
  5932. if (child.nodeType === 3) {
  5933. result += child.textContent;
  5934. }
  5935. child = child.nextSibling;
  5936. }
  5937. return result;
  5938. };
  5939. Tools.ToDegrees = function (angle) {
  5940. return angle * 180 / Math.PI;
  5941. };
  5942. Tools.ToRadians = function (angle) {
  5943. return angle * Math.PI / 180;
  5944. };
  5945. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5946. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5947. var output = "";
  5948. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5949. var i = 0;
  5950. var bytes = new Uint8Array(buffer);
  5951. while (i < bytes.length) {
  5952. chr1 = bytes[i++];
  5953. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5954. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5955. enc1 = chr1 >> 2;
  5956. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5957. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5958. enc4 = chr3 & 63;
  5959. if (isNaN(chr2)) {
  5960. enc3 = enc4 = 64;
  5961. }
  5962. else if (isNaN(chr3)) {
  5963. enc4 = 64;
  5964. }
  5965. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5966. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5967. }
  5968. return "data:image/png;base64," + output;
  5969. };
  5970. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5971. if (bias === void 0) { bias = null; }
  5972. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5973. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5974. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5975. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5976. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5977. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5978. }
  5979. if (bias) {
  5980. minimum.x -= minimum.x * bias.x + bias.y;
  5981. minimum.y -= minimum.y * bias.x + bias.y;
  5982. minimum.z -= minimum.z * bias.x + bias.y;
  5983. maximum.x += maximum.x * bias.x + bias.y;
  5984. maximum.y += maximum.y * bias.x + bias.y;
  5985. maximum.z += maximum.z * bias.x + bias.y;
  5986. }
  5987. return {
  5988. minimum: minimum,
  5989. maximum: maximum
  5990. };
  5991. };
  5992. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5993. if (bias === void 0) { bias = null; }
  5994. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5995. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5996. if (!stride) {
  5997. stride = 3;
  5998. }
  5999. for (var index = start; index < start + count; index++) {
  6000. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  6001. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6002. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6003. }
  6004. if (bias) {
  6005. minimum.x -= minimum.x * bias.x + bias.y;
  6006. minimum.y -= minimum.y * bias.x + bias.y;
  6007. minimum.z -= minimum.z * bias.x + bias.y;
  6008. maximum.x += maximum.x * bias.x + bias.y;
  6009. maximum.y += maximum.y * bias.x + bias.y;
  6010. maximum.z += maximum.z * bias.x + bias.y;
  6011. }
  6012. return {
  6013. minimum: minimum,
  6014. maximum: maximum
  6015. };
  6016. };
  6017. Tools.Vector2ArrayFeeder = function (array) {
  6018. return function (index) {
  6019. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  6020. var length = isFloatArray ? array.length / 2 : array.length;
  6021. if (index >= length) {
  6022. return null;
  6023. }
  6024. if (isFloatArray) {
  6025. var fa = array;
  6026. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  6027. }
  6028. var a = array;
  6029. return a[index];
  6030. };
  6031. };
  6032. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  6033. if (bias === void 0) { bias = null; }
  6034. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  6035. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  6036. var i = 0;
  6037. var cur = feeder(i++);
  6038. while (cur) {
  6039. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  6040. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  6041. cur = feeder(i++);
  6042. }
  6043. if (bias) {
  6044. minimum.x -= minimum.x * bias.x + bias.y;
  6045. minimum.y -= minimum.y * bias.x + bias.y;
  6046. maximum.x += maximum.x * bias.x + bias.y;
  6047. maximum.y += maximum.y * bias.x + bias.y;
  6048. }
  6049. return {
  6050. minimum: minimum,
  6051. maximum: maximum
  6052. };
  6053. };
  6054. Tools.MakeArray = function (obj, allowsNullUndefined) {
  6055. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6056. return null;
  6057. return Array.isArray(obj) ? obj : [obj];
  6058. };
  6059. // Misc.
  6060. Tools.GetPointerPrefix = function () {
  6061. var eventPrefix = "pointer";
  6062. // Check if pointer events are supported
  6063. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  6064. eventPrefix = "mouse";
  6065. }
  6066. return eventPrefix;
  6067. };
  6068. /**
  6069. * @param func - the function to be called
  6070. * @param requester - the object that will request the next frame. Falls back to window.
  6071. */
  6072. Tools.QueueNewFrame = function (func, requester) {
  6073. if (!Tools.IsWindowObjectExist()) {
  6074. return setTimeout(func, 16);
  6075. }
  6076. if (!requester) {
  6077. requester = window;
  6078. }
  6079. if (requester.requestAnimationFrame) {
  6080. return requester.requestAnimationFrame(func);
  6081. }
  6082. else if (requester.msRequestAnimationFrame) {
  6083. return requester.msRequestAnimationFrame(func);
  6084. }
  6085. else if (requester.webkitRequestAnimationFrame) {
  6086. return requester.webkitRequestAnimationFrame(func);
  6087. }
  6088. else if (requester.mozRequestAnimationFrame) {
  6089. return requester.mozRequestAnimationFrame(func);
  6090. }
  6091. else if (requester.oRequestAnimationFrame) {
  6092. return requester.oRequestAnimationFrame(func);
  6093. }
  6094. else {
  6095. return window.setTimeout(func, 16);
  6096. }
  6097. };
  6098. Tools.RequestFullscreen = function (element) {
  6099. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6100. if (!requestFunction)
  6101. return;
  6102. requestFunction.call(element);
  6103. };
  6104. Tools.ExitFullscreen = function () {
  6105. if (document.exitFullscreen) {
  6106. document.exitFullscreen();
  6107. }
  6108. else if (document.mozCancelFullScreen) {
  6109. document.mozCancelFullScreen();
  6110. }
  6111. else if (document.webkitCancelFullScreen) {
  6112. document.webkitCancelFullScreen();
  6113. }
  6114. else if (document.msCancelFullScreen) {
  6115. document.msCancelFullScreen();
  6116. }
  6117. };
  6118. Tools.SetCorsBehavior = function (url, element) {
  6119. if (url && url.indexOf("data:") === 0) {
  6120. return;
  6121. }
  6122. if (Tools.CorsBehavior) {
  6123. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  6124. element.crossOrigin = Tools.CorsBehavior;
  6125. }
  6126. else {
  6127. var result = Tools.CorsBehavior(url);
  6128. if (result) {
  6129. element.crossOrigin = result;
  6130. }
  6131. }
  6132. }
  6133. };
  6134. // External files
  6135. Tools.CleanUrl = function (url) {
  6136. url = url.replace(/#/mg, "%23");
  6137. return url;
  6138. };
  6139. Tools.LoadImage = function (url, onLoad, onError, database) {
  6140. if (url instanceof ArrayBuffer) {
  6141. url = Tools.EncodeArrayBufferTobase64(url);
  6142. }
  6143. url = Tools.CleanUrl(url);
  6144. url = Tools.PreprocessUrl(url);
  6145. var img = new Image();
  6146. Tools.SetCorsBehavior(url, img);
  6147. img.onload = function () {
  6148. onLoad(img);
  6149. };
  6150. img.onerror = function (err) {
  6151. Tools.Error("Error while trying to load image: " + url);
  6152. if (onError) {
  6153. onError("Error while trying to load image: " + url, err);
  6154. }
  6155. };
  6156. var noIndexedDB = function () {
  6157. img.src = url;
  6158. };
  6159. var loadFromIndexedDB = function () {
  6160. if (database) {
  6161. database.loadImageFromDB(url, img);
  6162. }
  6163. };
  6164. //ANY database to do!
  6165. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6166. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6167. }
  6168. else {
  6169. if (url.indexOf("file:") !== -1) {
  6170. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  6171. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  6172. try {
  6173. var blobURL;
  6174. try {
  6175. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  6176. }
  6177. catch (ex) {
  6178. // Chrome doesn't support oneTimeOnly parameter
  6179. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  6180. }
  6181. img.src = blobURL;
  6182. }
  6183. catch (e) {
  6184. img.src = "";
  6185. }
  6186. return img;
  6187. }
  6188. }
  6189. noIndexedDB();
  6190. }
  6191. return img;
  6192. };
  6193. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError, onRetry, retryStrategy) {
  6194. if (retryStrategy === void 0) { retryStrategy = null; }
  6195. url = Tools.CleanUrl(url);
  6196. url = Tools.PreprocessUrl(url);
  6197. var request = null;
  6198. var aborted = false;
  6199. var noIndexedDB = function (retryIndex) {
  6200. if (aborted) {
  6201. return;
  6202. }
  6203. var oldRequest = request;
  6204. request = new XMLHttpRequest();
  6205. var loadUrl = Tools.BaseUrl + url;
  6206. request.open('GET', loadUrl, true);
  6207. if (useArrayBuffer) {
  6208. request.responseType = "arraybuffer";
  6209. }
  6210. if (progressCallBack) {
  6211. request.onprogress = progressCallBack;
  6212. }
  6213. request.addEventListener("abort", function () {
  6214. aborted = true;
  6215. });
  6216. var onreadystatechange = function () {
  6217. var req = request;
  6218. // In case of undefined state in some browsers.
  6219. if (req.readyState === (XMLHttpRequest.DONE || 4)) {
  6220. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  6221. req.removeEventListener("readystatechange", onreadystatechange);
  6222. if (req.status >= 200 && req.status < 300 || (!Tools.IsWindowObjectExist() && (req.status === 0))) {
  6223. callback(!useArrayBuffer ? req.responseText : req.response, req.responseURL);
  6224. return;
  6225. }
  6226. retryStrategy = retryStrategy || Tools.DefaultRetryStrategy;
  6227. if (retryStrategy) {
  6228. var waitTime = retryStrategy(loadUrl, req, retryIndex || 0);
  6229. if (waitTime !== -1) {
  6230. setTimeout(function () { return noIndexedDB((retryIndex || 0) + 1); }, waitTime);
  6231. return;
  6232. }
  6233. }
  6234. var e = new LoadFileError("Error status: " + req.status + " - Unable to load " + loadUrl);
  6235. if (onError) {
  6236. onError(req, e);
  6237. }
  6238. else {
  6239. throw e;
  6240. }
  6241. }
  6242. };
  6243. request.addEventListener("readystatechange", onreadystatechange);
  6244. request.send();
  6245. if (oldRequest && onRetry) {
  6246. onRetry(oldRequest, request);
  6247. }
  6248. };
  6249. var loadFromIndexedDB = function () {
  6250. if (database) {
  6251. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6252. }
  6253. };
  6254. // If file and file input are set
  6255. if (url.indexOf("file:") !== -1) {
  6256. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  6257. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6258. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6259. return request;
  6260. }
  6261. }
  6262. // Caching all files
  6263. if (database && database.enableSceneOffline) {
  6264. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6265. }
  6266. else {
  6267. noIndexedDB();
  6268. }
  6269. return request;
  6270. };
  6271. /**
  6272. * Load a script (identified by an url). When the url returns, the
  6273. * content of this file is added into a new script element, attached to the DOM (body element)
  6274. */
  6275. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6276. var head = document.getElementsByTagName('head')[0];
  6277. var script = document.createElement('script');
  6278. script.type = 'text/javascript';
  6279. script.src = scriptUrl;
  6280. script.onload = function () {
  6281. if (onSuccess) {
  6282. onSuccess();
  6283. }
  6284. };
  6285. script.onerror = function (e) {
  6286. if (onError) {
  6287. onError("Unable to load script", e);
  6288. }
  6289. };
  6290. head.appendChild(script);
  6291. };
  6292. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6293. var reader = new FileReader();
  6294. reader.onload = function (e) {
  6295. //target doesn't have result from ts 1.3
  6296. callback(e.target['result']);
  6297. };
  6298. reader.onprogress = progressCallback;
  6299. reader.readAsDataURL(fileToLoad);
  6300. };
  6301. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6302. var reader = new FileReader();
  6303. reader.onerror = function (e) {
  6304. Tools.Log("Error while reading file: " + fileToLoad.name);
  6305. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6306. };
  6307. reader.onload = function (e) {
  6308. //target doesn't have result from ts 1.3
  6309. callback(e.target['result']);
  6310. };
  6311. if (progressCallBack) {
  6312. reader.onprogress = progressCallBack;
  6313. }
  6314. if (!useArrayBuffer) {
  6315. // Asynchronous read
  6316. reader.readAsText(fileToLoad);
  6317. }
  6318. else {
  6319. reader.readAsArrayBuffer(fileToLoad);
  6320. }
  6321. };
  6322. //returns a downloadable url to a file content.
  6323. Tools.FileAsURL = function (content) {
  6324. var fileBlob = new Blob([content]);
  6325. var url = window.URL || window.webkitURL;
  6326. var link = url.createObjectURL(fileBlob);
  6327. return link;
  6328. };
  6329. // Misc.
  6330. Tools.Format = function (value, decimals) {
  6331. if (decimals === void 0) { decimals = 2; }
  6332. return value.toFixed(decimals);
  6333. };
  6334. Tools.CheckExtends = function (v, min, max) {
  6335. if (v.x < min.x)
  6336. min.x = v.x;
  6337. if (v.y < min.y)
  6338. min.y = v.y;
  6339. if (v.z < min.z)
  6340. min.z = v.z;
  6341. if (v.x > max.x)
  6342. max.x = v.x;
  6343. if (v.y > max.y)
  6344. max.y = v.y;
  6345. if (v.z > max.z)
  6346. max.z = v.z;
  6347. };
  6348. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6349. for (var prop in source) {
  6350. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6351. continue;
  6352. }
  6353. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6354. continue;
  6355. }
  6356. var sourceValue = source[prop];
  6357. var typeOfSourceValue = typeof sourceValue;
  6358. if (typeOfSourceValue === "function") {
  6359. continue;
  6360. }
  6361. if (typeOfSourceValue === "object") {
  6362. if (sourceValue instanceof Array) {
  6363. destination[prop] = [];
  6364. if (sourceValue.length > 0) {
  6365. if (typeof sourceValue[0] == "object") {
  6366. for (var index = 0; index < sourceValue.length; index++) {
  6367. var clonedValue = cloneValue(sourceValue[index], destination);
  6368. if (destination[prop].indexOf(clonedValue) === -1) {
  6369. destination[prop].push(clonedValue);
  6370. }
  6371. }
  6372. }
  6373. else {
  6374. destination[prop] = sourceValue.slice(0);
  6375. }
  6376. }
  6377. }
  6378. else {
  6379. destination[prop] = cloneValue(sourceValue, destination);
  6380. }
  6381. }
  6382. else {
  6383. destination[prop] = sourceValue;
  6384. }
  6385. }
  6386. };
  6387. Tools.IsEmpty = function (obj) {
  6388. for (var i in obj) {
  6389. if (obj.hasOwnProperty(i)) {
  6390. return false;
  6391. }
  6392. }
  6393. return true;
  6394. };
  6395. Tools.RegisterTopRootEvents = function (events) {
  6396. for (var index = 0; index < events.length; index++) {
  6397. var event = events[index];
  6398. window.addEventListener(event.name, event.handler, false);
  6399. try {
  6400. if (window.parent) {
  6401. window.parent.addEventListener(event.name, event.handler, false);
  6402. }
  6403. }
  6404. catch (e) {
  6405. // Silently fails...
  6406. }
  6407. }
  6408. };
  6409. Tools.UnregisterTopRootEvents = function (events) {
  6410. for (var index = 0; index < events.length; index++) {
  6411. var event = events[index];
  6412. window.removeEventListener(event.name, event.handler);
  6413. try {
  6414. if (window.parent) {
  6415. window.parent.removeEventListener(event.name, event.handler);
  6416. }
  6417. }
  6418. catch (e) {
  6419. // Silently fails...
  6420. }
  6421. }
  6422. };
  6423. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  6424. if (mimeType === void 0) { mimeType = "image/png"; }
  6425. // Read the contents of the framebuffer
  6426. var numberOfChannelsByLine = width * 4;
  6427. var halfHeight = height / 2;
  6428. //Reading datas from WebGL
  6429. var data = engine.readPixels(0, 0, width, height);
  6430. //To flip image on Y axis.
  6431. for (var i = 0; i < halfHeight; i++) {
  6432. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6433. var currentCell = j + i * numberOfChannelsByLine;
  6434. var targetLine = height - i - 1;
  6435. var targetCell = j + targetLine * numberOfChannelsByLine;
  6436. var temp = data[currentCell];
  6437. data[currentCell] = data[targetCell];
  6438. data[targetCell] = temp;
  6439. }
  6440. }
  6441. // Create a 2D canvas to store the result
  6442. if (!screenshotCanvas) {
  6443. screenshotCanvas = document.createElement('canvas');
  6444. }
  6445. screenshotCanvas.width = width;
  6446. screenshotCanvas.height = height;
  6447. var context = screenshotCanvas.getContext('2d');
  6448. if (context) {
  6449. // Copy the pixels to a 2D canvas
  6450. var imageData = context.createImageData(width, height);
  6451. var castData = (imageData.data);
  6452. castData.set(data);
  6453. context.putImageData(imageData, 0, 0);
  6454. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  6455. }
  6456. };
  6457. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  6458. if (mimeType === void 0) { mimeType = "image/png"; }
  6459. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6460. if (successCallback) {
  6461. successCallback(base64Image);
  6462. }
  6463. else {
  6464. // We need HTMLCanvasElement.toBlob for HD screenshots
  6465. if (!screenshotCanvas.toBlob) {
  6466. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  6467. screenshotCanvas.toBlob = function (callback, type, quality) {
  6468. var _this = this;
  6469. setTimeout(function () {
  6470. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  6471. for (var i = 0; i < len; i++) {
  6472. arr[i] = binStr.charCodeAt(i);
  6473. }
  6474. callback(new Blob([arr], { type: type || 'image/png' }));
  6475. });
  6476. };
  6477. }
  6478. screenshotCanvas.toBlob(function (blob) {
  6479. var url = URL.createObjectURL(blob);
  6480. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6481. if (("download" in document.createElement("a"))) {
  6482. var a = window.document.createElement("a");
  6483. a.href = url;
  6484. if (fileName) {
  6485. a.setAttribute("download", fileName);
  6486. }
  6487. else {
  6488. var date = new Date();
  6489. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6490. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6491. }
  6492. window.document.body.appendChild(a);
  6493. a.addEventListener("click", function () {
  6494. if (a.parentElement) {
  6495. a.parentElement.removeChild(a);
  6496. }
  6497. });
  6498. a.click();
  6499. }
  6500. else {
  6501. var newWindow = window.open("");
  6502. if (!newWindow)
  6503. return;
  6504. var img = newWindow.document.createElement("img");
  6505. img.onload = function () {
  6506. // no longer need to read the blob so it's revoked
  6507. URL.revokeObjectURL(url);
  6508. };
  6509. img.src = url;
  6510. newWindow.document.body.appendChild(img);
  6511. }
  6512. });
  6513. }
  6514. };
  6515. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6516. if (mimeType === void 0) { mimeType = "image/png"; }
  6517. var width;
  6518. var height;
  6519. // If a precision value is specified
  6520. if (size.precision) {
  6521. width = Math.round(engine.getRenderWidth() * size.precision);
  6522. height = Math.round(width / engine.getAspectRatio(camera));
  6523. }
  6524. else if (size.width && size.height) {
  6525. width = size.width;
  6526. height = size.height;
  6527. }
  6528. else if (size.width && !size.height) {
  6529. width = size.width;
  6530. height = Math.round(width / engine.getAspectRatio(camera));
  6531. }
  6532. else if (size.height && !size.width) {
  6533. height = size.height;
  6534. width = Math.round(height * engine.getAspectRatio(camera));
  6535. }
  6536. else if (!isNaN(size)) {
  6537. height = size;
  6538. width = size;
  6539. }
  6540. else {
  6541. Tools.Error("Invalid 'size' parameter !");
  6542. return;
  6543. }
  6544. if (!screenshotCanvas) {
  6545. screenshotCanvas = document.createElement('canvas');
  6546. }
  6547. screenshotCanvas.width = width;
  6548. screenshotCanvas.height = height;
  6549. var renderContext = screenshotCanvas.getContext("2d");
  6550. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6551. var newWidth = width;
  6552. var newHeight = newWidth / ratio;
  6553. if (newHeight > height) {
  6554. newHeight = height;
  6555. newWidth = newHeight * ratio;
  6556. }
  6557. var offsetX = Math.max(0, width - newWidth) / 2;
  6558. var offsetY = Math.max(0, height - newHeight) / 2;
  6559. var renderingCanvas = engine.getRenderingCanvas();
  6560. if (renderContext && renderingCanvas) {
  6561. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  6562. }
  6563. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6564. };
  6565. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  6566. if (mimeType === void 0) { mimeType = "image/png"; }
  6567. if (samples === void 0) { samples = 1; }
  6568. if (antialiasing === void 0) { antialiasing = false; }
  6569. var width;
  6570. var height;
  6571. //If a precision value is specified
  6572. if (size.precision) {
  6573. width = Math.round(engine.getRenderWidth() * size.precision);
  6574. height = Math.round(width / engine.getAspectRatio(camera));
  6575. size = { width: width, height: height };
  6576. }
  6577. else if (size.width && size.height) {
  6578. width = size.width;
  6579. height = size.height;
  6580. }
  6581. else if (size.width && !size.height) {
  6582. width = size.width;
  6583. height = Math.round(width / engine.getAspectRatio(camera));
  6584. size = { width: width, height: height };
  6585. }
  6586. else if (size.height && !size.width) {
  6587. height = size.height;
  6588. width = Math.round(height * engine.getAspectRatio(camera));
  6589. size = { width: width, height: height };
  6590. }
  6591. else if (!isNaN(size)) {
  6592. height = size;
  6593. width = size;
  6594. }
  6595. else {
  6596. Tools.Error("Invalid 'size' parameter !");
  6597. return;
  6598. }
  6599. var scene = camera.getScene();
  6600. var previousCamera = null;
  6601. if (scene.activeCamera !== camera) {
  6602. previousCamera = scene.activeCamera;
  6603. scene.activeCamera = camera;
  6604. }
  6605. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6606. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6607. texture.renderList = null;
  6608. texture.samples = samples;
  6609. if (antialiasing) {
  6610. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  6611. }
  6612. texture.onAfterRenderObservable.add(function () {
  6613. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  6614. });
  6615. scene.incrementRenderId();
  6616. scene.resetCachedMaterial();
  6617. texture.render(true);
  6618. texture.dispose();
  6619. if (previousCamera) {
  6620. scene.activeCamera = previousCamera;
  6621. }
  6622. camera.getProjectionMatrix(true); // Force cache refresh;
  6623. };
  6624. // XHR response validator for local file scenario
  6625. Tools.ValidateXHRData = function (xhr, dataType) {
  6626. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6627. if (dataType === void 0) { dataType = 7; }
  6628. try {
  6629. if (dataType & 1) {
  6630. if (xhr.responseText && xhr.responseText.length > 0) {
  6631. return true;
  6632. }
  6633. else if (dataType === 1) {
  6634. return false;
  6635. }
  6636. }
  6637. if (dataType & 2) {
  6638. // Check header width and height since there is no "TGA" magic number
  6639. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6640. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6641. return true;
  6642. }
  6643. else if (dataType === 2) {
  6644. return false;
  6645. }
  6646. }
  6647. if (dataType & 4) {
  6648. // Check for the "DDS" magic number
  6649. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6650. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6651. return true;
  6652. }
  6653. else {
  6654. return false;
  6655. }
  6656. }
  6657. }
  6658. catch (e) {
  6659. // Global protection
  6660. }
  6661. return false;
  6662. };
  6663. /**
  6664. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6665. * Be aware Math.random() could cause collisions, but:
  6666. * "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"
  6667. */
  6668. Tools.RandomId = function () {
  6669. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6670. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6671. return v.toString(16);
  6672. });
  6673. };
  6674. Object.defineProperty(Tools, "NoneLogLevel", {
  6675. get: function () {
  6676. return Tools._NoneLogLevel;
  6677. },
  6678. enumerable: true,
  6679. configurable: true
  6680. });
  6681. Object.defineProperty(Tools, "MessageLogLevel", {
  6682. get: function () {
  6683. return Tools._MessageLogLevel;
  6684. },
  6685. enumerable: true,
  6686. configurable: true
  6687. });
  6688. Object.defineProperty(Tools, "WarningLogLevel", {
  6689. get: function () {
  6690. return Tools._WarningLogLevel;
  6691. },
  6692. enumerable: true,
  6693. configurable: true
  6694. });
  6695. Object.defineProperty(Tools, "ErrorLogLevel", {
  6696. get: function () {
  6697. return Tools._ErrorLogLevel;
  6698. },
  6699. enumerable: true,
  6700. configurable: true
  6701. });
  6702. Object.defineProperty(Tools, "AllLogLevel", {
  6703. get: function () {
  6704. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6705. },
  6706. enumerable: true,
  6707. configurable: true
  6708. });
  6709. Tools._AddLogEntry = function (entry) {
  6710. Tools._LogCache = entry + Tools._LogCache;
  6711. if (Tools.OnNewCacheEntry) {
  6712. Tools.OnNewCacheEntry(entry);
  6713. }
  6714. };
  6715. Tools._FormatMessage = function (message) {
  6716. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6717. var date = new Date();
  6718. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6719. };
  6720. Tools._LogDisabled = function (message) {
  6721. // nothing to do
  6722. };
  6723. Tools._LogEnabled = function (message) {
  6724. var formattedMessage = Tools._FormatMessage(message);
  6725. console.log("BJS - " + formattedMessage);
  6726. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6727. Tools._AddLogEntry(entry);
  6728. };
  6729. Tools._WarnDisabled = function (message) {
  6730. // nothing to do
  6731. };
  6732. Tools._WarnEnabled = function (message) {
  6733. var formattedMessage = Tools._FormatMessage(message);
  6734. console.warn("BJS - " + formattedMessage);
  6735. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6736. Tools._AddLogEntry(entry);
  6737. };
  6738. Tools._ErrorDisabled = function (message) {
  6739. // nothing to do
  6740. };
  6741. Tools._ErrorEnabled = function (message) {
  6742. Tools.errorsCount++;
  6743. var formattedMessage = Tools._FormatMessage(message);
  6744. console.error("BJS - " + formattedMessage);
  6745. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6746. Tools._AddLogEntry(entry);
  6747. };
  6748. Object.defineProperty(Tools, "LogCache", {
  6749. get: function () {
  6750. return Tools._LogCache;
  6751. },
  6752. enumerable: true,
  6753. configurable: true
  6754. });
  6755. Tools.ClearLogCache = function () {
  6756. Tools._LogCache = "";
  6757. Tools.errorsCount = 0;
  6758. };
  6759. Object.defineProperty(Tools, "LogLevels", {
  6760. set: function (level) {
  6761. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6762. Tools.Log = Tools._LogEnabled;
  6763. }
  6764. else {
  6765. Tools.Log = Tools._LogDisabled;
  6766. }
  6767. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6768. Tools.Warn = Tools._WarnEnabled;
  6769. }
  6770. else {
  6771. Tools.Warn = Tools._WarnDisabled;
  6772. }
  6773. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6774. Tools.Error = Tools._ErrorEnabled;
  6775. }
  6776. else {
  6777. Tools.Error = Tools._ErrorDisabled;
  6778. }
  6779. },
  6780. enumerable: true,
  6781. configurable: true
  6782. });
  6783. Tools.IsWindowObjectExist = function () {
  6784. return (typeof window) !== "undefined";
  6785. };
  6786. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6787. get: function () {
  6788. return Tools._PerformanceNoneLogLevel;
  6789. },
  6790. enumerable: true,
  6791. configurable: true
  6792. });
  6793. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6794. get: function () {
  6795. return Tools._PerformanceUserMarkLogLevel;
  6796. },
  6797. enumerable: true,
  6798. configurable: true
  6799. });
  6800. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6801. get: function () {
  6802. return Tools._PerformanceConsoleLogLevel;
  6803. },
  6804. enumerable: true,
  6805. configurable: true
  6806. });
  6807. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6808. set: function (level) {
  6809. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6810. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6811. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6812. return;
  6813. }
  6814. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6815. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6816. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6817. return;
  6818. }
  6819. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6820. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6821. },
  6822. enumerable: true,
  6823. configurable: true
  6824. });
  6825. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6826. };
  6827. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6828. };
  6829. Tools._StartUserMark = function (counterName, condition) {
  6830. if (condition === void 0) { condition = true; }
  6831. if (!Tools._performance) {
  6832. if (!Tools.IsWindowObjectExist()) {
  6833. return;
  6834. }
  6835. Tools._performance = window.performance;
  6836. }
  6837. if (!condition || !Tools._performance.mark) {
  6838. return;
  6839. }
  6840. Tools._performance.mark(counterName + "-Begin");
  6841. };
  6842. Tools._EndUserMark = function (counterName, condition) {
  6843. if (condition === void 0) { condition = true; }
  6844. if (!condition || !Tools._performance.mark) {
  6845. return;
  6846. }
  6847. Tools._performance.mark(counterName + "-End");
  6848. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6849. };
  6850. Tools._StartPerformanceConsole = function (counterName, condition) {
  6851. if (condition === void 0) { condition = true; }
  6852. if (!condition) {
  6853. return;
  6854. }
  6855. Tools._StartUserMark(counterName, condition);
  6856. if (console.time) {
  6857. console.time(counterName);
  6858. }
  6859. };
  6860. Tools._EndPerformanceConsole = function (counterName, condition) {
  6861. if (condition === void 0) { condition = true; }
  6862. if (!condition) {
  6863. return;
  6864. }
  6865. Tools._EndUserMark(counterName, condition);
  6866. if (console.time) {
  6867. console.timeEnd(counterName);
  6868. }
  6869. };
  6870. Object.defineProperty(Tools, "Now", {
  6871. get: function () {
  6872. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  6873. return window.performance.now();
  6874. }
  6875. return new Date().getTime();
  6876. },
  6877. enumerable: true,
  6878. configurable: true
  6879. });
  6880. /**
  6881. * This method will return the name of the class used to create the instance of the given object.
  6882. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6883. * @param object the object to get the class name from
  6884. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6885. */
  6886. Tools.GetClassName = function (object, isType) {
  6887. if (isType === void 0) { isType = false; }
  6888. var name = null;
  6889. if (!isType && object.getClassName) {
  6890. name = object.getClassName();
  6891. }
  6892. else {
  6893. if (object instanceof Object) {
  6894. var classObj = isType ? object : Object.getPrototypeOf(object);
  6895. name = classObj.constructor["__bjsclassName__"];
  6896. }
  6897. if (!name) {
  6898. name = typeof object;
  6899. }
  6900. }
  6901. return name;
  6902. };
  6903. Tools.First = function (array, predicate) {
  6904. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6905. var el = array_1[_i];
  6906. if (predicate(el)) {
  6907. return el;
  6908. }
  6909. }
  6910. return null;
  6911. };
  6912. /**
  6913. * This method will return the name of the full name of the class, including its owning module (if any).
  6914. * 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).
  6915. * @param object the object to get the class name from
  6916. * @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.
  6917. */
  6918. Tools.getFullClassName = function (object, isType) {
  6919. if (isType === void 0) { isType = false; }
  6920. var className = null;
  6921. var moduleName = null;
  6922. if (!isType && object.getClassName) {
  6923. className = object.getClassName();
  6924. }
  6925. else {
  6926. if (object instanceof Object) {
  6927. var classObj = isType ? object : Object.getPrototypeOf(object);
  6928. className = classObj.constructor["__bjsclassName__"];
  6929. moduleName = classObj.constructor["__bjsmoduleName__"];
  6930. }
  6931. if (!className) {
  6932. className = typeof object;
  6933. }
  6934. }
  6935. if (!className) {
  6936. return null;
  6937. }
  6938. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6939. };
  6940. /**
  6941. * 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.
  6942. * @param array
  6943. */
  6944. Tools.arrayOrStringFeeder = function (array) {
  6945. return function (index) {
  6946. if (index >= array.length) {
  6947. return null;
  6948. }
  6949. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6950. if (val && val.getHashCode) {
  6951. val = val.getHashCode();
  6952. }
  6953. if (typeof val === "string") {
  6954. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6955. }
  6956. return val;
  6957. };
  6958. };
  6959. /**
  6960. * Compute the hashCode of a stream of number
  6961. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6962. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6963. * @return the hash code computed
  6964. */
  6965. Tools.hashCodeFromStream = function (feeder) {
  6966. // Based from here: http://stackoverflow.com/a/7616484/802124
  6967. var hash = 0;
  6968. var index = 0;
  6969. var chr = feeder(index++);
  6970. while (chr != null) {
  6971. hash = ((hash << 5) - hash) + chr;
  6972. hash |= 0; // Convert to 32bit integer
  6973. chr = feeder(index++);
  6974. }
  6975. return hash;
  6976. };
  6977. Tools.BaseUrl = "";
  6978. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  6979. /**
  6980. * Default behaviour for cors in the application.
  6981. * It can be a string if the expected behavior is identical in the entire app.
  6982. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  6983. */
  6984. Tools.CorsBehavior = "anonymous";
  6985. Tools.UseFallbackTexture = true;
  6986. /**
  6987. * Use this object to register external classes like custom textures or material
  6988. * to allow the laoders to instantiate them
  6989. */
  6990. Tools.RegisteredExternalClasses = {};
  6991. // Used in case of a texture loading problem
  6992. 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";
  6993. Tools.PreprocessUrl = function (url) {
  6994. return url;
  6995. };
  6996. // Logs
  6997. Tools._NoneLogLevel = 0;
  6998. Tools._MessageLogLevel = 1;
  6999. Tools._WarningLogLevel = 2;
  7000. Tools._ErrorLogLevel = 4;
  7001. Tools._LogCache = "";
  7002. Tools.errorsCount = 0;
  7003. Tools.Log = Tools._LogEnabled;
  7004. Tools.Warn = Tools._WarnEnabled;
  7005. Tools.Error = Tools._ErrorEnabled;
  7006. // Performances
  7007. Tools._PerformanceNoneLogLevel = 0;
  7008. Tools._PerformanceUserMarkLogLevel = 1;
  7009. Tools._PerformanceConsoleLogLevel = 2;
  7010. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7011. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7012. return Tools;
  7013. }());
  7014. BABYLON.Tools = Tools;
  7015. /**
  7016. * This class is used to track a performance counter which is number based.
  7017. * The user has access to many properties which give statistics of different nature
  7018. *
  7019. * The implementer can track two kinds of Performance Counter: time and count
  7020. * 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.
  7021. * 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.
  7022. */
  7023. var PerfCounter = /** @class */ (function () {
  7024. function PerfCounter() {
  7025. this._startMonitoringTime = 0;
  7026. this._min = 0;
  7027. this._max = 0;
  7028. this._average = 0;
  7029. this._lastSecAverage = 0;
  7030. this._current = 0;
  7031. this._totalValueCount = 0;
  7032. this._totalAccumulated = 0;
  7033. this._lastSecAccumulated = 0;
  7034. this._lastSecTime = 0;
  7035. this._lastSecValueCount = 0;
  7036. }
  7037. Object.defineProperty(PerfCounter.prototype, "min", {
  7038. /**
  7039. * Returns the smallest value ever
  7040. */
  7041. get: function () {
  7042. return this._min;
  7043. },
  7044. enumerable: true,
  7045. configurable: true
  7046. });
  7047. Object.defineProperty(PerfCounter.prototype, "max", {
  7048. /**
  7049. * Returns the biggest value ever
  7050. */
  7051. get: function () {
  7052. return this._max;
  7053. },
  7054. enumerable: true,
  7055. configurable: true
  7056. });
  7057. Object.defineProperty(PerfCounter.prototype, "average", {
  7058. /**
  7059. * Returns the average value since the performance counter is running
  7060. */
  7061. get: function () {
  7062. return this._average;
  7063. },
  7064. enumerable: true,
  7065. configurable: true
  7066. });
  7067. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  7068. /**
  7069. * Returns the average value of the last second the counter was monitored
  7070. */
  7071. get: function () {
  7072. return this._lastSecAverage;
  7073. },
  7074. enumerable: true,
  7075. configurable: true
  7076. });
  7077. Object.defineProperty(PerfCounter.prototype, "current", {
  7078. /**
  7079. * Returns the current value
  7080. */
  7081. get: function () {
  7082. return this._current;
  7083. },
  7084. enumerable: true,
  7085. configurable: true
  7086. });
  7087. Object.defineProperty(PerfCounter.prototype, "total", {
  7088. get: function () {
  7089. return this._totalAccumulated;
  7090. },
  7091. enumerable: true,
  7092. configurable: true
  7093. });
  7094. Object.defineProperty(PerfCounter.prototype, "count", {
  7095. get: function () {
  7096. return this._totalValueCount;
  7097. },
  7098. enumerable: true,
  7099. configurable: true
  7100. });
  7101. /**
  7102. * Call this method to start monitoring a new frame.
  7103. * 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.
  7104. */
  7105. PerfCounter.prototype.fetchNewFrame = function () {
  7106. this._totalValueCount++;
  7107. this._current = 0;
  7108. this._lastSecValueCount++;
  7109. };
  7110. /**
  7111. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  7112. * @param newCount the count value to add to the monitored count
  7113. * @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.
  7114. */
  7115. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  7116. if (!PerfCounter.Enabled) {
  7117. return;
  7118. }
  7119. this._current += newCount;
  7120. if (fetchResult) {
  7121. this._fetchResult();
  7122. }
  7123. };
  7124. /**
  7125. * Start monitoring this performance counter
  7126. */
  7127. PerfCounter.prototype.beginMonitoring = function () {
  7128. if (!PerfCounter.Enabled) {
  7129. return;
  7130. }
  7131. this._startMonitoringTime = Tools.Now;
  7132. };
  7133. /**
  7134. * Compute the time lapsed since the previous beginMonitoring() call.
  7135. * @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
  7136. */
  7137. PerfCounter.prototype.endMonitoring = function (newFrame) {
  7138. if (newFrame === void 0) { newFrame = true; }
  7139. if (!PerfCounter.Enabled) {
  7140. return;
  7141. }
  7142. if (newFrame) {
  7143. this.fetchNewFrame();
  7144. }
  7145. var currentTime = Tools.Now;
  7146. this._current = currentTime - this._startMonitoringTime;
  7147. if (newFrame) {
  7148. this._fetchResult();
  7149. }
  7150. };
  7151. PerfCounter.prototype._fetchResult = function () {
  7152. this._totalAccumulated += this._current;
  7153. this._lastSecAccumulated += this._current;
  7154. // Min/Max update
  7155. this._min = Math.min(this._min, this._current);
  7156. this._max = Math.max(this._max, this._current);
  7157. this._average = this._totalAccumulated / this._totalValueCount;
  7158. // Reset last sec?
  7159. var now = Tools.Now;
  7160. if ((now - this._lastSecTime) > 1000) {
  7161. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  7162. this._lastSecTime = now;
  7163. this._lastSecAccumulated = 0;
  7164. this._lastSecValueCount = 0;
  7165. }
  7166. };
  7167. PerfCounter.Enabled = true;
  7168. return PerfCounter;
  7169. }());
  7170. BABYLON.PerfCounter = PerfCounter;
  7171. /**
  7172. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  7173. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  7174. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  7175. * @param name The name of the class, case should be preserved
  7176. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  7177. */
  7178. function className(name, module) {
  7179. return function (target) {
  7180. target["__bjsclassName__"] = name;
  7181. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7182. };
  7183. }
  7184. BABYLON.className = className;
  7185. /**
  7186. * An implementation of a loop for asynchronous functions.
  7187. */
  7188. var AsyncLoop = /** @class */ (function () {
  7189. /**
  7190. * Constroctor.
  7191. * @param iterations the number of iterations.
  7192. * @param _fn the function to run each iteration
  7193. * @param _successCallback the callback that will be called upon succesful execution
  7194. * @param offset starting offset.
  7195. */
  7196. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7197. if (offset === void 0) { offset = 0; }
  7198. this.iterations = iterations;
  7199. this._fn = _fn;
  7200. this._successCallback = _successCallback;
  7201. this.index = offset - 1;
  7202. this._done = false;
  7203. }
  7204. /**
  7205. * Execute the next iteration. Must be called after the last iteration was finished.
  7206. */
  7207. AsyncLoop.prototype.executeNext = function () {
  7208. if (!this._done) {
  7209. if (this.index + 1 < this.iterations) {
  7210. ++this.index;
  7211. this._fn(this);
  7212. }
  7213. else {
  7214. this.breakLoop();
  7215. }
  7216. }
  7217. };
  7218. /**
  7219. * Break the loop and run the success callback.
  7220. */
  7221. AsyncLoop.prototype.breakLoop = function () {
  7222. this._done = true;
  7223. this._successCallback();
  7224. };
  7225. /**
  7226. * Helper function
  7227. */
  7228. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7229. if (offset === void 0) { offset = 0; }
  7230. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7231. loop.executeNext();
  7232. return loop;
  7233. };
  7234. /**
  7235. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7236. * @param iterations total number of iterations
  7237. * @param syncedIterations number of synchronous iterations in each async iteration.
  7238. * @param fn the function to call each iteration.
  7239. * @param callback a success call back that will be called when iterating stops.
  7240. * @param breakFunction a break condition (optional)
  7241. * @param timeout timeout settings for the setTimeout function. default - 0.
  7242. * @constructor
  7243. */
  7244. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7245. if (timeout === void 0) { timeout = 0; }
  7246. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7247. if (breakFunction && breakFunction())
  7248. loop.breakLoop();
  7249. else {
  7250. setTimeout(function () {
  7251. for (var i = 0; i < syncedIterations; ++i) {
  7252. var iteration = (loop.index * syncedIterations) + i;
  7253. if (iteration >= iterations)
  7254. break;
  7255. fn(iteration);
  7256. if (breakFunction && breakFunction()) {
  7257. loop.breakLoop();
  7258. break;
  7259. }
  7260. }
  7261. loop.executeNext();
  7262. }, timeout);
  7263. }
  7264. }, callback);
  7265. };
  7266. return AsyncLoop;
  7267. }());
  7268. BABYLON.AsyncLoop = AsyncLoop;
  7269. })(BABYLON || (BABYLON = {}));
  7270. //# sourceMappingURL=babylon.tools.js.map
  7271. var BABYLON;
  7272. (function (BABYLON) {
  7273. var Internals;
  7274. (function (Internals) {
  7275. var _AlphaState = /** @class */ (function () {
  7276. /**
  7277. * Initializes the state.
  7278. */
  7279. function _AlphaState() {
  7280. this._isAlphaBlendDirty = false;
  7281. this._isBlendFunctionParametersDirty = false;
  7282. this._isBlendEquationParametersDirty = false;
  7283. this._isBlendConstantsDirty = false;
  7284. this._alphaBlend = false;
  7285. this._blendFunctionParameters = new Array(4);
  7286. this._blendEquationParameters = new Array(2);
  7287. this._blendConstants = new Array(4);
  7288. this.reset();
  7289. }
  7290. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7291. get: function () {
  7292. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7293. },
  7294. enumerable: true,
  7295. configurable: true
  7296. });
  7297. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7298. get: function () {
  7299. return this._alphaBlend;
  7300. },
  7301. set: function (value) {
  7302. if (this._alphaBlend === value) {
  7303. return;
  7304. }
  7305. this._alphaBlend = value;
  7306. this._isAlphaBlendDirty = true;
  7307. },
  7308. enumerable: true,
  7309. configurable: true
  7310. });
  7311. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  7312. if (this._blendConstants[0] === r &&
  7313. this._blendConstants[1] === g &&
  7314. this._blendConstants[2] === b &&
  7315. this._blendConstants[3] === a) {
  7316. return;
  7317. }
  7318. this._blendConstants[0] = r;
  7319. this._blendConstants[1] = g;
  7320. this._blendConstants[2] = b;
  7321. this._blendConstants[3] = a;
  7322. this._isBlendConstantsDirty = true;
  7323. };
  7324. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7325. if (this._blendFunctionParameters[0] === value0 &&
  7326. this._blendFunctionParameters[1] === value1 &&
  7327. this._blendFunctionParameters[2] === value2 &&
  7328. this._blendFunctionParameters[3] === value3) {
  7329. return;
  7330. }
  7331. this._blendFunctionParameters[0] = value0;
  7332. this._blendFunctionParameters[1] = value1;
  7333. this._blendFunctionParameters[2] = value2;
  7334. this._blendFunctionParameters[3] = value3;
  7335. this._isBlendFunctionParametersDirty = true;
  7336. };
  7337. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  7338. if (this._blendEquationParameters[0] === rgb &&
  7339. this._blendEquationParameters[1] === alpha) {
  7340. return;
  7341. }
  7342. this._blendEquationParameters[0] = rgb;
  7343. this._blendEquationParameters[1] = alpha;
  7344. this._isBlendEquationParametersDirty = true;
  7345. };
  7346. _AlphaState.prototype.reset = function () {
  7347. this._alphaBlend = false;
  7348. this._blendFunctionParameters[0] = null;
  7349. this._blendFunctionParameters[1] = null;
  7350. this._blendFunctionParameters[2] = null;
  7351. this._blendFunctionParameters[3] = null;
  7352. this._blendEquationParameters[0] = null;
  7353. this._blendEquationParameters[1] = null;
  7354. this._blendConstants[0] = null;
  7355. this._blendConstants[1] = null;
  7356. this._blendConstants[2] = null;
  7357. this._blendConstants[3] = null;
  7358. this._isAlphaBlendDirty = true;
  7359. this._isBlendFunctionParametersDirty = false;
  7360. this._isBlendEquationParametersDirty = false;
  7361. this._isBlendConstantsDirty = false;
  7362. };
  7363. _AlphaState.prototype.apply = function (gl) {
  7364. if (!this.isDirty) {
  7365. return;
  7366. }
  7367. // Alpha blend
  7368. if (this._isAlphaBlendDirty) {
  7369. if (this._alphaBlend) {
  7370. gl.enable(gl.BLEND);
  7371. }
  7372. else {
  7373. gl.disable(gl.BLEND);
  7374. }
  7375. this._isAlphaBlendDirty = false;
  7376. }
  7377. // Alpha function
  7378. if (this._isBlendFunctionParametersDirty) {
  7379. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7380. this._isBlendFunctionParametersDirty = false;
  7381. }
  7382. // Alpha equation
  7383. if (this._isBlendEquationParametersDirty) {
  7384. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  7385. this._isBlendEquationParametersDirty = false;
  7386. }
  7387. // Constants
  7388. if (this._isBlendConstantsDirty) {
  7389. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  7390. this._isBlendConstantsDirty = false;
  7391. }
  7392. };
  7393. return _AlphaState;
  7394. }());
  7395. Internals._AlphaState = _AlphaState;
  7396. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7397. })(BABYLON || (BABYLON = {}));
  7398. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7399. var BABYLON;
  7400. (function (BABYLON) {
  7401. var Internals;
  7402. (function (Internals) {
  7403. var _DepthCullingState = /** @class */ (function () {
  7404. /**
  7405. * Initializes the state.
  7406. */
  7407. function _DepthCullingState() {
  7408. this._isDepthTestDirty = false;
  7409. this._isDepthMaskDirty = false;
  7410. this._isDepthFuncDirty = false;
  7411. this._isCullFaceDirty = false;
  7412. this._isCullDirty = false;
  7413. this._isZOffsetDirty = false;
  7414. this._isFrontFaceDirty = false;
  7415. this.reset();
  7416. }
  7417. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7418. get: function () {
  7419. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  7420. },
  7421. enumerable: true,
  7422. configurable: true
  7423. });
  7424. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7425. get: function () {
  7426. return this._zOffset;
  7427. },
  7428. set: function (value) {
  7429. if (this._zOffset === value) {
  7430. return;
  7431. }
  7432. this._zOffset = value;
  7433. this._isZOffsetDirty = true;
  7434. },
  7435. enumerable: true,
  7436. configurable: true
  7437. });
  7438. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7439. get: function () {
  7440. return this._cullFace;
  7441. },
  7442. set: function (value) {
  7443. if (this._cullFace === value) {
  7444. return;
  7445. }
  7446. this._cullFace = value;
  7447. this._isCullFaceDirty = true;
  7448. },
  7449. enumerable: true,
  7450. configurable: true
  7451. });
  7452. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7453. get: function () {
  7454. return this._cull;
  7455. },
  7456. set: function (value) {
  7457. if (this._cull === value) {
  7458. return;
  7459. }
  7460. this._cull = value;
  7461. this._isCullDirty = true;
  7462. },
  7463. enumerable: true,
  7464. configurable: true
  7465. });
  7466. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7467. get: function () {
  7468. return this._depthFunc;
  7469. },
  7470. set: function (value) {
  7471. if (this._depthFunc === value) {
  7472. return;
  7473. }
  7474. this._depthFunc = value;
  7475. this._isDepthFuncDirty = true;
  7476. },
  7477. enumerable: true,
  7478. configurable: true
  7479. });
  7480. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7481. get: function () {
  7482. return this._depthMask;
  7483. },
  7484. set: function (value) {
  7485. if (this._depthMask === value) {
  7486. return;
  7487. }
  7488. this._depthMask = value;
  7489. this._isDepthMaskDirty = true;
  7490. },
  7491. enumerable: true,
  7492. configurable: true
  7493. });
  7494. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7495. get: function () {
  7496. return this._depthTest;
  7497. },
  7498. set: function (value) {
  7499. if (this._depthTest === value) {
  7500. return;
  7501. }
  7502. this._depthTest = value;
  7503. this._isDepthTestDirty = true;
  7504. },
  7505. enumerable: true,
  7506. configurable: true
  7507. });
  7508. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  7509. get: function () {
  7510. return this._frontFace;
  7511. },
  7512. set: function (value) {
  7513. if (this._frontFace === value) {
  7514. return;
  7515. }
  7516. this._frontFace = value;
  7517. this._isFrontFaceDirty = true;
  7518. },
  7519. enumerable: true,
  7520. configurable: true
  7521. });
  7522. _DepthCullingState.prototype.reset = function () {
  7523. this._depthMask = true;
  7524. this._depthTest = true;
  7525. this._depthFunc = null;
  7526. this._cullFace = null;
  7527. this._cull = null;
  7528. this._zOffset = 0;
  7529. this._frontFace = null;
  7530. this._isDepthTestDirty = true;
  7531. this._isDepthMaskDirty = true;
  7532. this._isDepthFuncDirty = false;
  7533. this._isCullFaceDirty = false;
  7534. this._isCullDirty = false;
  7535. this._isZOffsetDirty = false;
  7536. this._isFrontFaceDirty = false;
  7537. };
  7538. _DepthCullingState.prototype.apply = function (gl) {
  7539. if (!this.isDirty) {
  7540. return;
  7541. }
  7542. // Cull
  7543. if (this._isCullDirty) {
  7544. if (this.cull) {
  7545. gl.enable(gl.CULL_FACE);
  7546. }
  7547. else {
  7548. gl.disable(gl.CULL_FACE);
  7549. }
  7550. this._isCullDirty = false;
  7551. }
  7552. // Cull face
  7553. if (this._isCullFaceDirty) {
  7554. gl.cullFace(this.cullFace);
  7555. this._isCullFaceDirty = false;
  7556. }
  7557. // Depth mask
  7558. if (this._isDepthMaskDirty) {
  7559. gl.depthMask(this.depthMask);
  7560. this._isDepthMaskDirty = false;
  7561. }
  7562. // Depth test
  7563. if (this._isDepthTestDirty) {
  7564. if (this.depthTest) {
  7565. gl.enable(gl.DEPTH_TEST);
  7566. }
  7567. else {
  7568. gl.disable(gl.DEPTH_TEST);
  7569. }
  7570. this._isDepthTestDirty = false;
  7571. }
  7572. // Depth func
  7573. if (this._isDepthFuncDirty) {
  7574. gl.depthFunc(this.depthFunc);
  7575. this._isDepthFuncDirty = false;
  7576. }
  7577. // zOffset
  7578. if (this._isZOffsetDirty) {
  7579. if (this.zOffset) {
  7580. gl.enable(gl.POLYGON_OFFSET_FILL);
  7581. gl.polygonOffset(this.zOffset, 0);
  7582. }
  7583. else {
  7584. gl.disable(gl.POLYGON_OFFSET_FILL);
  7585. }
  7586. this._isZOffsetDirty = false;
  7587. }
  7588. // Front face
  7589. if (this._isFrontFaceDirty) {
  7590. gl.frontFace(this.frontFace);
  7591. this._isFrontFaceDirty = false;
  7592. }
  7593. };
  7594. return _DepthCullingState;
  7595. }());
  7596. Internals._DepthCullingState = _DepthCullingState;
  7597. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7598. })(BABYLON || (BABYLON = {}));
  7599. //# sourceMappingURL=babylon.depthCullingState.js.map
  7600. var BABYLON;
  7601. (function (BABYLON) {
  7602. var Internals;
  7603. (function (Internals) {
  7604. var _StencilState = /** @class */ (function () {
  7605. function _StencilState() {
  7606. this._isStencilTestDirty = false;
  7607. this._isStencilMaskDirty = false;
  7608. this._isStencilFuncDirty = false;
  7609. this._isStencilOpDirty = false;
  7610. this.reset();
  7611. }
  7612. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7613. get: function () {
  7614. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7615. },
  7616. enumerable: true,
  7617. configurable: true
  7618. });
  7619. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7620. get: function () {
  7621. return this._stencilFunc;
  7622. },
  7623. set: function (value) {
  7624. if (this._stencilFunc === value) {
  7625. return;
  7626. }
  7627. this._stencilFunc = value;
  7628. this._isStencilFuncDirty = true;
  7629. },
  7630. enumerable: true,
  7631. configurable: true
  7632. });
  7633. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7634. get: function () {
  7635. return this._stencilFuncRef;
  7636. },
  7637. set: function (value) {
  7638. if (this._stencilFuncRef === value) {
  7639. return;
  7640. }
  7641. this._stencilFuncRef = value;
  7642. this._isStencilFuncDirty = true;
  7643. },
  7644. enumerable: true,
  7645. configurable: true
  7646. });
  7647. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7648. get: function () {
  7649. return this._stencilFuncMask;
  7650. },
  7651. set: function (value) {
  7652. if (this._stencilFuncMask === value) {
  7653. return;
  7654. }
  7655. this._stencilFuncMask = value;
  7656. this._isStencilFuncDirty = true;
  7657. },
  7658. enumerable: true,
  7659. configurable: true
  7660. });
  7661. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7662. get: function () {
  7663. return this._stencilOpStencilFail;
  7664. },
  7665. set: function (value) {
  7666. if (this._stencilOpStencilFail === value) {
  7667. return;
  7668. }
  7669. this._stencilOpStencilFail = value;
  7670. this._isStencilOpDirty = true;
  7671. },
  7672. enumerable: true,
  7673. configurable: true
  7674. });
  7675. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7676. get: function () {
  7677. return this._stencilOpDepthFail;
  7678. },
  7679. set: function (value) {
  7680. if (this._stencilOpDepthFail === value) {
  7681. return;
  7682. }
  7683. this._stencilOpDepthFail = value;
  7684. this._isStencilOpDirty = true;
  7685. },
  7686. enumerable: true,
  7687. configurable: true
  7688. });
  7689. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7690. get: function () {
  7691. return this._stencilOpStencilDepthPass;
  7692. },
  7693. set: function (value) {
  7694. if (this._stencilOpStencilDepthPass === value) {
  7695. return;
  7696. }
  7697. this._stencilOpStencilDepthPass = value;
  7698. this._isStencilOpDirty = true;
  7699. },
  7700. enumerable: true,
  7701. configurable: true
  7702. });
  7703. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7704. get: function () {
  7705. return this._stencilMask;
  7706. },
  7707. set: function (value) {
  7708. if (this._stencilMask === value) {
  7709. return;
  7710. }
  7711. this._stencilMask = value;
  7712. this._isStencilMaskDirty = true;
  7713. },
  7714. enumerable: true,
  7715. configurable: true
  7716. });
  7717. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7718. get: function () {
  7719. return this._stencilTest;
  7720. },
  7721. set: function (value) {
  7722. if (this._stencilTest === value) {
  7723. return;
  7724. }
  7725. this._stencilTest = value;
  7726. this._isStencilTestDirty = true;
  7727. },
  7728. enumerable: true,
  7729. configurable: true
  7730. });
  7731. _StencilState.prototype.reset = function () {
  7732. this._stencilTest = false;
  7733. this._stencilMask = 0xFF;
  7734. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7735. this._stencilFuncRef = 1;
  7736. this._stencilFuncMask = 0xFF;
  7737. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7738. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7739. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7740. this._isStencilTestDirty = true;
  7741. this._isStencilMaskDirty = true;
  7742. this._isStencilFuncDirty = true;
  7743. this._isStencilOpDirty = true;
  7744. };
  7745. _StencilState.prototype.apply = function (gl) {
  7746. if (!this.isDirty) {
  7747. return;
  7748. }
  7749. // Stencil test
  7750. if (this._isStencilTestDirty) {
  7751. if (this.stencilTest) {
  7752. gl.enable(gl.STENCIL_TEST);
  7753. }
  7754. else {
  7755. gl.disable(gl.STENCIL_TEST);
  7756. }
  7757. this._isStencilTestDirty = false;
  7758. }
  7759. // Stencil mask
  7760. if (this._isStencilMaskDirty) {
  7761. gl.stencilMask(this.stencilMask);
  7762. this._isStencilMaskDirty = false;
  7763. }
  7764. // Stencil func
  7765. if (this._isStencilFuncDirty) {
  7766. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7767. this._isStencilFuncDirty = false;
  7768. }
  7769. // Stencil op
  7770. if (this._isStencilOpDirty) {
  7771. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7772. this._isStencilOpDirty = false;
  7773. }
  7774. };
  7775. return _StencilState;
  7776. }());
  7777. Internals._StencilState = _StencilState;
  7778. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7779. })(BABYLON || (BABYLON = {}));
  7780. //# sourceMappingURL=babylon.stencilState.js.map
  7781. var BABYLON;
  7782. (function (BABYLON) {
  7783. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7784. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  7785. };
  7786. var compileRawShader = function (gl, source, type) {
  7787. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7788. gl.shaderSource(shader, source);
  7789. gl.compileShader(shader);
  7790. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7791. var log = gl.getShaderInfoLog(shader);
  7792. if (log) {
  7793. throw new Error(log);
  7794. }
  7795. }
  7796. if (!shader) {
  7797. throw new Error("Something went wrong while compile the shader.");
  7798. }
  7799. return shader;
  7800. };
  7801. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7802. var magFilter = gl.NEAREST;
  7803. var minFilter = gl.NEAREST;
  7804. switch (samplingMode) {
  7805. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7806. magFilter = gl.LINEAR;
  7807. if (generateMipMaps) {
  7808. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7809. }
  7810. else {
  7811. minFilter = gl.LINEAR;
  7812. }
  7813. break;
  7814. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7815. magFilter = gl.LINEAR;
  7816. if (generateMipMaps) {
  7817. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7818. }
  7819. else {
  7820. minFilter = gl.LINEAR;
  7821. }
  7822. break;
  7823. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7824. magFilter = gl.NEAREST;
  7825. if (generateMipMaps) {
  7826. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7827. }
  7828. else {
  7829. minFilter = gl.NEAREST;
  7830. }
  7831. break;
  7832. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7833. magFilter = gl.NEAREST;
  7834. if (generateMipMaps) {
  7835. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7836. }
  7837. else {
  7838. minFilter = gl.NEAREST;
  7839. }
  7840. break;
  7841. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7842. magFilter = gl.NEAREST;
  7843. if (generateMipMaps) {
  7844. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7845. }
  7846. else {
  7847. minFilter = gl.LINEAR;
  7848. }
  7849. break;
  7850. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7851. magFilter = gl.NEAREST;
  7852. if (generateMipMaps) {
  7853. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7854. }
  7855. else {
  7856. minFilter = gl.LINEAR;
  7857. }
  7858. break;
  7859. case BABYLON.Texture.NEAREST_LINEAR:
  7860. magFilter = gl.NEAREST;
  7861. minFilter = gl.LINEAR;
  7862. break;
  7863. case BABYLON.Texture.NEAREST_NEAREST:
  7864. magFilter = gl.NEAREST;
  7865. minFilter = gl.NEAREST;
  7866. break;
  7867. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7868. magFilter = gl.LINEAR;
  7869. if (generateMipMaps) {
  7870. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7871. }
  7872. else {
  7873. minFilter = gl.NEAREST;
  7874. }
  7875. break;
  7876. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7877. magFilter = gl.LINEAR;
  7878. if (generateMipMaps) {
  7879. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7880. }
  7881. else {
  7882. minFilter = gl.NEAREST;
  7883. }
  7884. break;
  7885. case BABYLON.Texture.LINEAR_LINEAR:
  7886. magFilter = gl.LINEAR;
  7887. minFilter = gl.LINEAR;
  7888. break;
  7889. case BABYLON.Texture.LINEAR_NEAREST:
  7890. magFilter = gl.LINEAR;
  7891. minFilter = gl.NEAREST;
  7892. break;
  7893. }
  7894. return {
  7895. min: minFilter,
  7896. mag: magFilter
  7897. };
  7898. };
  7899. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7900. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7901. var img;
  7902. var onload = function () {
  7903. loadedImages[index] = img;
  7904. loadedImages._internalCount++;
  7905. if (scene) {
  7906. scene._removePendingData(img);
  7907. }
  7908. if (loadedImages._internalCount === 6) {
  7909. onfinish(loadedImages);
  7910. }
  7911. };
  7912. var onerror = function (message, exception) {
  7913. if (scene) {
  7914. scene._removePendingData(img);
  7915. }
  7916. if (onErrorCallBack) {
  7917. onErrorCallBack(message, exception);
  7918. }
  7919. };
  7920. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7921. if (scene) {
  7922. scene._addPendingData(img);
  7923. }
  7924. };
  7925. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  7926. if (onError === void 0) { onError = null; }
  7927. var loadedImages = [];
  7928. loadedImages._internalCount = 0;
  7929. for (var index = 0; index < 6; index++) {
  7930. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  7931. }
  7932. };
  7933. var partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  7934. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7935. var onload = function (data) {
  7936. loadedFiles[index] = data;
  7937. loadedFiles._internalCount++;
  7938. if (loadedFiles._internalCount === 6) {
  7939. onfinish(loadedFiles);
  7940. }
  7941. };
  7942. var onerror = function (request, exception) {
  7943. if (onErrorCallBack && request) {
  7944. onErrorCallBack(request.status + " " + request.statusText, exception);
  7945. }
  7946. };
  7947. BABYLON.Tools.LoadFile(url, onload, undefined, undefined, true, onerror);
  7948. };
  7949. var cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  7950. if (onError === void 0) { onError = null; }
  7951. var loadedFiles = [];
  7952. loadedFiles._internalCount = 0;
  7953. for (var index = 0; index < 6; index++) {
  7954. partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  7955. }
  7956. };
  7957. var BufferPointer = /** @class */ (function () {
  7958. function BufferPointer() {
  7959. }
  7960. return BufferPointer;
  7961. }());
  7962. var InstancingAttributeInfo = /** @class */ (function () {
  7963. function InstancingAttributeInfo() {
  7964. }
  7965. return InstancingAttributeInfo;
  7966. }());
  7967. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7968. /**
  7969. * Define options used to create a render target texture
  7970. */
  7971. var RenderTargetCreationOptions = /** @class */ (function () {
  7972. function RenderTargetCreationOptions() {
  7973. }
  7974. return RenderTargetCreationOptions;
  7975. }());
  7976. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7977. /**
  7978. * Regroup several parameters relative to the browser in use
  7979. */
  7980. var EngineCapabilities = /** @class */ (function () {
  7981. function EngineCapabilities() {
  7982. }
  7983. return EngineCapabilities;
  7984. }());
  7985. BABYLON.EngineCapabilities = EngineCapabilities;
  7986. /**
  7987. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7988. */
  7989. var Engine = /** @class */ (function () {
  7990. /**
  7991. * @constructor
  7992. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7993. * @param {boolean} [antialias] - enable antialias
  7994. * @param options - further options to be sent to the getContext function
  7995. */
  7996. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7997. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7998. var _this = this;
  7999. // Public members
  8000. this.forcePOTTextures = false;
  8001. this.isFullscreen = false;
  8002. this.isPointerLock = false;
  8003. this.cullBackFaces = true;
  8004. this.renderEvenInBackground = true;
  8005. this.preventCacheWipeBetweenFrames = false;
  8006. // To enable/disable IDB support and avoid XHR on .manifest
  8007. this.enableOfflineSupport = false;
  8008. this.scenes = new Array();
  8009. this.postProcesses = new Array();
  8010. // Observables
  8011. /**
  8012. * Observable event triggered each time the rendering canvas is resized
  8013. */
  8014. this.onResizeObservable = new BABYLON.Observable();
  8015. /**
  8016. * Observable event triggered each time the canvas loses focus
  8017. */
  8018. this.onCanvasBlurObservable = new BABYLON.Observable();
  8019. /**
  8020. * Observable event triggered each time the canvas gains focus
  8021. */
  8022. this.onCanvasFocusObservable = new BABYLON.Observable();
  8023. /**
  8024. * Observable event triggered each time the canvas receives pointerout event
  8025. */
  8026. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  8027. /**
  8028. * Observable event triggered before each texture is initialized
  8029. */
  8030. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  8031. //WebVR
  8032. this._vrDisplay = undefined;
  8033. this._vrSupported = false;
  8034. this._vrExclusivePointerMode = false;
  8035. // Uniform buffers list
  8036. this.disableUniformBuffers = false;
  8037. this._uniformBuffers = new Array();
  8038. // Observables
  8039. /**
  8040. * Observable raised when the engine begins a new frame
  8041. */
  8042. this.onBeginFrameObservable = new BABYLON.Observable();
  8043. /**
  8044. * Observable raised when the engine ends the current frame
  8045. */
  8046. this.onEndFrameObservable = new BABYLON.Observable();
  8047. /**
  8048. * Observable raised when the engine is about to compile a shader
  8049. */
  8050. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  8051. /**
  8052. * Observable raised when the engine has jsut compiled a shader
  8053. */
  8054. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  8055. this._windowIsBackground = false;
  8056. this._webGLVersion = 1.0;
  8057. this._badOS = false;
  8058. this._badDesktopOS = false;
  8059. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  8060. this.onVRRequestPresentComplete = new BABYLON.Observable();
  8061. this.onVRRequestPresentStart = new BABYLON.Observable();
  8062. this._colorWrite = true;
  8063. this._drawCalls = new BABYLON.PerfCounter();
  8064. this._renderingQueueLaunched = false;
  8065. this._activeRenderLoops = new Array();
  8066. // Deterministic lockstepMaxSteps
  8067. this._deterministicLockstep = false;
  8068. this._lockstepMaxSteps = 4;
  8069. // Lost context
  8070. this.onContextLostObservable = new BABYLON.Observable();
  8071. this.onContextRestoredObservable = new BABYLON.Observable();
  8072. this._contextWasLost = false;
  8073. this._doNotHandleContextLost = false;
  8074. // FPS
  8075. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  8076. this._fps = 60;
  8077. this._deltaTime = 0;
  8078. /**
  8079. * Turn this value on if you want to pause FPS computation when in background
  8080. */
  8081. this.disablePerformanceMonitorInBackground = false;
  8082. // States
  8083. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  8084. this._stencilState = new BABYLON.Internals._StencilState();
  8085. this._alphaState = new BABYLON.Internals._AlphaState();
  8086. this._alphaMode = Engine.ALPHA_DISABLE;
  8087. // Cache
  8088. this._internalTexturesCache = new Array();
  8089. this._boundTexturesCache = {};
  8090. this._boundTexturesOrder = new Array();
  8091. this._compiledEffects = {};
  8092. this._vertexAttribArraysEnabled = [];
  8093. this._uintIndicesCurrentlySet = false;
  8094. this._currentBoundBuffer = new Array();
  8095. this._currentBufferPointers = new Array();
  8096. this._currentInstanceLocations = new Array();
  8097. this._currentInstanceBuffers = new Array();
  8098. this._vaoRecordInProgress = false;
  8099. this._mustWipeVertexAttributes = false;
  8100. this._nextFreeTextureSlot = 0;
  8101. // Hardware supported Compressed Textures
  8102. this._texturesSupported = new Array();
  8103. this._onVRFullScreenTriggered = function () {
  8104. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  8105. //get the old size before we change
  8106. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  8107. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  8108. //get the width and height, change the render size
  8109. var leftEye = _this._vrDisplay.getEyeParameters('left');
  8110. _this.setHardwareScalingLevel(1);
  8111. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  8112. }
  8113. else {
  8114. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  8115. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  8116. }
  8117. };
  8118. this._boundUniforms = {};
  8119. var canvas = null;
  8120. Engine.Instances.push(this);
  8121. if (!canvasOrContext) {
  8122. return;
  8123. }
  8124. options = options || {};
  8125. if (canvasOrContext.getContext) {
  8126. canvas = canvasOrContext;
  8127. this._renderingCanvas = canvas;
  8128. if (antialias != null) {
  8129. options.antialias = antialias;
  8130. }
  8131. if (options.deterministicLockstep === undefined) {
  8132. options.deterministicLockstep = false;
  8133. }
  8134. if (options.lockstepMaxSteps === undefined) {
  8135. options.lockstepMaxSteps = 4;
  8136. }
  8137. if (options.preserveDrawingBuffer === undefined) {
  8138. options.preserveDrawingBuffer = false;
  8139. }
  8140. if (options.audioEngine === undefined) {
  8141. options.audioEngine = true;
  8142. }
  8143. if (options.stencil === undefined) {
  8144. options.stencil = true;
  8145. }
  8146. this._deterministicLockstep = options.deterministicLockstep;
  8147. this._lockstepMaxSteps = options.lockstepMaxSteps;
  8148. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  8149. // Exceptions
  8150. if (!options.disableWebGL2Support) {
  8151. if (navigator && navigator.userAgent) {
  8152. var ua = navigator.userAgent;
  8153. for (var _i = 0, _a = Engine.WebGL2UniformBuffersExceptionList; _i < _a.length; _i++) {
  8154. var exception = _a[_i];
  8155. if (ua.indexOf(exception) > -1) {
  8156. this.disableUniformBuffers = true;
  8157. break;
  8158. }
  8159. }
  8160. }
  8161. }
  8162. // GL
  8163. if (!options.disableWebGL2Support) {
  8164. try {
  8165. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  8166. if (this._gl) {
  8167. this._webGLVersion = 2.0;
  8168. }
  8169. }
  8170. catch (e) {
  8171. // Do nothing
  8172. }
  8173. }
  8174. if (!this._gl) {
  8175. if (!canvas) {
  8176. throw new Error("The provided canvas is null or undefined.");
  8177. }
  8178. try {
  8179. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  8180. }
  8181. catch (e) {
  8182. throw new Error("WebGL not supported");
  8183. }
  8184. }
  8185. if (!this._gl) {
  8186. throw new Error("WebGL not supported");
  8187. }
  8188. this._onCanvasFocus = function () {
  8189. _this.onCanvasFocusObservable.notifyObservers(_this);
  8190. };
  8191. this._onCanvasBlur = function () {
  8192. _this.onCanvasBlurObservable.notifyObservers(_this);
  8193. };
  8194. canvas.addEventListener("focus", this._onCanvasFocus);
  8195. canvas.addEventListener("blur", this._onCanvasBlur);
  8196. this._onBlur = function () {
  8197. if (_this.disablePerformanceMonitorInBackground) {
  8198. _this._performanceMonitor.disable();
  8199. }
  8200. _this._windowIsBackground = true;
  8201. };
  8202. this._onFocus = function () {
  8203. if (_this.disablePerformanceMonitorInBackground) {
  8204. _this._performanceMonitor.enable();
  8205. }
  8206. _this._windowIsBackground = false;
  8207. };
  8208. this._onCanvasPointerOut = function () {
  8209. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  8210. };
  8211. window.addEventListener("blur", this._onBlur);
  8212. window.addEventListener("focus", this._onFocus);
  8213. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  8214. // Context lost
  8215. if (!this._doNotHandleContextLost) {
  8216. this._onContextLost = function (evt) {
  8217. evt.preventDefault();
  8218. _this._contextWasLost = true;
  8219. BABYLON.Tools.Warn("WebGL context lost.");
  8220. _this.onContextLostObservable.notifyObservers(_this);
  8221. };
  8222. this._onContextRestored = function (evt) {
  8223. // Adding a timeout to avoid race condition at browser level
  8224. setTimeout(function () {
  8225. // Rebuild gl context
  8226. _this._initGLContext();
  8227. // Rebuild effects
  8228. _this._rebuildEffects();
  8229. // Rebuild textures
  8230. _this._rebuildInternalTextures();
  8231. // Rebuild buffers
  8232. _this._rebuildBuffers();
  8233. // Cache
  8234. _this.wipeCaches(true);
  8235. BABYLON.Tools.Warn("WebGL context successfully restored.");
  8236. _this.onContextRestoredObservable.notifyObservers(_this);
  8237. _this._contextWasLost = false;
  8238. }, 0);
  8239. };
  8240. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  8241. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  8242. }
  8243. }
  8244. else {
  8245. this._gl = canvasOrContext;
  8246. this._renderingCanvas = this._gl.canvas;
  8247. if (this._gl.renderbufferStorageMultisample) {
  8248. this._webGLVersion = 2.0;
  8249. }
  8250. options.stencil = this._gl.getContextAttributes().stencil;
  8251. }
  8252. // Viewport
  8253. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  8254. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  8255. this.resize();
  8256. this._isStencilEnable = options.stencil ? true : false;
  8257. this._initGLContext();
  8258. if (canvas) {
  8259. // Fullscreen
  8260. this._onFullscreenChange = function () {
  8261. if (document.fullscreen !== undefined) {
  8262. _this.isFullscreen = document.fullscreen;
  8263. }
  8264. else if (document.mozFullScreen !== undefined) {
  8265. _this.isFullscreen = document.mozFullScreen;
  8266. }
  8267. else if (document.webkitIsFullScreen !== undefined) {
  8268. _this.isFullscreen = document.webkitIsFullScreen;
  8269. }
  8270. else if (document.msIsFullScreen !== undefined) {
  8271. _this.isFullscreen = document.msIsFullScreen;
  8272. }
  8273. // Pointer lock
  8274. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  8275. canvas.requestPointerLock = canvas.requestPointerLock ||
  8276. canvas.msRequestPointerLock ||
  8277. canvas.mozRequestPointerLock ||
  8278. canvas.webkitRequestPointerLock;
  8279. if (canvas.requestPointerLock) {
  8280. canvas.requestPointerLock();
  8281. }
  8282. }
  8283. };
  8284. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  8285. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  8286. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  8287. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  8288. // Pointer lock
  8289. this._onPointerLockChange = function () {
  8290. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  8291. document.webkitPointerLockElement === canvas ||
  8292. document.msPointerLockElement === canvas ||
  8293. document.pointerLockElement === canvas);
  8294. };
  8295. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  8296. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  8297. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  8298. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  8299. this._onVRDisplayPointerRestricted = function () {
  8300. if (canvas) {
  8301. canvas.requestPointerLock();
  8302. }
  8303. };
  8304. this._onVRDisplayPointerUnrestricted = function () {
  8305. document.exitPointerLock();
  8306. };
  8307. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  8308. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  8309. }
  8310. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  8311. Engine.audioEngine = new BABYLON.AudioEngine();
  8312. }
  8313. // Prepare buffer pointers
  8314. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  8315. this._currentBufferPointers[i] = new BufferPointer();
  8316. }
  8317. // Load WebVR Devices
  8318. if (options.autoEnableWebVR) {
  8319. this.initWebVR();
  8320. }
  8321. // Detect if we are running on a faulty buggy OS.
  8322. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  8323. // Detect if we are running on a faulty buggy desktop OS.
  8324. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  8325. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  8326. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  8327. }
  8328. Object.defineProperty(Engine, "LastCreatedEngine", {
  8329. get: function () {
  8330. if (Engine.Instances.length === 0) {
  8331. return null;
  8332. }
  8333. return Engine.Instances[Engine.Instances.length - 1];
  8334. },
  8335. enumerable: true,
  8336. configurable: true
  8337. });
  8338. Object.defineProperty(Engine, "LastCreatedScene", {
  8339. get: function () {
  8340. var lastCreatedEngine = Engine.LastCreatedEngine;
  8341. if (!lastCreatedEngine) {
  8342. return null;
  8343. }
  8344. if (lastCreatedEngine.scenes.length === 0) {
  8345. return null;
  8346. }
  8347. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  8348. },
  8349. enumerable: true,
  8350. configurable: true
  8351. });
  8352. /**
  8353. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  8354. */
  8355. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  8356. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  8357. var engine = Engine.Instances[engineIndex];
  8358. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  8359. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  8360. }
  8361. }
  8362. };
  8363. Object.defineProperty(Engine, "NEVER", {
  8364. get: function () {
  8365. return Engine._NEVER;
  8366. },
  8367. enumerable: true,
  8368. configurable: true
  8369. });
  8370. Object.defineProperty(Engine, "ALWAYS", {
  8371. get: function () {
  8372. return Engine._ALWAYS;
  8373. },
  8374. enumerable: true,
  8375. configurable: true
  8376. });
  8377. Object.defineProperty(Engine, "LESS", {
  8378. get: function () {
  8379. return Engine._LESS;
  8380. },
  8381. enumerable: true,
  8382. configurable: true
  8383. });
  8384. Object.defineProperty(Engine, "EQUAL", {
  8385. get: function () {
  8386. return Engine._EQUAL;
  8387. },
  8388. enumerable: true,
  8389. configurable: true
  8390. });
  8391. Object.defineProperty(Engine, "LEQUAL", {
  8392. get: function () {
  8393. return Engine._LEQUAL;
  8394. },
  8395. enumerable: true,
  8396. configurable: true
  8397. });
  8398. Object.defineProperty(Engine, "GREATER", {
  8399. get: function () {
  8400. return Engine._GREATER;
  8401. },
  8402. enumerable: true,
  8403. configurable: true
  8404. });
  8405. Object.defineProperty(Engine, "GEQUAL", {
  8406. get: function () {
  8407. return Engine._GEQUAL;
  8408. },
  8409. enumerable: true,
  8410. configurable: true
  8411. });
  8412. Object.defineProperty(Engine, "NOTEQUAL", {
  8413. get: function () {
  8414. return Engine._NOTEQUAL;
  8415. },
  8416. enumerable: true,
  8417. configurable: true
  8418. });
  8419. Object.defineProperty(Engine, "KEEP", {
  8420. get: function () {
  8421. return Engine._KEEP;
  8422. },
  8423. enumerable: true,
  8424. configurable: true
  8425. });
  8426. Object.defineProperty(Engine, "REPLACE", {
  8427. get: function () {
  8428. return Engine._REPLACE;
  8429. },
  8430. enumerable: true,
  8431. configurable: true
  8432. });
  8433. Object.defineProperty(Engine, "INCR", {
  8434. get: function () {
  8435. return Engine._INCR;
  8436. },
  8437. enumerable: true,
  8438. configurable: true
  8439. });
  8440. Object.defineProperty(Engine, "DECR", {
  8441. get: function () {
  8442. return Engine._DECR;
  8443. },
  8444. enumerable: true,
  8445. configurable: true
  8446. });
  8447. Object.defineProperty(Engine, "INVERT", {
  8448. get: function () {
  8449. return Engine._INVERT;
  8450. },
  8451. enumerable: true,
  8452. configurable: true
  8453. });
  8454. Object.defineProperty(Engine, "INCR_WRAP", {
  8455. get: function () {
  8456. return Engine._INCR_WRAP;
  8457. },
  8458. enumerable: true,
  8459. configurable: true
  8460. });
  8461. Object.defineProperty(Engine, "DECR_WRAP", {
  8462. get: function () {
  8463. return Engine._DECR_WRAP;
  8464. },
  8465. enumerable: true,
  8466. configurable: true
  8467. });
  8468. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8469. get: function () {
  8470. return Engine._ALPHA_DISABLE;
  8471. },
  8472. enumerable: true,
  8473. configurable: true
  8474. });
  8475. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8476. get: function () {
  8477. return Engine._ALPHA_ONEONE;
  8478. },
  8479. enumerable: true,
  8480. configurable: true
  8481. });
  8482. Object.defineProperty(Engine, "ALPHA_ADD", {
  8483. get: function () {
  8484. return Engine._ALPHA_ADD;
  8485. },
  8486. enumerable: true,
  8487. configurable: true
  8488. });
  8489. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8490. get: function () {
  8491. return Engine._ALPHA_COMBINE;
  8492. },
  8493. enumerable: true,
  8494. configurable: true
  8495. });
  8496. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8497. get: function () {
  8498. return Engine._ALPHA_SUBTRACT;
  8499. },
  8500. enumerable: true,
  8501. configurable: true
  8502. });
  8503. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8504. get: function () {
  8505. return Engine._ALPHA_MULTIPLY;
  8506. },
  8507. enumerable: true,
  8508. configurable: true
  8509. });
  8510. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8511. get: function () {
  8512. return Engine._ALPHA_MAXIMIZED;
  8513. },
  8514. enumerable: true,
  8515. configurable: true
  8516. });
  8517. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8518. get: function () {
  8519. return Engine._ALPHA_PREMULTIPLIED;
  8520. },
  8521. enumerable: true,
  8522. configurable: true
  8523. });
  8524. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8525. get: function () {
  8526. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8527. },
  8528. enumerable: true,
  8529. configurable: true
  8530. });
  8531. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8532. get: function () {
  8533. return Engine._ALPHA_INTERPOLATE;
  8534. },
  8535. enumerable: true,
  8536. configurable: true
  8537. });
  8538. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8539. get: function () {
  8540. return Engine._ALPHA_SCREENMODE;
  8541. },
  8542. enumerable: true,
  8543. configurable: true
  8544. });
  8545. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8546. get: function () {
  8547. return Engine._DELAYLOADSTATE_NONE;
  8548. },
  8549. enumerable: true,
  8550. configurable: true
  8551. });
  8552. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8553. get: function () {
  8554. return Engine._DELAYLOADSTATE_LOADED;
  8555. },
  8556. enumerable: true,
  8557. configurable: true
  8558. });
  8559. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8560. get: function () {
  8561. return Engine._DELAYLOADSTATE_LOADING;
  8562. },
  8563. enumerable: true,
  8564. configurable: true
  8565. });
  8566. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8567. get: function () {
  8568. return Engine._DELAYLOADSTATE_NOTLOADED;
  8569. },
  8570. enumerable: true,
  8571. configurable: true
  8572. });
  8573. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8574. get: function () {
  8575. return Engine._TEXTUREFORMAT_ALPHA;
  8576. },
  8577. enumerable: true,
  8578. configurable: true
  8579. });
  8580. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8581. get: function () {
  8582. return Engine._TEXTUREFORMAT_LUMINANCE;
  8583. },
  8584. enumerable: true,
  8585. configurable: true
  8586. });
  8587. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8588. get: function () {
  8589. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8590. },
  8591. enumerable: true,
  8592. configurable: true
  8593. });
  8594. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8595. get: function () {
  8596. return Engine._TEXTUREFORMAT_RGB;
  8597. },
  8598. enumerable: true,
  8599. configurable: true
  8600. });
  8601. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8602. get: function () {
  8603. return Engine._TEXTUREFORMAT_RGBA;
  8604. },
  8605. enumerable: true,
  8606. configurable: true
  8607. });
  8608. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8609. get: function () {
  8610. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8611. },
  8612. enumerable: true,
  8613. configurable: true
  8614. });
  8615. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8616. get: function () {
  8617. return Engine._TEXTURETYPE_FLOAT;
  8618. },
  8619. enumerable: true,
  8620. configurable: true
  8621. });
  8622. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8623. get: function () {
  8624. return Engine._TEXTURETYPE_HALF_FLOAT;
  8625. },
  8626. enumerable: true,
  8627. configurable: true
  8628. });
  8629. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8630. get: function () {
  8631. return Engine._SCALEMODE_FLOOR;
  8632. },
  8633. enumerable: true,
  8634. configurable: true
  8635. });
  8636. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8637. get: function () {
  8638. return Engine._SCALEMODE_NEAREST;
  8639. },
  8640. enumerable: true,
  8641. configurable: true
  8642. });
  8643. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8644. get: function () {
  8645. return Engine._SCALEMODE_CEILING;
  8646. },
  8647. enumerable: true,
  8648. configurable: true
  8649. });
  8650. Object.defineProperty(Engine, "Version", {
  8651. get: function () {
  8652. return "3.2.0-alpha0";
  8653. },
  8654. enumerable: true,
  8655. configurable: true
  8656. });
  8657. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  8658. get: function () {
  8659. return this._vrExclusivePointerMode;
  8660. },
  8661. enumerable: true,
  8662. configurable: true
  8663. });
  8664. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8665. get: function () {
  8666. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8667. },
  8668. enumerable: true,
  8669. configurable: true
  8670. });
  8671. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8672. get: function () {
  8673. return this._webGLVersion < 2 || this.forcePOTTextures;
  8674. },
  8675. enumerable: true,
  8676. configurable: true
  8677. });
  8678. Object.defineProperty(Engine.prototype, "badOS", {
  8679. get: function () {
  8680. return this._badOS;
  8681. },
  8682. enumerable: true,
  8683. configurable: true
  8684. });
  8685. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8686. get: function () {
  8687. return this._badDesktopOS;
  8688. },
  8689. enumerable: true,
  8690. configurable: true
  8691. });
  8692. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8693. get: function () {
  8694. return this._performanceMonitor;
  8695. },
  8696. enumerable: true,
  8697. configurable: true
  8698. });
  8699. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8700. get: function () {
  8701. return this._texturesSupported;
  8702. },
  8703. enumerable: true,
  8704. configurable: true
  8705. });
  8706. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8707. get: function () {
  8708. return this._textureFormatInUse;
  8709. },
  8710. enumerable: true,
  8711. configurable: true
  8712. });
  8713. Object.defineProperty(Engine.prototype, "currentViewport", {
  8714. get: function () {
  8715. return this._cachedViewport;
  8716. },
  8717. enumerable: true,
  8718. configurable: true
  8719. });
  8720. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8721. // Empty texture
  8722. get: function () {
  8723. if (!this._emptyTexture) {
  8724. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8725. }
  8726. return this._emptyTexture;
  8727. },
  8728. enumerable: true,
  8729. configurable: true
  8730. });
  8731. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  8732. get: function () {
  8733. if (!this._emptyTexture3D) {
  8734. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8735. }
  8736. return this._emptyTexture3D;
  8737. },
  8738. enumerable: true,
  8739. configurable: true
  8740. });
  8741. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8742. get: function () {
  8743. if (!this._emptyCubeTexture) {
  8744. var faceData = new Uint8Array(4);
  8745. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8746. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8747. }
  8748. return this._emptyCubeTexture;
  8749. },
  8750. enumerable: true,
  8751. configurable: true
  8752. });
  8753. Engine.prototype._rebuildInternalTextures = function () {
  8754. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8755. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8756. var internalTexture = currentState_1[_i];
  8757. internalTexture._rebuild();
  8758. }
  8759. };
  8760. Engine.prototype._rebuildEffects = function () {
  8761. for (var key in this._compiledEffects) {
  8762. var effect = this._compiledEffects[key];
  8763. effect._prepareEffect();
  8764. }
  8765. BABYLON.Effect.ResetCache();
  8766. };
  8767. Engine.prototype._rebuildBuffers = function () {
  8768. // Index / Vertex
  8769. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8770. var scene = _a[_i];
  8771. scene.resetCachedMaterial();
  8772. scene._rebuildGeometries();
  8773. scene._rebuildTextures();
  8774. }
  8775. // Uniforms
  8776. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8777. var uniformBuffer = _c[_b];
  8778. uniformBuffer._rebuild();
  8779. }
  8780. };
  8781. Engine.prototype._initGLContext = function () {
  8782. // Caps
  8783. this._caps = new EngineCapabilities();
  8784. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8785. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8786. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8787. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8788. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8789. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8790. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8791. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8792. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8793. // Infos
  8794. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8795. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8796. if (rendererInfo != null) {
  8797. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8798. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8799. }
  8800. if (!this._glVendor) {
  8801. this._glVendor = "Unknown vendor";
  8802. }
  8803. if (!this._glRenderer) {
  8804. this._glRenderer = "Unknown renderer";
  8805. }
  8806. // Constants
  8807. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8808. if (this._gl.RGBA16F !== 0x881A) {
  8809. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8810. }
  8811. if (this._gl.RGBA32F !== 0x8814) {
  8812. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8813. }
  8814. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  8815. this._gl.DEPTH24_STENCIL8 = 35056;
  8816. }
  8817. // Extensions
  8818. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8819. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8820. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8821. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8822. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8823. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8824. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8825. 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');
  8826. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8827. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8828. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8829. this._caps.highPrecisionShaderSupported = true;
  8830. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  8831. if (this._caps.timerQuery) {
  8832. if (this._webGLVersion === 1) {
  8833. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  8834. }
  8835. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  8836. }
  8837. // Checks if some of the format renders first to allow the use of webgl inspector.
  8838. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8839. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8840. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8841. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8842. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8843. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8844. if (this._webGLVersion > 1) {
  8845. this._gl.HALF_FLOAT_OES = 0x140B;
  8846. }
  8847. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8848. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8849. // Draw buffers
  8850. if (this._webGLVersion > 1) {
  8851. this._caps.drawBuffersExtension = true;
  8852. }
  8853. else {
  8854. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  8855. if (drawBuffersExtension !== null) {
  8856. this._caps.drawBuffersExtension = true;
  8857. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  8858. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  8859. for (var i = 0; i < 16; i++) {
  8860. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  8861. }
  8862. }
  8863. else {
  8864. this._caps.drawBuffersExtension = false;
  8865. }
  8866. }
  8867. // Depth Texture
  8868. if (this._webGLVersion > 1) {
  8869. this._caps.depthTextureExtension = true;
  8870. }
  8871. else {
  8872. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  8873. if (depthTextureExtension != null) {
  8874. this._caps.depthTextureExtension = true;
  8875. }
  8876. }
  8877. // Vertex array object
  8878. if (this._webGLVersion > 1) {
  8879. this._caps.vertexArrayObject = true;
  8880. }
  8881. else {
  8882. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8883. if (vertexArrayObjectExtension != null) {
  8884. this._caps.vertexArrayObject = true;
  8885. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8886. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8887. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8888. }
  8889. else {
  8890. this._caps.vertexArrayObject = false;
  8891. }
  8892. }
  8893. // Instances count
  8894. if (this._webGLVersion > 1) {
  8895. this._caps.instancedArrays = true;
  8896. }
  8897. else {
  8898. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8899. if (instanceExtension != null) {
  8900. this._caps.instancedArrays = true;
  8901. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8902. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8903. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8904. }
  8905. else {
  8906. this._caps.instancedArrays = false;
  8907. }
  8908. }
  8909. // Intelligently add supported compressed formats in order to check for.
  8910. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8911. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8912. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8913. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8914. if (this._caps.astc)
  8915. this.texturesSupported.push('-astc.ktx');
  8916. if (this._caps.s3tc)
  8917. this.texturesSupported.push('-dxt.ktx');
  8918. if (this._caps.pvrtc)
  8919. this.texturesSupported.push('-pvrtc.ktx');
  8920. if (this._caps.etc2)
  8921. this.texturesSupported.push('-etc2.ktx');
  8922. if (this._caps.etc1)
  8923. this.texturesSupported.push('-etc1.ktx');
  8924. if (this._gl.getShaderPrecisionFormat) {
  8925. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8926. if (highp) {
  8927. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8928. }
  8929. }
  8930. // Depth buffer
  8931. this.setDepthBuffer(true);
  8932. this.setDepthFunctionToLessOrEqual();
  8933. this.setDepthWrite(true);
  8934. };
  8935. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8936. get: function () {
  8937. return this._webGLVersion;
  8938. },
  8939. enumerable: true,
  8940. configurable: true
  8941. });
  8942. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8943. /**
  8944. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8945. */
  8946. get: function () {
  8947. return this._isStencilEnable;
  8948. },
  8949. enumerable: true,
  8950. configurable: true
  8951. });
  8952. Engine.prototype._prepareWorkingCanvas = function () {
  8953. if (this._workingCanvas) {
  8954. return;
  8955. }
  8956. this._workingCanvas = document.createElement("canvas");
  8957. var context = this._workingCanvas.getContext("2d");
  8958. if (context) {
  8959. this._workingContext = context;
  8960. }
  8961. };
  8962. Engine.prototype.resetTextureCache = function () {
  8963. for (var key in this._boundTexturesCache) {
  8964. var boundTexture = this._boundTexturesCache[key];
  8965. if (boundTexture) {
  8966. this._removeDesignatedSlot(boundTexture);
  8967. }
  8968. this._boundTexturesCache[key] = null;
  8969. }
  8970. this._nextFreeTextureSlot = 0;
  8971. this._activeChannel = -1;
  8972. };
  8973. Engine.prototype.isDeterministicLockStep = function () {
  8974. return this._deterministicLockstep;
  8975. };
  8976. Engine.prototype.getLockstepMaxSteps = function () {
  8977. return this._lockstepMaxSteps;
  8978. };
  8979. Engine.prototype.getGlInfo = function () {
  8980. return {
  8981. vendor: this._glVendor,
  8982. renderer: this._glRenderer,
  8983. version: this._glVersion
  8984. };
  8985. };
  8986. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8987. if (useScreen === void 0) { useScreen = false; }
  8988. var viewport = camera.viewport;
  8989. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8990. };
  8991. Engine.prototype.getRenderWidth = function (useScreen) {
  8992. if (useScreen === void 0) { useScreen = false; }
  8993. if (!useScreen && this._currentRenderTarget) {
  8994. return this._currentRenderTarget.width;
  8995. }
  8996. return this._gl.drawingBufferWidth;
  8997. };
  8998. Engine.prototype.getRenderHeight = function (useScreen) {
  8999. if (useScreen === void 0) { useScreen = false; }
  9000. if (!useScreen && this._currentRenderTarget) {
  9001. return this._currentRenderTarget.height;
  9002. }
  9003. return this._gl.drawingBufferHeight;
  9004. };
  9005. Engine.prototype.getRenderingCanvas = function () {
  9006. return this._renderingCanvas;
  9007. };
  9008. Engine.prototype.getRenderingCanvasClientRect = function () {
  9009. if (!this._renderingCanvas) {
  9010. return null;
  9011. }
  9012. return this._renderingCanvas.getBoundingClientRect();
  9013. };
  9014. Engine.prototype.setHardwareScalingLevel = function (level) {
  9015. this._hardwareScalingLevel = level;
  9016. this.resize();
  9017. };
  9018. Engine.prototype.getHardwareScalingLevel = function () {
  9019. return this._hardwareScalingLevel;
  9020. };
  9021. Engine.prototype.getLoadedTexturesCache = function () {
  9022. return this._internalTexturesCache;
  9023. };
  9024. Engine.prototype.getCaps = function () {
  9025. return this._caps;
  9026. };
  9027. Object.defineProperty(Engine.prototype, "drawCalls", {
  9028. /** The number of draw calls submitted last frame */
  9029. get: function () {
  9030. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  9031. return 0;
  9032. },
  9033. enumerable: true,
  9034. configurable: true
  9035. });
  9036. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  9037. get: function () {
  9038. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  9039. return null;
  9040. },
  9041. enumerable: true,
  9042. configurable: true
  9043. });
  9044. Engine.prototype.getDepthFunction = function () {
  9045. return this._depthCullingState.depthFunc;
  9046. };
  9047. Engine.prototype.setDepthFunction = function (depthFunc) {
  9048. this._depthCullingState.depthFunc = depthFunc;
  9049. };
  9050. Engine.prototype.setDepthFunctionToGreater = function () {
  9051. this._depthCullingState.depthFunc = this._gl.GREATER;
  9052. };
  9053. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  9054. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  9055. };
  9056. Engine.prototype.setDepthFunctionToLess = function () {
  9057. this._depthCullingState.depthFunc = this._gl.LESS;
  9058. };
  9059. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  9060. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  9061. };
  9062. Engine.prototype.getStencilBuffer = function () {
  9063. return this._stencilState.stencilTest;
  9064. };
  9065. Engine.prototype.setStencilBuffer = function (enable) {
  9066. this._stencilState.stencilTest = enable;
  9067. };
  9068. Engine.prototype.getStencilMask = function () {
  9069. return this._stencilState.stencilMask;
  9070. };
  9071. Engine.prototype.setStencilMask = function (mask) {
  9072. this._stencilState.stencilMask = mask;
  9073. };
  9074. Engine.prototype.getStencilFunction = function () {
  9075. return this._stencilState.stencilFunc;
  9076. };
  9077. Engine.prototype.getStencilFunctionReference = function () {
  9078. return this._stencilState.stencilFuncRef;
  9079. };
  9080. Engine.prototype.getStencilFunctionMask = function () {
  9081. return this._stencilState.stencilFuncMask;
  9082. };
  9083. Engine.prototype.setStencilFunction = function (stencilFunc) {
  9084. this._stencilState.stencilFunc = stencilFunc;
  9085. };
  9086. Engine.prototype.setStencilFunctionReference = function (reference) {
  9087. this._stencilState.stencilFuncRef = reference;
  9088. };
  9089. Engine.prototype.setStencilFunctionMask = function (mask) {
  9090. this._stencilState.stencilFuncMask = mask;
  9091. };
  9092. Engine.prototype.getStencilOperationFail = function () {
  9093. return this._stencilState.stencilOpStencilFail;
  9094. };
  9095. Engine.prototype.getStencilOperationDepthFail = function () {
  9096. return this._stencilState.stencilOpDepthFail;
  9097. };
  9098. Engine.prototype.getStencilOperationPass = function () {
  9099. return this._stencilState.stencilOpStencilDepthPass;
  9100. };
  9101. Engine.prototype.setStencilOperationFail = function (operation) {
  9102. this._stencilState.stencilOpStencilFail = operation;
  9103. };
  9104. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  9105. this._stencilState.stencilOpDepthFail = operation;
  9106. };
  9107. Engine.prototype.setStencilOperationPass = function (operation) {
  9108. this._stencilState.stencilOpStencilDepthPass = operation;
  9109. };
  9110. Engine.prototype.setDitheringState = function (value) {
  9111. if (value) {
  9112. this._gl.enable(this._gl.DITHER);
  9113. }
  9114. else {
  9115. this._gl.disable(this._gl.DITHER);
  9116. }
  9117. };
  9118. Engine.prototype.setRasterizerState = function (value) {
  9119. if (value) {
  9120. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  9121. }
  9122. else {
  9123. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  9124. }
  9125. };
  9126. /**
  9127. * stop executing a render loop function and remove it from the execution array
  9128. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  9129. */
  9130. Engine.prototype.stopRenderLoop = function (renderFunction) {
  9131. if (!renderFunction) {
  9132. this._activeRenderLoops = [];
  9133. return;
  9134. }
  9135. var index = this._activeRenderLoops.indexOf(renderFunction);
  9136. if (index >= 0) {
  9137. this._activeRenderLoops.splice(index, 1);
  9138. }
  9139. };
  9140. Engine.prototype._renderLoop = function () {
  9141. if (!this._contextWasLost) {
  9142. var shouldRender = true;
  9143. if (!this.renderEvenInBackground && this._windowIsBackground) {
  9144. shouldRender = false;
  9145. }
  9146. if (shouldRender) {
  9147. // Start new frame
  9148. this.beginFrame();
  9149. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  9150. var renderFunction = this._activeRenderLoops[index];
  9151. renderFunction();
  9152. }
  9153. // Present
  9154. this.endFrame();
  9155. }
  9156. }
  9157. if (this._activeRenderLoops.length > 0) {
  9158. // Register new frame
  9159. var requester = null;
  9160. if (this._vrDisplay && this._vrDisplay.isPresenting)
  9161. requester = this._vrDisplay;
  9162. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  9163. }
  9164. else {
  9165. this._renderingQueueLaunched = false;
  9166. }
  9167. };
  9168. /**
  9169. * Register and execute a render loop. The engine can have more than one render function.
  9170. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  9171. * @example
  9172. * engine.runRenderLoop(function () {
  9173. * scene.render()
  9174. * })
  9175. */
  9176. Engine.prototype.runRenderLoop = function (renderFunction) {
  9177. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  9178. return;
  9179. }
  9180. this._activeRenderLoops.push(renderFunction);
  9181. if (!this._renderingQueueLaunched) {
  9182. this._renderingQueueLaunched = true;
  9183. this._bindedRenderFunction = this._renderLoop.bind(this);
  9184. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  9185. }
  9186. };
  9187. /**
  9188. * Toggle full screen mode.
  9189. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  9190. * @param {any} options - an options object to be sent to the requestFullscreen function
  9191. */
  9192. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  9193. if (this.isFullscreen) {
  9194. BABYLON.Tools.ExitFullscreen();
  9195. }
  9196. else {
  9197. this._pointerLockRequested = requestPointerLock;
  9198. if (this._renderingCanvas) {
  9199. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  9200. }
  9201. }
  9202. };
  9203. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  9204. if (stencil === void 0) { stencil = false; }
  9205. this.applyStates();
  9206. var mode = 0;
  9207. if (backBuffer && color) {
  9208. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  9209. mode |= this._gl.COLOR_BUFFER_BIT;
  9210. }
  9211. if (depth) {
  9212. this._gl.clearDepth(1.0);
  9213. mode |= this._gl.DEPTH_BUFFER_BIT;
  9214. }
  9215. if (stencil) {
  9216. this._gl.clearStencil(0);
  9217. mode |= this._gl.STENCIL_BUFFER_BIT;
  9218. }
  9219. this._gl.clear(mode);
  9220. };
  9221. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  9222. var gl = this._gl;
  9223. // Save state
  9224. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  9225. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  9226. // Change state
  9227. gl.enable(gl.SCISSOR_TEST);
  9228. gl.scissor(x, y, width, height);
  9229. // Clear
  9230. this.clear(clearColor, true, true, true);
  9231. // Restore state
  9232. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  9233. if (curScissor === true) {
  9234. gl.enable(gl.SCISSOR_TEST);
  9235. }
  9236. else {
  9237. gl.disable(gl.SCISSOR_TEST);
  9238. }
  9239. };
  9240. /**
  9241. * Set the WebGL's viewport
  9242. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  9243. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  9244. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  9245. */
  9246. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  9247. var width = requiredWidth || this.getRenderWidth();
  9248. var height = requiredHeight || this.getRenderHeight();
  9249. var x = viewport.x || 0;
  9250. var y = viewport.y || 0;
  9251. this._cachedViewport = viewport;
  9252. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  9253. };
  9254. /**
  9255. * Directly set the WebGL Viewport
  9256. * The x, y, width & height are directly passed to the WebGL call
  9257. * @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.
  9258. */
  9259. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  9260. var currentViewport = this._cachedViewport;
  9261. this._cachedViewport = null;
  9262. this._gl.viewport(x, y, width, height);
  9263. return currentViewport;
  9264. };
  9265. Engine.prototype.beginFrame = function () {
  9266. this.onBeginFrameObservable.notifyObservers(this);
  9267. this._measureFps();
  9268. };
  9269. Engine.prototype.endFrame = function () {
  9270. //force a flush in case we are using a bad OS.
  9271. if (this._badOS) {
  9272. this.flushFramebuffer();
  9273. }
  9274. //submit frame to the vr device, if enabled
  9275. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9276. // TODO: We should only submit the frame if we read frameData successfully.
  9277. this._vrDisplay.submitFrame();
  9278. }
  9279. this.onEndFrameObservable.notifyObservers(this);
  9280. };
  9281. /**
  9282. * resize the view according to the canvas' size.
  9283. * @example
  9284. * window.addEventListener("resize", function () {
  9285. * engine.resize();
  9286. * });
  9287. */
  9288. Engine.prototype.resize = function () {
  9289. // We're not resizing the size of the canvas while in VR mode & presenting
  9290. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  9291. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  9292. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  9293. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  9294. }
  9295. };
  9296. /**
  9297. * force a specific size of the canvas
  9298. * @param {number} width - the new canvas' width
  9299. * @param {number} height - the new canvas' height
  9300. */
  9301. Engine.prototype.setSize = function (width, height) {
  9302. if (!this._renderingCanvas) {
  9303. return;
  9304. }
  9305. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  9306. return;
  9307. }
  9308. this._renderingCanvas.width = width;
  9309. this._renderingCanvas.height = height;
  9310. for (var index = 0; index < this.scenes.length; index++) {
  9311. var scene = this.scenes[index];
  9312. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  9313. var cam = scene.cameras[camIndex];
  9314. cam._currentRenderId = 0;
  9315. }
  9316. }
  9317. if (this.onResizeObservable.hasObservers) {
  9318. this.onResizeObservable.notifyObservers(this);
  9319. }
  9320. };
  9321. // WebVR functions
  9322. Engine.prototype.isVRDevicePresent = function () {
  9323. return !!this._vrDisplay;
  9324. };
  9325. Engine.prototype.getVRDevice = function () {
  9326. return this._vrDisplay;
  9327. };
  9328. Engine.prototype.initWebVR = function () {
  9329. var _this = this;
  9330. var notifyObservers = function () {
  9331. var eventArgs = {
  9332. vrDisplay: _this._vrDisplay,
  9333. vrSupported: _this._vrSupported
  9334. };
  9335. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  9336. };
  9337. if (!this._onVrDisplayConnect) {
  9338. this._onVrDisplayConnect = function (event) {
  9339. _this._vrDisplay = event.display;
  9340. notifyObservers();
  9341. };
  9342. this._onVrDisplayDisconnect = function () {
  9343. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  9344. _this._vrDisplay = undefined;
  9345. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  9346. notifyObservers();
  9347. };
  9348. this._onVrDisplayPresentChange = function () {
  9349. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  9350. };
  9351. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  9352. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  9353. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  9354. }
  9355. this._getVRDisplays(notifyObservers);
  9356. return this.onVRDisplayChangedObservable;
  9357. };
  9358. Engine.prototype.enableVR = function () {
  9359. var _this = this;
  9360. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  9361. var onResolved = function () {
  9362. _this.onVRRequestPresentComplete.notifyObservers(true);
  9363. _this._onVRFullScreenTriggered();
  9364. };
  9365. var onRejected = function () {
  9366. _this.onVRRequestPresentComplete.notifyObservers(false);
  9367. };
  9368. this.onVRRequestPresentStart.notifyObservers(this);
  9369. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  9370. }
  9371. };
  9372. Engine.prototype.disableVR = function () {
  9373. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9374. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  9375. }
  9376. };
  9377. Engine.prototype._getVRDisplays = function (callback) {
  9378. var _this = this;
  9379. var getWebVRDevices = function (devices) {
  9380. _this._vrSupported = true;
  9381. // note that devices may actually be an empty array. This is fine;
  9382. // we expect this._vrDisplay to be undefined in this case.
  9383. return _this._vrDisplay = devices[0];
  9384. };
  9385. if (navigator.getVRDisplays) {
  9386. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  9387. // TODO: System CANNOT support WebVR, despite API presence.
  9388. _this._vrSupported = false;
  9389. callback();
  9390. });
  9391. }
  9392. else {
  9393. // TODO: Browser does not support WebVR
  9394. this._vrDisplay = undefined;
  9395. this._vrSupported = false;
  9396. callback();
  9397. }
  9398. };
  9399. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  9400. if (this._currentRenderTarget) {
  9401. this.unBindFramebuffer(this._currentRenderTarget);
  9402. }
  9403. this._currentRenderTarget = texture;
  9404. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  9405. var gl = this._gl;
  9406. if (texture.isCube) {
  9407. if (faceIndex === undefined) {
  9408. faceIndex = 0;
  9409. }
  9410. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  9411. }
  9412. if (this._cachedViewport && !forceFullscreenViewport) {
  9413. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  9414. }
  9415. else {
  9416. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  9417. }
  9418. this.wipeCaches();
  9419. };
  9420. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  9421. if (this._currentFramebuffer !== framebuffer) {
  9422. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  9423. this._currentFramebuffer = framebuffer;
  9424. }
  9425. };
  9426. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  9427. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  9428. this._currentRenderTarget = null;
  9429. // If MSAA, we need to bitblt back to main texture
  9430. var gl = this._gl;
  9431. if (texture._MSAAFramebuffer) {
  9432. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  9433. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  9434. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  9435. }
  9436. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  9437. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9438. gl.generateMipmap(gl.TEXTURE_2D);
  9439. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9440. }
  9441. if (onBeforeUnbind) {
  9442. if (texture._MSAAFramebuffer) {
  9443. // Bind the correct framebuffer
  9444. this.bindUnboundFramebuffer(texture._framebuffer);
  9445. }
  9446. onBeforeUnbind();
  9447. }
  9448. this.bindUnboundFramebuffer(null);
  9449. };
  9450. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  9451. if (texture.generateMipMaps) {
  9452. var gl = this._gl;
  9453. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9454. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9455. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9456. }
  9457. };
  9458. Engine.prototype.flushFramebuffer = function () {
  9459. this._gl.flush();
  9460. };
  9461. Engine.prototype.restoreDefaultFramebuffer = function () {
  9462. if (this._currentRenderTarget) {
  9463. this.unBindFramebuffer(this._currentRenderTarget);
  9464. }
  9465. else {
  9466. this.bindUnboundFramebuffer(null);
  9467. }
  9468. if (this._cachedViewport) {
  9469. this.setViewport(this._cachedViewport);
  9470. }
  9471. this.wipeCaches();
  9472. };
  9473. // UBOs
  9474. Engine.prototype.createUniformBuffer = function (elements) {
  9475. var ubo = this._gl.createBuffer();
  9476. if (!ubo) {
  9477. throw new Error("Unable to create uniform buffer");
  9478. }
  9479. this.bindUniformBuffer(ubo);
  9480. if (elements instanceof Float32Array) {
  9481. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  9482. }
  9483. else {
  9484. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  9485. }
  9486. this.bindUniformBuffer(null);
  9487. ubo.references = 1;
  9488. return ubo;
  9489. };
  9490. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  9491. var ubo = this._gl.createBuffer();
  9492. if (!ubo) {
  9493. throw new Error("Unable to create dynamic uniform buffer");
  9494. }
  9495. this.bindUniformBuffer(ubo);
  9496. if (elements instanceof Float32Array) {
  9497. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  9498. }
  9499. else {
  9500. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  9501. }
  9502. this.bindUniformBuffer(null);
  9503. ubo.references = 1;
  9504. return ubo;
  9505. };
  9506. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  9507. this.bindUniformBuffer(uniformBuffer);
  9508. if (offset === undefined) {
  9509. offset = 0;
  9510. }
  9511. if (count === undefined) {
  9512. if (elements instanceof Float32Array) {
  9513. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  9514. }
  9515. else {
  9516. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  9517. }
  9518. }
  9519. else {
  9520. if (elements instanceof Float32Array) {
  9521. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  9522. }
  9523. else {
  9524. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  9525. }
  9526. }
  9527. this.bindUniformBuffer(null);
  9528. };
  9529. // VBOs
  9530. Engine.prototype._resetVertexBufferBinding = function () {
  9531. this.bindArrayBuffer(null);
  9532. this._cachedVertexBuffers = null;
  9533. };
  9534. Engine.prototype.createVertexBuffer = function (vertices) {
  9535. var vbo = this._gl.createBuffer();
  9536. if (!vbo) {
  9537. throw new Error("Unable to create vertex buffer");
  9538. }
  9539. this.bindArrayBuffer(vbo);
  9540. if (vertices instanceof Float32Array) {
  9541. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  9542. }
  9543. else {
  9544. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  9545. }
  9546. this._resetVertexBufferBinding();
  9547. vbo.references = 1;
  9548. return vbo;
  9549. };
  9550. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  9551. var vbo = this._gl.createBuffer();
  9552. if (!vbo) {
  9553. throw new Error("Unable to create dynamic vertex buffer");
  9554. }
  9555. this.bindArrayBuffer(vbo);
  9556. if (vertices instanceof Float32Array) {
  9557. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  9558. }
  9559. else {
  9560. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  9561. }
  9562. this._resetVertexBufferBinding();
  9563. vbo.references = 1;
  9564. return vbo;
  9565. };
  9566. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  9567. if (offset === void 0) { offset = 0; }
  9568. // Force cache update
  9569. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  9570. this.bindIndexBuffer(indexBuffer);
  9571. var arrayBuffer;
  9572. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  9573. arrayBuffer = indices;
  9574. }
  9575. else {
  9576. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9577. }
  9578. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  9579. this._resetIndexBufferBinding();
  9580. };
  9581. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  9582. this.bindArrayBuffer(vertexBuffer);
  9583. if (offset === undefined) {
  9584. offset = 0;
  9585. }
  9586. if (count === undefined) {
  9587. if (vertices instanceof Float32Array) {
  9588. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  9589. }
  9590. else {
  9591. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  9592. }
  9593. }
  9594. else {
  9595. if (vertices instanceof Float32Array) {
  9596. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  9597. }
  9598. else {
  9599. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  9600. }
  9601. }
  9602. this._resetVertexBufferBinding();
  9603. };
  9604. Engine.prototype._resetIndexBufferBinding = function () {
  9605. this.bindIndexBuffer(null);
  9606. this._cachedIndexBuffer = null;
  9607. };
  9608. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  9609. var vbo = this._gl.createBuffer();
  9610. if (!vbo) {
  9611. throw new Error("Unable to create index buffer");
  9612. }
  9613. this.bindIndexBuffer(vbo);
  9614. // Check for 32 bits indices
  9615. var arrayBuffer;
  9616. var need32Bits = false;
  9617. if (indices instanceof Uint16Array) {
  9618. arrayBuffer = indices;
  9619. }
  9620. else {
  9621. //check 32 bit support
  9622. if (this._caps.uintIndices) {
  9623. if (indices instanceof Uint32Array) {
  9624. arrayBuffer = indices;
  9625. need32Bits = true;
  9626. }
  9627. else {
  9628. //number[] or Int32Array, check if 32 bit is necessary
  9629. for (var index = 0; index < indices.length; index++) {
  9630. if (indices[index] > 65535) {
  9631. need32Bits = true;
  9632. break;
  9633. }
  9634. }
  9635. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9636. }
  9637. }
  9638. else {
  9639. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9640. arrayBuffer = new Uint16Array(indices);
  9641. }
  9642. }
  9643. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  9644. this._resetIndexBufferBinding();
  9645. vbo.references = 1;
  9646. vbo.is32Bits = need32Bits;
  9647. return vbo;
  9648. };
  9649. Engine.prototype.bindArrayBuffer = function (buffer) {
  9650. if (!this._vaoRecordInProgress) {
  9651. this._unbindVertexArrayObject();
  9652. }
  9653. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9654. };
  9655. Engine.prototype.bindUniformBuffer = function (buffer) {
  9656. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9657. };
  9658. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9659. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9660. };
  9661. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9662. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9663. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9664. };
  9665. ;
  9666. Engine.prototype.bindIndexBuffer = function (buffer) {
  9667. if (!this._vaoRecordInProgress) {
  9668. this._unbindVertexArrayObject();
  9669. }
  9670. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9671. };
  9672. Engine.prototype.bindBuffer = function (buffer, target) {
  9673. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9674. this._gl.bindBuffer(target, buffer);
  9675. this._currentBoundBuffer[target] = buffer;
  9676. }
  9677. };
  9678. Engine.prototype.updateArrayBuffer = function (data) {
  9679. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9680. };
  9681. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9682. var pointer = this._currentBufferPointers[indx];
  9683. var changed = false;
  9684. if (!pointer.active) {
  9685. changed = true;
  9686. pointer.active = true;
  9687. pointer.index = indx;
  9688. pointer.size = size;
  9689. pointer.type = type;
  9690. pointer.normalized = normalized;
  9691. pointer.stride = stride;
  9692. pointer.offset = offset;
  9693. pointer.buffer = buffer;
  9694. }
  9695. else {
  9696. if (pointer.buffer !== buffer) {
  9697. pointer.buffer = buffer;
  9698. changed = true;
  9699. }
  9700. if (pointer.size !== size) {
  9701. pointer.size = size;
  9702. changed = true;
  9703. }
  9704. if (pointer.type !== type) {
  9705. pointer.type = type;
  9706. changed = true;
  9707. }
  9708. if (pointer.normalized !== normalized) {
  9709. pointer.normalized = normalized;
  9710. changed = true;
  9711. }
  9712. if (pointer.stride !== stride) {
  9713. pointer.stride = stride;
  9714. changed = true;
  9715. }
  9716. if (pointer.offset !== offset) {
  9717. pointer.offset = offset;
  9718. changed = true;
  9719. }
  9720. }
  9721. if (changed || this._vaoRecordInProgress) {
  9722. this.bindArrayBuffer(buffer);
  9723. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9724. }
  9725. };
  9726. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9727. if (indexBuffer == null) {
  9728. return;
  9729. }
  9730. if (this._cachedIndexBuffer !== indexBuffer) {
  9731. this._cachedIndexBuffer = indexBuffer;
  9732. this.bindIndexBuffer(indexBuffer);
  9733. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9734. }
  9735. };
  9736. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9737. var attributes = effect.getAttributesNames();
  9738. if (!this._vaoRecordInProgress) {
  9739. this._unbindVertexArrayObject();
  9740. }
  9741. this.unbindAllAttributes();
  9742. for (var index = 0; index < attributes.length; index++) {
  9743. var order = effect.getAttributeLocation(index);
  9744. if (order >= 0) {
  9745. var vertexBuffer = vertexBuffers[attributes[index]];
  9746. if (!vertexBuffer) {
  9747. continue;
  9748. }
  9749. this._gl.enableVertexAttribArray(order);
  9750. if (!this._vaoRecordInProgress) {
  9751. this._vertexAttribArraysEnabled[order] = true;
  9752. }
  9753. var buffer = vertexBuffer.getBuffer();
  9754. if (buffer) {
  9755. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9756. if (vertexBuffer.getIsInstanced()) {
  9757. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9758. if (!this._vaoRecordInProgress) {
  9759. this._currentInstanceLocations.push(order);
  9760. this._currentInstanceBuffers.push(buffer);
  9761. }
  9762. }
  9763. }
  9764. }
  9765. }
  9766. };
  9767. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9768. var vao = this._gl.createVertexArray();
  9769. this._vaoRecordInProgress = true;
  9770. this._gl.bindVertexArray(vao);
  9771. this._mustWipeVertexAttributes = true;
  9772. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9773. this.bindIndexBuffer(indexBuffer);
  9774. this._vaoRecordInProgress = false;
  9775. this._gl.bindVertexArray(null);
  9776. return vao;
  9777. };
  9778. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9779. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9780. this._cachedVertexArrayObject = vertexArrayObject;
  9781. this._gl.bindVertexArray(vertexArrayObject);
  9782. this._cachedVertexBuffers = null;
  9783. this._cachedIndexBuffer = null;
  9784. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9785. this._mustWipeVertexAttributes = true;
  9786. }
  9787. };
  9788. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9789. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9790. this._cachedVertexBuffers = vertexBuffer;
  9791. this._cachedEffectForVertexBuffers = effect;
  9792. var attributesCount = effect.getAttributesCount();
  9793. this._unbindVertexArrayObject();
  9794. this.unbindAllAttributes();
  9795. var offset = 0;
  9796. for (var index = 0; index < attributesCount; index++) {
  9797. if (index < vertexDeclaration.length) {
  9798. var order = effect.getAttributeLocation(index);
  9799. if (order >= 0) {
  9800. this._gl.enableVertexAttribArray(order);
  9801. this._vertexAttribArraysEnabled[order] = true;
  9802. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9803. }
  9804. offset += vertexDeclaration[index] * 4;
  9805. }
  9806. }
  9807. }
  9808. this._bindIndexBufferWithCache(indexBuffer);
  9809. };
  9810. Engine.prototype._unbindVertexArrayObject = function () {
  9811. if (!this._cachedVertexArrayObject) {
  9812. return;
  9813. }
  9814. this._cachedVertexArrayObject = null;
  9815. this._gl.bindVertexArray(null);
  9816. };
  9817. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9818. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9819. this._cachedVertexBuffers = vertexBuffers;
  9820. this._cachedEffectForVertexBuffers = effect;
  9821. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9822. }
  9823. this._bindIndexBufferWithCache(indexBuffer);
  9824. };
  9825. Engine.prototype.unbindInstanceAttributes = function () {
  9826. var boundBuffer;
  9827. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9828. var instancesBuffer = this._currentInstanceBuffers[i];
  9829. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9830. boundBuffer = instancesBuffer;
  9831. this.bindArrayBuffer(instancesBuffer);
  9832. }
  9833. var offsetLocation = this._currentInstanceLocations[i];
  9834. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9835. }
  9836. this._currentInstanceBuffers.length = 0;
  9837. this._currentInstanceLocations.length = 0;
  9838. };
  9839. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9840. this._gl.deleteVertexArray(vao);
  9841. };
  9842. Engine.prototype._releaseBuffer = function (buffer) {
  9843. buffer.references--;
  9844. if (buffer.references === 0) {
  9845. this._gl.deleteBuffer(buffer);
  9846. return true;
  9847. }
  9848. return false;
  9849. };
  9850. Engine.prototype.createInstancesBuffer = function (capacity) {
  9851. var buffer = this._gl.createBuffer();
  9852. if (!buffer) {
  9853. throw new Error("Unable to create instance buffer");
  9854. }
  9855. buffer.capacity = capacity;
  9856. this.bindArrayBuffer(buffer);
  9857. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9858. return buffer;
  9859. };
  9860. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9861. this._gl.deleteBuffer(buffer);
  9862. };
  9863. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9864. this.bindArrayBuffer(instancesBuffer);
  9865. if (data) {
  9866. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9867. }
  9868. if (offsetLocations[0].index !== undefined) {
  9869. var stride = 0;
  9870. for (var i = 0; i < offsetLocations.length; i++) {
  9871. var ai = offsetLocations[i];
  9872. stride += ai.attributeSize * 4;
  9873. }
  9874. for (var i = 0; i < offsetLocations.length; i++) {
  9875. var ai = offsetLocations[i];
  9876. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9877. this._gl.enableVertexAttribArray(ai.index);
  9878. this._vertexAttribArraysEnabled[ai.index] = true;
  9879. }
  9880. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9881. this._gl.vertexAttribDivisor(ai.index, 1);
  9882. this._currentInstanceLocations.push(ai.index);
  9883. this._currentInstanceBuffers.push(instancesBuffer);
  9884. }
  9885. }
  9886. else {
  9887. for (var index = 0; index < 4; index++) {
  9888. var offsetLocation = offsetLocations[index];
  9889. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9890. this._gl.enableVertexAttribArray(offsetLocation);
  9891. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9892. }
  9893. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9894. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9895. this._currentInstanceLocations.push(offsetLocation);
  9896. this._currentInstanceBuffers.push(instancesBuffer);
  9897. }
  9898. }
  9899. };
  9900. Engine.prototype.applyStates = function () {
  9901. this._depthCullingState.apply(this._gl);
  9902. this._stencilState.apply(this._gl);
  9903. this._alphaState.apply(this._gl);
  9904. };
  9905. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9906. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  9907. };
  9908. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9909. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  9910. };
  9911. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9912. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  9913. };
  9914. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  9915. // Apply states
  9916. this.applyStates();
  9917. this._drawCalls.addCount(1, false);
  9918. // Render
  9919. var drawMode = this.DrawMode(fillMode);
  9920. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9921. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9922. if (instancesCount) {
  9923. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  9924. }
  9925. else {
  9926. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  9927. }
  9928. };
  9929. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  9930. // Apply states
  9931. this.applyStates();
  9932. this._drawCalls.addCount(1, false);
  9933. var drawMode = this.DrawMode(fillMode);
  9934. if (instancesCount) {
  9935. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  9936. }
  9937. else {
  9938. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  9939. }
  9940. };
  9941. Engine.prototype.DrawMode = function (fillMode) {
  9942. switch (fillMode) {
  9943. // Triangle views
  9944. case BABYLON.Material.TriangleFillMode:
  9945. return this._gl.TRIANGLES;
  9946. case BABYLON.Material.PointFillMode:
  9947. return this._gl.POINTS;
  9948. case BABYLON.Material.WireFrameFillMode:
  9949. return this._gl.LINES;
  9950. // Draw modes
  9951. case BABYLON.Material.PointListDrawMode:
  9952. return this._gl.POINTS;
  9953. case BABYLON.Material.LineListDrawMode:
  9954. return this._gl.LINES;
  9955. case BABYLON.Material.LineLoopDrawMode:
  9956. return this._gl.LINE_LOOP;
  9957. case BABYLON.Material.LineStripDrawMode:
  9958. return this._gl.LINE_STRIP;
  9959. case BABYLON.Material.TriangleStripDrawMode:
  9960. return this._gl.TRIANGLE_STRIP;
  9961. case BABYLON.Material.TriangleFanDrawMode:
  9962. return this._gl.TRIANGLE_FAN;
  9963. default:
  9964. return this._gl.TRIANGLES;
  9965. }
  9966. };
  9967. // Shaders
  9968. Engine.prototype._releaseEffect = function (effect) {
  9969. if (this._compiledEffects[effect._key]) {
  9970. delete this._compiledEffects[effect._key];
  9971. this._deleteProgram(effect.getProgram());
  9972. }
  9973. };
  9974. Engine.prototype._deleteProgram = function (program) {
  9975. if (program) {
  9976. program.__SPECTOR_rebuildProgram = null;
  9977. if (program.transformFeedback) {
  9978. this.deleteTransformFeedback(program.transformFeedback);
  9979. program.transformFeedback = null;
  9980. }
  9981. this._gl.deleteProgram(program);
  9982. }
  9983. };
  9984. /**
  9985. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9986. * @param samplers An array of string used to represent textures
  9987. */
  9988. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9989. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9990. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9991. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9992. if (this._compiledEffects[name]) {
  9993. var compiledEffect = this._compiledEffects[name];
  9994. if (onCompiled && compiledEffect.isReady()) {
  9995. onCompiled(compiledEffect);
  9996. }
  9997. return compiledEffect;
  9998. }
  9999. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  10000. effect._key = name;
  10001. this._compiledEffects[name] = effect;
  10002. return effect;
  10003. };
  10004. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  10005. if (uniformsNames === void 0) { uniformsNames = []; }
  10006. if (samplers === void 0) { samplers = []; }
  10007. if (defines === void 0) { defines = ""; }
  10008. return this.createEffect({
  10009. vertex: "particles",
  10010. fragmentElement: fragmentName
  10011. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  10012. };
  10013. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  10014. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10015. context = context || this._gl;
  10016. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  10017. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  10018. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  10019. };
  10020. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  10021. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10022. context = context || this._gl;
  10023. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  10024. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  10025. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  10026. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  10027. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  10028. this.onAfterShaderCompilationObservable.notifyObservers(this);
  10029. return program;
  10030. };
  10031. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  10032. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10033. var shaderProgram = context.createProgram();
  10034. if (!shaderProgram) {
  10035. throw new Error("Unable to create program");
  10036. }
  10037. context.attachShader(shaderProgram, vertexShader);
  10038. context.attachShader(shaderProgram, fragmentShader);
  10039. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  10040. var transformFeedback = this.createTransformFeedback();
  10041. this.bindTransformFeedback(transformFeedback);
  10042. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  10043. shaderProgram.transformFeedback = transformFeedback;
  10044. }
  10045. context.linkProgram(shaderProgram);
  10046. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  10047. this.bindTransformFeedback(null);
  10048. }
  10049. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  10050. if (!linked) {
  10051. context.validateProgram(shaderProgram);
  10052. var error = context.getProgramInfoLog(shaderProgram);
  10053. if (error) {
  10054. throw new Error(error);
  10055. }
  10056. }
  10057. context.deleteShader(vertexShader);
  10058. context.deleteShader(fragmentShader);
  10059. return shaderProgram;
  10060. };
  10061. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  10062. var results = new Array();
  10063. for (var index = 0; index < uniformsNames.length; index++) {
  10064. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  10065. }
  10066. return results;
  10067. };
  10068. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  10069. var results = [];
  10070. for (var index = 0; index < attributesNames.length; index++) {
  10071. try {
  10072. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  10073. }
  10074. catch (e) {
  10075. results.push(-1);
  10076. }
  10077. }
  10078. return results;
  10079. };
  10080. Engine.prototype.enableEffect = function (effect) {
  10081. if (!effect) {
  10082. return;
  10083. }
  10084. // Use program
  10085. this.bindSamplers(effect);
  10086. this._currentEffect = effect;
  10087. if (effect.onBind) {
  10088. effect.onBind(effect);
  10089. }
  10090. effect.onBindObservable.notifyObservers(effect);
  10091. };
  10092. Engine.prototype.setIntArray = function (uniform, array) {
  10093. if (!uniform)
  10094. return;
  10095. this._gl.uniform1iv(uniform, array);
  10096. };
  10097. Engine.prototype.setIntArray2 = function (uniform, array) {
  10098. if (!uniform || array.length % 2 !== 0)
  10099. return;
  10100. this._gl.uniform2iv(uniform, array);
  10101. };
  10102. Engine.prototype.setIntArray3 = function (uniform, array) {
  10103. if (!uniform || array.length % 3 !== 0)
  10104. return;
  10105. this._gl.uniform3iv(uniform, array);
  10106. };
  10107. Engine.prototype.setIntArray4 = function (uniform, array) {
  10108. if (!uniform || array.length % 4 !== 0)
  10109. return;
  10110. this._gl.uniform4iv(uniform, array);
  10111. };
  10112. Engine.prototype.setFloatArray = function (uniform, array) {
  10113. if (!uniform)
  10114. return;
  10115. this._gl.uniform1fv(uniform, array);
  10116. };
  10117. Engine.prototype.setFloatArray2 = function (uniform, array) {
  10118. if (!uniform || array.length % 2 !== 0)
  10119. return;
  10120. this._gl.uniform2fv(uniform, array);
  10121. };
  10122. Engine.prototype.setFloatArray3 = function (uniform, array) {
  10123. if (!uniform || array.length % 3 !== 0)
  10124. return;
  10125. this._gl.uniform3fv(uniform, array);
  10126. };
  10127. Engine.prototype.setFloatArray4 = function (uniform, array) {
  10128. if (!uniform || array.length % 4 !== 0)
  10129. return;
  10130. this._gl.uniform4fv(uniform, array);
  10131. };
  10132. Engine.prototype.setArray = function (uniform, array) {
  10133. if (!uniform)
  10134. return;
  10135. this._gl.uniform1fv(uniform, array);
  10136. };
  10137. Engine.prototype.setArray2 = function (uniform, array) {
  10138. if (!uniform || array.length % 2 !== 0)
  10139. return;
  10140. this._gl.uniform2fv(uniform, array);
  10141. };
  10142. Engine.prototype.setArray3 = function (uniform, array) {
  10143. if (!uniform || array.length % 3 !== 0)
  10144. return;
  10145. this._gl.uniform3fv(uniform, array);
  10146. };
  10147. Engine.prototype.setArray4 = function (uniform, array) {
  10148. if (!uniform || array.length % 4 !== 0)
  10149. return;
  10150. this._gl.uniform4fv(uniform, array);
  10151. };
  10152. Engine.prototype.setMatrices = function (uniform, matrices) {
  10153. if (!uniform)
  10154. return;
  10155. this._gl.uniformMatrix4fv(uniform, false, matrices);
  10156. };
  10157. Engine.prototype.setMatrix = function (uniform, matrix) {
  10158. if (!uniform)
  10159. return;
  10160. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  10161. };
  10162. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  10163. if (!uniform)
  10164. return;
  10165. this._gl.uniformMatrix3fv(uniform, false, matrix);
  10166. };
  10167. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  10168. if (!uniform)
  10169. return;
  10170. this._gl.uniformMatrix2fv(uniform, false, matrix);
  10171. };
  10172. Engine.prototype.setFloat = function (uniform, value) {
  10173. if (!uniform)
  10174. return;
  10175. this._gl.uniform1f(uniform, value);
  10176. };
  10177. Engine.prototype.setFloat2 = function (uniform, x, y) {
  10178. if (!uniform)
  10179. return;
  10180. this._gl.uniform2f(uniform, x, y);
  10181. };
  10182. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  10183. if (!uniform)
  10184. return;
  10185. this._gl.uniform3f(uniform, x, y, z);
  10186. };
  10187. Engine.prototype.setBool = function (uniform, bool) {
  10188. if (!uniform)
  10189. return;
  10190. this._gl.uniform1i(uniform, bool);
  10191. };
  10192. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  10193. if (!uniform)
  10194. return;
  10195. this._gl.uniform4f(uniform, x, y, z, w);
  10196. };
  10197. Engine.prototype.setColor3 = function (uniform, color3) {
  10198. if (!uniform)
  10199. return;
  10200. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  10201. };
  10202. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  10203. if (!uniform)
  10204. return;
  10205. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  10206. };
  10207. // States
  10208. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  10209. if (zOffset === void 0) { zOffset = 0; }
  10210. if (reverseSide === void 0) { reverseSide = false; }
  10211. // Culling
  10212. if (this._depthCullingState.cull !== culling || force) {
  10213. this._depthCullingState.cull = culling;
  10214. }
  10215. // Cull face
  10216. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  10217. if (this._depthCullingState.cullFace !== cullFace || force) {
  10218. this._depthCullingState.cullFace = cullFace;
  10219. }
  10220. // Z offset
  10221. this.setZOffset(zOffset);
  10222. // Front face
  10223. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  10224. if (this._depthCullingState.frontFace !== frontFace || force) {
  10225. this._depthCullingState.frontFace = frontFace;
  10226. }
  10227. };
  10228. Engine.prototype.setZOffset = function (value) {
  10229. this._depthCullingState.zOffset = value;
  10230. };
  10231. Engine.prototype.getZOffset = function () {
  10232. return this._depthCullingState.zOffset;
  10233. };
  10234. Engine.prototype.setDepthBuffer = function (enable) {
  10235. this._depthCullingState.depthTest = enable;
  10236. };
  10237. Engine.prototype.getDepthWrite = function () {
  10238. return this._depthCullingState.depthMask;
  10239. };
  10240. Engine.prototype.setDepthWrite = function (enable) {
  10241. this._depthCullingState.depthMask = enable;
  10242. };
  10243. Engine.prototype.setColorWrite = function (enable) {
  10244. this._gl.colorMask(enable, enable, enable, enable);
  10245. this._colorWrite = enable;
  10246. };
  10247. Engine.prototype.getColorWrite = function () {
  10248. return this._colorWrite;
  10249. };
  10250. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  10251. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  10252. };
  10253. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  10254. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  10255. if (this._alphaMode === mode) {
  10256. return;
  10257. }
  10258. switch (mode) {
  10259. case Engine.ALPHA_DISABLE:
  10260. this._alphaState.alphaBlend = false;
  10261. break;
  10262. case Engine.ALPHA_PREMULTIPLIED:
  10263. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10264. this._alphaState.alphaBlend = true;
  10265. break;
  10266. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  10267. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10268. this._alphaState.alphaBlend = true;
  10269. break;
  10270. case Engine.ALPHA_COMBINE:
  10271. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10272. this._alphaState.alphaBlend = true;
  10273. break;
  10274. case Engine.ALPHA_ONEONE:
  10275. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10276. this._alphaState.alphaBlend = true;
  10277. break;
  10278. case Engine.ALPHA_ADD:
  10279. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10280. this._alphaState.alphaBlend = true;
  10281. break;
  10282. case Engine.ALPHA_SUBTRACT:
  10283. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10284. this._alphaState.alphaBlend = true;
  10285. break;
  10286. case Engine.ALPHA_MULTIPLY:
  10287. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  10288. this._alphaState.alphaBlend = true;
  10289. break;
  10290. case Engine.ALPHA_MAXIMIZED:
  10291. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10292. this._alphaState.alphaBlend = true;
  10293. break;
  10294. case Engine.ALPHA_INTERPOLATE:
  10295. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  10296. this._alphaState.alphaBlend = true;
  10297. break;
  10298. case Engine.ALPHA_SCREENMODE:
  10299. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10300. this._alphaState.alphaBlend = true;
  10301. break;
  10302. }
  10303. if (!noDepthWriteChange) {
  10304. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  10305. }
  10306. this._alphaMode = mode;
  10307. };
  10308. Engine.prototype.getAlphaMode = function () {
  10309. return this._alphaMode;
  10310. };
  10311. Engine.prototype.setAlphaTesting = function (enable) {
  10312. this._alphaTest = enable;
  10313. };
  10314. Engine.prototype.getAlphaTesting = function () {
  10315. return !!this._alphaTest;
  10316. };
  10317. // Textures
  10318. Engine.prototype.wipeCaches = function (bruteForce) {
  10319. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  10320. return;
  10321. }
  10322. this.resetTextureCache();
  10323. this._currentEffect = null;
  10324. // 6/8/2017: deltakosh: Should not be required anymore.
  10325. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  10326. if (bruteForce) {
  10327. this._currentProgram = null;
  10328. this._stencilState.reset();
  10329. this._depthCullingState.reset();
  10330. this.setDepthFunctionToLessOrEqual();
  10331. this._alphaState.reset();
  10332. }
  10333. this._cachedVertexBuffers = null;
  10334. this._cachedIndexBuffer = null;
  10335. this._cachedEffectForVertexBuffers = null;
  10336. this._unbindVertexArrayObject();
  10337. this.bindIndexBuffer(null);
  10338. this.bindArrayBuffer(null);
  10339. };
  10340. /**
  10341. * Set the compressed texture format to use, based on the formats you have, and the formats
  10342. * supported by the hardware / browser.
  10343. *
  10344. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  10345. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  10346. * to API arguments needed to compressed textures. This puts the burden on the container
  10347. * generator to house the arcane code for determining these for current & future formats.
  10348. *
  10349. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  10350. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  10351. *
  10352. * Note: The result of this call is not taken into account when a texture is base64.
  10353. *
  10354. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  10355. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  10356. *
  10357. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  10358. * @returns The extension selected.
  10359. */
  10360. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  10361. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  10362. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  10363. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  10364. return this._textureFormatInUse = this._texturesSupported[i];
  10365. }
  10366. }
  10367. }
  10368. // actively set format to nothing, to allow this to be called more than once
  10369. // and possibly fail the 2nd time
  10370. this._textureFormatInUse = null;
  10371. return null;
  10372. };
  10373. Engine.prototype._createTexture = function () {
  10374. var texture = this._gl.createTexture();
  10375. if (!texture) {
  10376. throw new Error("Unable to create texture");
  10377. }
  10378. return texture;
  10379. };
  10380. /**
  10381. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  10382. * @param {string} urlArg- This contains one of the following:
  10383. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  10384. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  10385. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  10386. *
  10387. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  10388. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  10389. * @param {Scene} scene- Needed for loading to the correct scene.
  10390. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  10391. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  10392. * @param {callback} onError- Optional callback to be called upon failure.
  10393. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  10394. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  10395. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  10396. *
  10397. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  10398. */
  10399. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  10400. var _this = this;
  10401. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10402. if (onLoad === void 0) { onLoad = null; }
  10403. if (onError === void 0) { onError = null; }
  10404. if (buffer === void 0) { buffer = null; }
  10405. if (fallBack === void 0) { fallBack = null; }
  10406. if (format === void 0) { format = null; }
  10407. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  10408. var fromData = url.substr(0, 5) === "data:";
  10409. var fromBlob = url.substr(0, 5) === "blob:";
  10410. var isBase64 = fromData && url.indexOf("base64") !== -1;
  10411. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  10412. // establish the file extension, if possible
  10413. var lastDot = url.lastIndexOf('.');
  10414. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  10415. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  10416. var isTGA = (extension === ".tga");
  10417. // determine if a ktx file should be substituted
  10418. var isKTX = false;
  10419. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  10420. url = url.substring(0, lastDot) + this._textureFormatInUse;
  10421. isKTX = true;
  10422. }
  10423. if (scene) {
  10424. scene._addPendingData(texture);
  10425. }
  10426. texture.url = url;
  10427. texture.generateMipMaps = !noMipmap;
  10428. texture.samplingMode = samplingMode;
  10429. texture.invertY = invertY;
  10430. if (!this._doNotHandleContextLost) {
  10431. // Keep a link to the buffer only if we plan to handle context lost
  10432. texture._buffer = buffer;
  10433. }
  10434. var onLoadObserver = null;
  10435. if (onLoad && !fallBack) {
  10436. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  10437. }
  10438. if (!fallBack)
  10439. this._internalTexturesCache.push(texture);
  10440. var onerror = function (message, exception) {
  10441. if (scene) {
  10442. scene._removePendingData(texture);
  10443. }
  10444. if (onLoadObserver) {
  10445. texture.onLoadedObservable.remove(onLoadObserver);
  10446. }
  10447. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  10448. if (isKTX) {
  10449. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10450. }
  10451. else if (BABYLON.Tools.UseFallbackTexture) {
  10452. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10453. }
  10454. if (onError) {
  10455. onError(message || "Unknown error", exception);
  10456. }
  10457. };
  10458. var callback = null;
  10459. // processing for non-image formats
  10460. if (isKTX || isTGA || isDDS) {
  10461. if (isKTX) {
  10462. callback = function (data) {
  10463. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  10464. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  10465. ktx.uploadLevels(_this._gl, !noMipmap);
  10466. return false;
  10467. }, samplingMode);
  10468. };
  10469. }
  10470. else if (isTGA) {
  10471. callback = function (arrayBuffer) {
  10472. var data = new Uint8Array(arrayBuffer);
  10473. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  10474. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  10475. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  10476. return false;
  10477. }, samplingMode);
  10478. };
  10479. }
  10480. else if (isDDS) {
  10481. callback = function (data) {
  10482. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10483. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  10484. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  10485. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  10486. return false;
  10487. }, samplingMode);
  10488. };
  10489. }
  10490. if (!buffer) {
  10491. BABYLON.Tools.LoadFile(url, function (data) {
  10492. if (callback) {
  10493. callback(data);
  10494. }
  10495. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  10496. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  10497. });
  10498. }
  10499. else {
  10500. if (callback) {
  10501. callback(buffer);
  10502. }
  10503. }
  10504. // image format processing
  10505. }
  10506. else {
  10507. var onload = function (img) {
  10508. if (fromBlob && !_this._doNotHandleContextLost) {
  10509. // We need to store the image if we need to rebuild the texture
  10510. // in case of a webgl context lost
  10511. texture._buffer = img;
  10512. }
  10513. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  10514. var gl = _this._gl;
  10515. var isPot = (img.width === potWidth && img.height === potHeight);
  10516. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  10517. if (isPot) {
  10518. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10519. return false;
  10520. }
  10521. // Using shaders to rescale because canvas.drawImage is lossy
  10522. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10523. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  10524. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10525. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10526. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10527. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10528. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10529. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  10530. _this._releaseTexture(source);
  10531. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10532. continuationCallback();
  10533. });
  10534. return true;
  10535. }, samplingMode);
  10536. };
  10537. if (!fromData || isBase64)
  10538. if (buffer instanceof HTMLImageElement) {
  10539. onload(buffer);
  10540. }
  10541. else {
  10542. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10543. }
  10544. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  10545. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  10546. else
  10547. onload(buffer);
  10548. }
  10549. return texture;
  10550. };
  10551. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  10552. var _this = this;
  10553. var rtt = this.createRenderTargetTexture({
  10554. width: destination.width,
  10555. height: destination.height,
  10556. }, {
  10557. generateMipMaps: false,
  10558. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  10559. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  10560. generateDepthBuffer: false,
  10561. generateStencilBuffer: false
  10562. });
  10563. if (!this._rescalePostProcess) {
  10564. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  10565. }
  10566. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  10567. _this._rescalePostProcess.onApply = function (effect) {
  10568. effect._bindTexture("textureSampler", source);
  10569. };
  10570. var hostingScene = scene;
  10571. if (!hostingScene) {
  10572. hostingScene = _this.scenes[_this.scenes.length - 1];
  10573. }
  10574. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  10575. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  10576. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  10577. _this.unBindFramebuffer(rtt);
  10578. _this._releaseTexture(rtt);
  10579. if (onComplete) {
  10580. onComplete();
  10581. }
  10582. });
  10583. };
  10584. Engine.prototype._getInternalFormat = function (format) {
  10585. var internalFormat = this._gl.RGBA;
  10586. switch (format) {
  10587. case Engine.TEXTUREFORMAT_ALPHA:
  10588. internalFormat = this._gl.ALPHA;
  10589. break;
  10590. case Engine.TEXTUREFORMAT_LUMINANCE:
  10591. internalFormat = this._gl.LUMINANCE;
  10592. break;
  10593. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  10594. internalFormat = this._gl.LUMINANCE_ALPHA;
  10595. break;
  10596. case Engine.TEXTUREFORMAT_RGB:
  10597. internalFormat = this._gl.RGB;
  10598. break;
  10599. case Engine.TEXTUREFORMAT_RGBA:
  10600. internalFormat = this._gl.RGBA;
  10601. break;
  10602. }
  10603. return internalFormat;
  10604. };
  10605. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  10606. if (compression === void 0) { compression = null; }
  10607. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  10608. if (!texture) {
  10609. return;
  10610. }
  10611. var internalFormat = this._getInternalFormat(format);
  10612. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10613. var textureType = this._getWebGLTextureType(type);
  10614. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10615. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10616. if (!this._doNotHandleContextLost) {
  10617. texture._bufferView = data;
  10618. texture.format = format;
  10619. texture.type = type;
  10620. texture.invertY = invertY;
  10621. texture._compression = compression;
  10622. }
  10623. if (texture.width % 4 !== 0) {
  10624. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  10625. }
  10626. if (compression && data) {
  10627. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  10628. }
  10629. else {
  10630. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  10631. }
  10632. if (texture.generateMipMaps) {
  10633. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10634. }
  10635. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10636. this.resetTextureCache();
  10637. texture.isReady = true;
  10638. };
  10639. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  10640. if (compression === void 0) { compression = null; }
  10641. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  10642. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  10643. texture.baseWidth = width;
  10644. texture.baseHeight = height;
  10645. texture.width = width;
  10646. texture.height = height;
  10647. texture.format = format;
  10648. texture.generateMipMaps = generateMipMaps;
  10649. texture.samplingMode = samplingMode;
  10650. texture.invertY = invertY;
  10651. texture._compression = compression;
  10652. texture.type = type;
  10653. if (!this._doNotHandleContextLost) {
  10654. texture._bufferView = data;
  10655. }
  10656. this.updateRawTexture(texture, data, format, invertY, compression, type);
  10657. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10658. // Filters
  10659. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  10660. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10661. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10662. if (generateMipMaps) {
  10663. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10664. }
  10665. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10666. this._internalTexturesCache.push(texture);
  10667. return texture;
  10668. };
  10669. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  10670. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  10671. texture.baseWidth = width;
  10672. texture.baseHeight = height;
  10673. if (generateMipMaps) {
  10674. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  10675. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  10676. }
  10677. this.resetTextureCache();
  10678. texture.width = width;
  10679. texture.height = height;
  10680. texture.isReady = false;
  10681. texture.generateMipMaps = generateMipMaps;
  10682. texture.samplingMode = samplingMode;
  10683. this.updateTextureSamplingMode(samplingMode, texture);
  10684. this._internalTexturesCache.push(texture);
  10685. return texture;
  10686. };
  10687. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  10688. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  10689. if (texture.isCube) {
  10690. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10691. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10692. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10693. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10694. }
  10695. else if (texture.is3D) {
  10696. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  10697. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10698. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10699. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  10700. }
  10701. else {
  10702. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10703. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10704. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10705. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10706. }
  10707. texture.samplingMode = samplingMode;
  10708. };
  10709. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  10710. if (premulAlpha === void 0) { premulAlpha = false; }
  10711. if (!texture) {
  10712. return;
  10713. }
  10714. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10715. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  10716. if (premulAlpha) {
  10717. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  10718. }
  10719. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  10720. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  10721. if (texture.generateMipMaps) {
  10722. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10723. }
  10724. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10725. if (premulAlpha) {
  10726. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  10727. }
  10728. this.resetTextureCache();
  10729. texture.isReady = true;
  10730. };
  10731. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10732. if (!texture || texture._isDisabled) {
  10733. return;
  10734. }
  10735. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10736. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10737. try {
  10738. // Testing video texture support
  10739. if (this._videoTextureSupported === undefined) {
  10740. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10741. if (this._gl.getError() !== 0) {
  10742. this._videoTextureSupported = false;
  10743. }
  10744. else {
  10745. this._videoTextureSupported = true;
  10746. }
  10747. }
  10748. // Copy video through the current working canvas if video texture is not supported
  10749. if (!this._videoTextureSupported) {
  10750. if (!texture._workingCanvas) {
  10751. texture._workingCanvas = document.createElement("canvas");
  10752. var context = texture._workingCanvas.getContext("2d");
  10753. if (!context) {
  10754. throw new Error("Unable to get 2d context");
  10755. }
  10756. texture._workingContext = context;
  10757. texture._workingCanvas.width = texture.width;
  10758. texture._workingCanvas.height = texture.height;
  10759. }
  10760. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10761. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10762. }
  10763. else {
  10764. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10765. }
  10766. if (texture.generateMipMaps) {
  10767. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10768. }
  10769. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10770. this.resetTextureCache();
  10771. texture.isReady = true;
  10772. }
  10773. catch (ex) {
  10774. // Something unexpected
  10775. // Let's disable the texture
  10776. texture._isDisabled = true;
  10777. }
  10778. };
  10779. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10780. var fullOptions = new RenderTargetCreationOptions();
  10781. if (options !== undefined && typeof options === "object") {
  10782. fullOptions.generateMipMaps = options.generateMipMaps;
  10783. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10784. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10785. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10786. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10787. }
  10788. else {
  10789. fullOptions.generateMipMaps = options;
  10790. fullOptions.generateDepthBuffer = true;
  10791. fullOptions.generateStencilBuffer = false;
  10792. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10793. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10794. }
  10795. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10796. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10797. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10798. }
  10799. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10800. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10801. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10802. }
  10803. var gl = this._gl;
  10804. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10805. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10806. var width = size.width || size;
  10807. var height = size.height || size;
  10808. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  10809. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10810. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10811. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10812. }
  10813. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10814. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10815. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10816. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10817. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10818. // Create the framebuffer
  10819. var framebuffer = gl.createFramebuffer();
  10820. this.bindUnboundFramebuffer(framebuffer);
  10821. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10822. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  10823. if (fullOptions.generateMipMaps) {
  10824. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10825. }
  10826. // Unbind
  10827. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10828. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10829. this.bindUnboundFramebuffer(null);
  10830. texture._framebuffer = framebuffer;
  10831. texture.baseWidth = width;
  10832. texture.baseHeight = height;
  10833. texture.width = width;
  10834. texture.height = height;
  10835. texture.isReady = true;
  10836. texture.samples = 1;
  10837. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  10838. texture.samplingMode = fullOptions.samplingMode;
  10839. texture.type = fullOptions.type;
  10840. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10841. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  10842. this.resetTextureCache();
  10843. this._internalTexturesCache.push(texture);
  10844. return texture;
  10845. };
  10846. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10847. var generateMipMaps = false;
  10848. var generateDepthBuffer = true;
  10849. var generateStencilBuffer = false;
  10850. var generateDepthTexture = false;
  10851. var textureCount = 1;
  10852. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10853. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10854. var types = [], samplingModes = [];
  10855. if (options !== undefined) {
  10856. generateMipMaps = options.generateMipMaps;
  10857. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10858. generateStencilBuffer = options.generateStencilBuffer;
  10859. generateDepthTexture = options.generateDepthTexture;
  10860. textureCount = options.textureCount || 1;
  10861. if (options.types) {
  10862. types = options.types;
  10863. }
  10864. if (options.samplingModes) {
  10865. samplingModes = options.samplingModes;
  10866. }
  10867. }
  10868. var gl = this._gl;
  10869. // Create the framebuffer
  10870. var framebuffer = gl.createFramebuffer();
  10871. this.bindUnboundFramebuffer(framebuffer);
  10872. var width = size.width || size;
  10873. var height = size.height || size;
  10874. var textures = [];
  10875. var attachments = [];
  10876. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10877. for (var i = 0; i < textureCount; i++) {
  10878. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10879. var type = types[i] || defaultType;
  10880. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10881. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10882. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10883. }
  10884. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10885. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10886. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10887. }
  10888. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10889. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10890. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10891. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10892. }
  10893. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10894. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10895. textures.push(texture);
  10896. attachments.push(attachment);
  10897. gl.activeTexture(gl["TEXTURE" + i]);
  10898. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10899. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10900. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10901. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10902. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10903. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10904. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10905. if (generateMipMaps) {
  10906. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10907. }
  10908. // Unbind
  10909. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10910. texture._framebuffer = framebuffer;
  10911. texture._depthStencilBuffer = depthStencilBuffer;
  10912. texture.baseWidth = width;
  10913. texture.baseHeight = height;
  10914. texture.width = width;
  10915. texture.height = height;
  10916. texture.isReady = true;
  10917. texture.samples = 1;
  10918. texture.generateMipMaps = generateMipMaps;
  10919. texture.samplingMode = samplingMode;
  10920. texture.type = type;
  10921. texture._generateDepthBuffer = generateDepthBuffer;
  10922. texture._generateStencilBuffer = generateStencilBuffer;
  10923. this._internalTexturesCache.push(texture);
  10924. }
  10925. if (generateDepthTexture && this._caps.depthTextureExtension) {
  10926. // Depth texture
  10927. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10928. gl.activeTexture(gl.TEXTURE0);
  10929. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10930. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10931. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10932. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10933. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10934. 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);
  10935. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10936. depthTexture._framebuffer = framebuffer;
  10937. depthTexture.baseWidth = width;
  10938. depthTexture.baseHeight = height;
  10939. depthTexture.width = width;
  10940. depthTexture.height = height;
  10941. depthTexture.isReady = true;
  10942. depthTexture.samples = 1;
  10943. depthTexture.generateMipMaps = generateMipMaps;
  10944. depthTexture.samplingMode = gl.NEAREST;
  10945. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10946. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10947. textures.push(depthTexture);
  10948. this._internalTexturesCache.push(depthTexture);
  10949. }
  10950. gl.drawBuffers(attachments);
  10951. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10952. this.bindUnboundFramebuffer(null);
  10953. this.resetTextureCache();
  10954. return textures;
  10955. };
  10956. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10957. if (samples === void 0) { samples = 1; }
  10958. var depthStencilBuffer = null;
  10959. var gl = this._gl;
  10960. // Create the depth/stencil buffer
  10961. if (generateStencilBuffer) {
  10962. depthStencilBuffer = gl.createRenderbuffer();
  10963. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10964. if (samples > 1) {
  10965. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10966. }
  10967. else {
  10968. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10969. }
  10970. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10971. }
  10972. else if (generateDepthBuffer) {
  10973. depthStencilBuffer = gl.createRenderbuffer();
  10974. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10975. if (samples > 1) {
  10976. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10977. }
  10978. else {
  10979. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10980. }
  10981. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10982. }
  10983. return depthStencilBuffer;
  10984. };
  10985. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10986. if (this.webGLVersion < 2 || !texture) {
  10987. return 1;
  10988. }
  10989. if (texture.samples === samples) {
  10990. return samples;
  10991. }
  10992. var gl = this._gl;
  10993. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10994. // Dispose previous render buffers
  10995. if (texture._depthStencilBuffer) {
  10996. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10997. }
  10998. if (texture._MSAAFramebuffer) {
  10999. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11000. }
  11001. if (texture._MSAARenderBuffer) {
  11002. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11003. }
  11004. if (samples > 1) {
  11005. var framebuffer = gl.createFramebuffer();
  11006. if (!framebuffer) {
  11007. throw new Error("Unable to create multi sampled framebuffer");
  11008. }
  11009. texture._MSAAFramebuffer = framebuffer;
  11010. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  11011. var colorRenderbuffer = gl.createRenderbuffer();
  11012. if (!colorRenderbuffer) {
  11013. throw new Error("Unable to create multi sampled framebuffer");
  11014. }
  11015. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  11016. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  11017. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  11018. texture._MSAARenderBuffer = colorRenderbuffer;
  11019. }
  11020. else {
  11021. this.bindUnboundFramebuffer(texture._framebuffer);
  11022. }
  11023. texture.samples = samples;
  11024. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  11025. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11026. this.bindUnboundFramebuffer(null);
  11027. return samples;
  11028. };
  11029. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  11030. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  11031. };
  11032. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  11033. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  11034. };
  11035. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  11036. var gl = this._gl;
  11037. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  11038. var generateMipMaps = true;
  11039. var generateDepthBuffer = true;
  11040. var generateStencilBuffer = false;
  11041. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  11042. if (options !== undefined) {
  11043. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  11044. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  11045. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  11046. if (options.samplingMode !== undefined) {
  11047. samplingMode = options.samplingMode;
  11048. }
  11049. }
  11050. texture.isCube = true;
  11051. texture.generateMipMaps = generateMipMaps;
  11052. texture.samples = 1;
  11053. texture.samplingMode = samplingMode;
  11054. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11055. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11056. for (var face = 0; face < 6; face++) {
  11057. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  11058. }
  11059. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  11060. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  11061. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11062. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11063. // Create the framebuffer
  11064. var framebuffer = gl.createFramebuffer();
  11065. this.bindUnboundFramebuffer(framebuffer);
  11066. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  11067. // Mipmaps
  11068. if (texture.generateMipMaps) {
  11069. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11070. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11071. }
  11072. // Unbind
  11073. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11074. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11075. this.bindUnboundFramebuffer(null);
  11076. texture._framebuffer = framebuffer;
  11077. texture.width = size;
  11078. texture.height = size;
  11079. texture.isReady = true;
  11080. this.resetTextureCache();
  11081. this._internalTexturesCache.push(texture);
  11082. return texture;
  11083. };
  11084. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  11085. var _this = this;
  11086. if (onLoad === void 0) { onLoad = null; }
  11087. if (onError === void 0) { onError = null; }
  11088. if (forcedExtension === void 0) { forcedExtension = null; }
  11089. var callback = function (loadData) {
  11090. if (!loadData) {
  11091. if (onLoad) {
  11092. onLoad(null);
  11093. }
  11094. return;
  11095. }
  11096. var texture = loadData.texture;
  11097. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  11098. texture._lodGenerationScale = scale;
  11099. texture._lodGenerationOffset = offset;
  11100. if (_this._caps.textureLOD) {
  11101. // Do not add extra process if texture lod is supported.
  11102. if (onLoad) {
  11103. onLoad(texture);
  11104. }
  11105. return;
  11106. }
  11107. var mipSlices = 3;
  11108. var gl = _this._gl;
  11109. var width = loadData.width;
  11110. if (!width) {
  11111. return;
  11112. }
  11113. var textures = [];
  11114. for (var i = 0; i < mipSlices; i++) {
  11115. //compute LOD from even spacing in smoothness (matching shader calculation)
  11116. var smoothness = i / (mipSlices - 1);
  11117. var roughness = 1 - smoothness;
  11118. var minLODIndex = offset; // roughness = 0
  11119. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  11120. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  11121. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  11122. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  11123. glTextureFromLod.isCube = true;
  11124. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  11125. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11126. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  11127. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11128. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11129. if (loadData.isDDS) {
  11130. var info = loadData.info;
  11131. var data = loadData.data;
  11132. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  11133. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  11134. }
  11135. else {
  11136. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  11137. }
  11138. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11139. // Wrap in a base texture for easy binding.
  11140. var lodTexture = new BABYLON.BaseTexture(scene);
  11141. lodTexture.isCube = true;
  11142. lodTexture._texture = glTextureFromLod;
  11143. glTextureFromLod.isReady = true;
  11144. textures.push(lodTexture);
  11145. }
  11146. texture._lodTextureHigh = textures[2];
  11147. texture._lodTextureMid = textures[1];
  11148. texture._lodTextureLow = textures[0];
  11149. if (onLoad) {
  11150. onLoad(texture);
  11151. }
  11152. };
  11153. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  11154. };
  11155. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  11156. var _this = this;
  11157. if (onLoad === void 0) { onLoad = null; }
  11158. if (onError === void 0) { onError = null; }
  11159. if (forcedExtension === void 0) { forcedExtension = null; }
  11160. var gl = this._gl;
  11161. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  11162. texture.isCube = true;
  11163. texture.url = rootUrl;
  11164. texture.generateMipMaps = !noMipmap;
  11165. if (!this._doNotHandleContextLost) {
  11166. texture._extension = forcedExtension;
  11167. texture._files = files;
  11168. }
  11169. var isKTX = false;
  11170. var isDDS = false;
  11171. var lastDot = rootUrl.lastIndexOf('.');
  11172. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  11173. if (this._textureFormatInUse) {
  11174. extension = this._textureFormatInUse;
  11175. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  11176. isKTX = true;
  11177. }
  11178. else {
  11179. isDDS = (extension === ".dds");
  11180. }
  11181. var onerror = function (request, exception) {
  11182. if (onError && request) {
  11183. onError(request.status + " " + request.statusText, exception);
  11184. }
  11185. };
  11186. if (isKTX) {
  11187. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  11188. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  11189. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  11190. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11191. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  11192. ktx.uploadLevels(_this._gl, !noMipmap);
  11193. _this.setCubeMapTextureParams(gl, loadMipmap);
  11194. texture.width = ktx.pixelWidth;
  11195. texture.height = ktx.pixelHeight;
  11196. texture.isReady = true;
  11197. }, undefined, undefined, true, onerror);
  11198. }
  11199. else if (isDDS) {
  11200. if (files && files.length === 6) {
  11201. cascadeLoadFiles(rootUrl, scene, function (imgs) {
  11202. var info;
  11203. var loadMipmap = false;
  11204. var width = 0;
  11205. for (var index = 0; index < imgs.length; index++) {
  11206. var data = imgs[index];
  11207. info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  11208. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  11209. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11210. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  11211. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  11212. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  11213. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11214. }
  11215. texture.width = info.width;
  11216. texture.height = info.height;
  11217. texture.type = info.textureType;
  11218. width = info.width;
  11219. }
  11220. _this.setCubeMapTextureParams(gl, loadMipmap);
  11221. texture.isReady = true;
  11222. if (onLoad) {
  11223. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  11224. }
  11225. }, files, onError);
  11226. }
  11227. else {
  11228. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  11229. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  11230. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  11231. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11232. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  11233. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  11234. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  11235. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11236. }
  11237. _this.setCubeMapTextureParams(gl, loadMipmap);
  11238. texture.width = info.width;
  11239. texture.height = info.height;
  11240. texture.isReady = true;
  11241. texture.type = info.textureType;
  11242. if (onLoad) {
  11243. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  11244. }
  11245. }, undefined, undefined, true, onerror);
  11246. }
  11247. }
  11248. else {
  11249. if (!files) {
  11250. throw new Error("Cannot load cubemap because files were not defined");
  11251. }
  11252. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  11253. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  11254. var height = width;
  11255. _this._prepareWorkingCanvas();
  11256. if (!_this._workingCanvas || !_this._workingContext) {
  11257. return;
  11258. }
  11259. _this._workingCanvas.width = width;
  11260. _this._workingCanvas.height = height;
  11261. var faces = [
  11262. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  11263. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  11264. ];
  11265. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11266. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11267. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  11268. for (var index = 0; index < faces.length; index++) {
  11269. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  11270. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  11271. }
  11272. if (!noMipmap) {
  11273. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11274. }
  11275. _this.setCubeMapTextureParams(gl, !noMipmap);
  11276. texture.width = width;
  11277. texture.height = height;
  11278. texture.isReady = true;
  11279. if (format) {
  11280. texture.format = format;
  11281. }
  11282. texture.onLoadedObservable.notifyObservers(texture);
  11283. texture.onLoadedObservable.clear();
  11284. if (onLoad) {
  11285. onLoad();
  11286. }
  11287. }, files, onError);
  11288. }
  11289. this._internalTexturesCache.push(texture);
  11290. return texture;
  11291. };
  11292. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  11293. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11294. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  11295. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11296. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11297. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11298. this.resetTextureCache();
  11299. };
  11300. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  11301. if (compression === void 0) { compression = null; }
  11302. if (level === void 0) { level = 0; }
  11303. texture._bufferViewArray = data;
  11304. texture.format = format;
  11305. texture.type = type;
  11306. texture.invertY = invertY;
  11307. texture._compression = compression;
  11308. var gl = this._gl;
  11309. var textureType = this._getWebGLTextureType(type);
  11310. var internalFormat = this._getInternalFormat(format);
  11311. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11312. var needConversion = false;
  11313. if (internalFormat === gl.RGB) {
  11314. internalFormat = gl.RGBA;
  11315. needConversion = true;
  11316. }
  11317. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11318. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11319. if (texture.width % 4 !== 0) {
  11320. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  11321. }
  11322. // Data are known to be in +X +Y +Z -X -Y -Z
  11323. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11324. var faceData = data[faceIndex];
  11325. if (compression) {
  11326. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  11327. }
  11328. else {
  11329. if (needConversion) {
  11330. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  11331. }
  11332. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  11333. }
  11334. }
  11335. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11336. if (isPot && texture.generateMipMaps && level === 0) {
  11337. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11338. }
  11339. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11340. this.resetTextureCache();
  11341. texture.isReady = true;
  11342. };
  11343. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  11344. if (compression === void 0) { compression = null; }
  11345. var gl = this._gl;
  11346. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  11347. texture.isCube = true;
  11348. texture.generateMipMaps = generateMipMaps;
  11349. texture.format = format;
  11350. texture.type = type;
  11351. if (!this._doNotHandleContextLost) {
  11352. texture._bufferViewArray = data;
  11353. }
  11354. var textureType = this._getWebGLTextureType(type);
  11355. var internalFormat = this._getInternalFormat(format);
  11356. if (internalFormat === gl.RGB) {
  11357. internalFormat = gl.RGBA;
  11358. }
  11359. var width = size;
  11360. var height = width;
  11361. texture.width = width;
  11362. texture.height = height;
  11363. // Double check on POT to generate Mips.
  11364. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11365. if (!isPot) {
  11366. generateMipMaps = false;
  11367. }
  11368. // Upload data if needed. The texture won't be ready until then.
  11369. if (data) {
  11370. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  11371. }
  11372. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  11373. // Filters
  11374. if (data && generateMipMaps) {
  11375. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11376. }
  11377. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  11378. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11379. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11380. }
  11381. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  11382. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11383. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11384. }
  11385. else {
  11386. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11387. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  11388. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  11389. }
  11390. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11391. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11392. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11393. return texture;
  11394. };
  11395. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  11396. var _this = this;
  11397. if (onLoad === void 0) { onLoad = null; }
  11398. if (onError === void 0) { onError = null; }
  11399. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11400. if (invertY === void 0) { invertY = false; }
  11401. var gl = this._gl;
  11402. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  11403. scene._addPendingData(texture);
  11404. texture.url = url;
  11405. this._internalTexturesCache.push(texture);
  11406. var onerror = function (request, exception) {
  11407. scene._removePendingData(texture);
  11408. if (onError && request) {
  11409. onError(request.status + " " + request.statusText, exception);
  11410. }
  11411. };
  11412. var internalCallback = function (data) {
  11413. var width = texture.width;
  11414. var faceDataArrays = callback(data);
  11415. if (!faceDataArrays) {
  11416. return;
  11417. }
  11418. if (mipmmapGenerator) {
  11419. var textureType = _this._getWebGLTextureType(type);
  11420. var internalFormat = _this._getInternalFormat(format);
  11421. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  11422. var needConversion = false;
  11423. if (internalFormat === gl.RGB) {
  11424. internalFormat = gl.RGBA;
  11425. needConversion = true;
  11426. }
  11427. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11428. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11429. var mipData = mipmmapGenerator(faceDataArrays);
  11430. for (var level = 0; level < mipData.length; level++) {
  11431. var mipSize = width >> level;
  11432. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11433. var mipFaceData = mipData[level][faceIndex];
  11434. if (needConversion) {
  11435. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  11436. }
  11437. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  11438. }
  11439. }
  11440. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11441. }
  11442. else {
  11443. texture.generateMipMaps = !noMipmap;
  11444. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  11445. }
  11446. texture.isReady = true;
  11447. _this.resetTextureCache();
  11448. scene._removePendingData(texture);
  11449. if (onLoad) {
  11450. onLoad();
  11451. }
  11452. };
  11453. BABYLON.Tools.LoadFile(url, function (data) {
  11454. internalCallback(data);
  11455. }, undefined, scene.database, true, onerror);
  11456. return texture;
  11457. };
  11458. ;
  11459. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  11460. if (compression === void 0) { compression = null; }
  11461. var internalFormat = this._getInternalFormat(format);
  11462. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11463. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11464. if (!this._doNotHandleContextLost) {
  11465. texture._bufferView = data;
  11466. texture.format = format;
  11467. texture.invertY = invertY;
  11468. texture._compression = compression;
  11469. }
  11470. if (texture.width % 4 !== 0) {
  11471. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11472. }
  11473. if (compression && data) {
  11474. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  11475. }
  11476. else {
  11477. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  11478. }
  11479. if (texture.generateMipMaps) {
  11480. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11481. }
  11482. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11483. this.resetTextureCache();
  11484. texture.isReady = true;
  11485. };
  11486. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  11487. if (compression === void 0) { compression = null; }
  11488. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  11489. texture.baseWidth = width;
  11490. texture.baseHeight = height;
  11491. texture.baseDepth = depth;
  11492. texture.width = width;
  11493. texture.height = height;
  11494. texture.depth = depth;
  11495. texture.format = format;
  11496. texture.generateMipMaps = generateMipMaps;
  11497. texture.samplingMode = samplingMode;
  11498. texture.is3D = true;
  11499. if (!this._doNotHandleContextLost) {
  11500. texture._bufferView = data;
  11501. }
  11502. this.updateRawTexture3D(texture, data, format, invertY, compression);
  11503. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11504. // Filters
  11505. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11506. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11507. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11508. if (generateMipMaps) {
  11509. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11510. }
  11511. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11512. this._internalTexturesCache.push(texture);
  11513. return texture;
  11514. };
  11515. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  11516. var gl = this._gl;
  11517. if (!gl) {
  11518. return;
  11519. }
  11520. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  11521. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11522. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11523. if (!noMipmap && !isCompressed) {
  11524. gl.generateMipmap(gl.TEXTURE_2D);
  11525. }
  11526. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11527. this.resetTextureCache();
  11528. if (scene) {
  11529. scene._removePendingData(texture);
  11530. }
  11531. texture.onLoadedObservable.notifyObservers(texture);
  11532. texture.onLoadedObservable.clear();
  11533. };
  11534. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  11535. var _this = this;
  11536. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11537. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  11538. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  11539. var gl = this._gl;
  11540. if (!gl) {
  11541. return;
  11542. }
  11543. if (!texture._webGLTexture) {
  11544. this.resetTextureCache();
  11545. if (scene) {
  11546. scene._removePendingData(texture);
  11547. }
  11548. return;
  11549. }
  11550. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11551. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11552. texture.baseWidth = width;
  11553. texture.baseHeight = height;
  11554. texture.width = potWidth;
  11555. texture.height = potHeight;
  11556. texture.isReady = true;
  11557. if (processFunction(potWidth, potHeight, function () {
  11558. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11559. })) {
  11560. // Returning as texture needs extra async steps
  11561. return;
  11562. }
  11563. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11564. };
  11565. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  11566. // Create new RGBA data container.
  11567. var rgbaData;
  11568. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  11569. rgbaData = new Float32Array(width * height * 4);
  11570. }
  11571. else {
  11572. rgbaData = new Uint32Array(width * height * 4);
  11573. }
  11574. // Convert each pixel.
  11575. for (var x = 0; x < width; x++) {
  11576. for (var y = 0; y < height; y++) {
  11577. var index = (y * width + x) * 3;
  11578. var newIndex = (y * width + x) * 4;
  11579. // Map Old Value to new value.
  11580. rgbaData[newIndex + 0] = rgbData[index + 0];
  11581. rgbaData[newIndex + 1] = rgbData[index + 1];
  11582. rgbaData[newIndex + 2] = rgbData[index + 2];
  11583. // Add fully opaque alpha channel.
  11584. rgbaData[newIndex + 3] = 1;
  11585. }
  11586. }
  11587. return rgbaData;
  11588. };
  11589. Engine.prototype._releaseFramebufferObjects = function (texture) {
  11590. var gl = this._gl;
  11591. if (texture._framebuffer) {
  11592. gl.deleteFramebuffer(texture._framebuffer);
  11593. texture._framebuffer = null;
  11594. }
  11595. if (texture._depthStencilBuffer) {
  11596. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11597. texture._depthStencilBuffer = null;
  11598. }
  11599. if (texture._MSAAFramebuffer) {
  11600. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11601. texture._MSAAFramebuffer = null;
  11602. }
  11603. if (texture._MSAARenderBuffer) {
  11604. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11605. texture._MSAARenderBuffer = null;
  11606. }
  11607. };
  11608. Engine.prototype._releaseTexture = function (texture) {
  11609. var gl = this._gl;
  11610. this._releaseFramebufferObjects(texture);
  11611. gl.deleteTexture(texture._webGLTexture);
  11612. // Unbind channels
  11613. this.unbindAllTextures();
  11614. var index = this._internalTexturesCache.indexOf(texture);
  11615. if (index !== -1) {
  11616. this._internalTexturesCache.splice(index, 1);
  11617. }
  11618. // Integrated fixed lod samplers.
  11619. if (texture._lodTextureHigh) {
  11620. texture._lodTextureHigh.dispose();
  11621. }
  11622. if (texture._lodTextureMid) {
  11623. texture._lodTextureMid.dispose();
  11624. }
  11625. if (texture._lodTextureLow) {
  11626. texture._lodTextureLow.dispose();
  11627. }
  11628. };
  11629. Engine.prototype.setProgram = function (program) {
  11630. if (this._currentProgram !== program) {
  11631. this._gl.useProgram(program);
  11632. this._currentProgram = program;
  11633. }
  11634. };
  11635. Engine.prototype.bindSamplers = function (effect) {
  11636. this.setProgram(effect.getProgram());
  11637. var samplers = effect.getSamplers();
  11638. for (var index = 0; index < samplers.length; index++) {
  11639. var uniform = effect.getUniform(samplers[index]);
  11640. if (uniform) {
  11641. this._boundUniforms[index] = uniform;
  11642. }
  11643. }
  11644. this._currentEffect = null;
  11645. };
  11646. Engine.prototype._activateTextureChannel = function (channel) {
  11647. if (this._activeChannel !== channel) {
  11648. this._gl.activeTexture(this._gl.TEXTURE0 + channel);
  11649. this._activeChannel = channel;
  11650. }
  11651. };
  11652. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  11653. var index = this._boundTexturesOrder.indexOf(internalTexture);
  11654. if (index > -1 && index !== this._boundTexturesOrder.length - 1) {
  11655. this._boundTexturesOrder.splice(index, 1);
  11656. this._boundTexturesOrder.push(internalTexture);
  11657. }
  11658. };
  11659. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  11660. var currentSlot = internalTexture._designatedSlot;
  11661. internalTexture._designatedSlot = -1;
  11662. var index = this._boundTexturesOrder.indexOf(internalTexture);
  11663. if (index > -1) {
  11664. this._boundTexturesOrder.splice(index, 1);
  11665. }
  11666. return currentSlot;
  11667. };
  11668. Engine.prototype._bindTextureDirectly = function (target, texture, isPartOfTextureArray) {
  11669. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  11670. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  11671. var isTextureForRendering = texture && texture._initialSlot > -1;
  11672. if (currentTextureBound !== texture) {
  11673. if (currentTextureBound) {
  11674. this._removeDesignatedSlot(currentTextureBound);
  11675. }
  11676. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  11677. if (this._activeChannel >= 0) {
  11678. this._boundTexturesCache[this._activeChannel] = texture;
  11679. if (isTextureForRendering) {
  11680. this._boundTexturesOrder.push(texture);
  11681. }
  11682. }
  11683. }
  11684. if (isTextureForRendering) {
  11685. texture._designatedSlot = this._activeChannel;
  11686. if (!isPartOfTextureArray) {
  11687. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  11688. }
  11689. }
  11690. };
  11691. Engine.prototype._bindTexture = function (channel, texture) {
  11692. if (channel < 0) {
  11693. return;
  11694. }
  11695. if (texture) {
  11696. channel = this._getCorrectTextureChannel(channel, texture);
  11697. }
  11698. this._activateTextureChannel(channel);
  11699. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  11700. };
  11701. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  11702. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  11703. };
  11704. Engine.prototype.unbindAllTextures = function () {
  11705. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  11706. this._activateTextureChannel(channel);
  11707. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11708. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11709. if (this.webGLVersion > 1) {
  11710. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11711. }
  11712. }
  11713. };
  11714. Engine.prototype.setTexture = function (channel, uniform, texture) {
  11715. if (channel < 0) {
  11716. return;
  11717. }
  11718. if (uniform) {
  11719. this._boundUniforms[channel] = uniform;
  11720. }
  11721. this._setTexture(channel, texture);
  11722. };
  11723. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  11724. if (!internalTexture) {
  11725. return -1;
  11726. }
  11727. internalTexture._initialSlot = channel;
  11728. if (channel !== internalTexture._designatedSlot) {
  11729. if (internalTexture._designatedSlot > -1) {
  11730. channel = internalTexture._designatedSlot;
  11731. }
  11732. else {
  11733. if (this._nextFreeTextureSlot > -1) {
  11734. channel = this._nextFreeTextureSlot;
  11735. this._nextFreeTextureSlot++;
  11736. if (this._nextFreeTextureSlot >= this._caps.maxTexturesImageUnits) {
  11737. this._nextFreeTextureSlot = -1; // No more free slots, we will recycle
  11738. }
  11739. }
  11740. else {
  11741. channel = this._removeDesignatedSlot(this._boundTexturesOrder[0]);
  11742. }
  11743. }
  11744. }
  11745. return channel;
  11746. };
  11747. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  11748. var uniform = this._boundUniforms[sourceSlot];
  11749. this._gl.uniform1i(uniform, destination);
  11750. };
  11751. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  11752. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  11753. // Not ready?
  11754. if (!texture) {
  11755. if (this._boundTexturesCache[channel] != null) {
  11756. this._activateTextureChannel(channel);
  11757. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11758. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11759. if (this.webGLVersion > 1) {
  11760. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11761. }
  11762. }
  11763. return false;
  11764. }
  11765. // Video
  11766. var alreadyActivated = false;
  11767. if (texture.video) {
  11768. this._activateTextureChannel(channel);
  11769. alreadyActivated = true;
  11770. texture.update();
  11771. }
  11772. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  11773. texture.delayLoad();
  11774. return false;
  11775. }
  11776. var internalTexture;
  11777. if (texture.isReady()) {
  11778. internalTexture = texture.getInternalTexture();
  11779. }
  11780. else if (texture.isCube) {
  11781. internalTexture = this.emptyCubeTexture;
  11782. }
  11783. else if (texture.is3D) {
  11784. internalTexture = this.emptyTexture3D;
  11785. }
  11786. else {
  11787. internalTexture = this.emptyTexture;
  11788. }
  11789. if (!isPartOfTextureArray) {
  11790. channel = this._getCorrectTextureChannel(channel, internalTexture);
  11791. }
  11792. if (this._boundTexturesCache[channel] === internalTexture) {
  11793. this._moveBoundTextureOnTop(internalTexture);
  11794. if (!isPartOfTextureArray) {
  11795. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  11796. }
  11797. return false;
  11798. }
  11799. if (!alreadyActivated) {
  11800. this._activateTextureChannel(channel);
  11801. }
  11802. if (internalTexture && internalTexture.is3D) {
  11803. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  11804. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11805. internalTexture._cachedWrapU = texture.wrapU;
  11806. switch (texture.wrapU) {
  11807. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11808. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11809. break;
  11810. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11811. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11812. break;
  11813. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11814. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11815. break;
  11816. }
  11817. }
  11818. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11819. internalTexture._cachedWrapV = texture.wrapV;
  11820. switch (texture.wrapV) {
  11821. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11822. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11823. break;
  11824. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11825. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11826. break;
  11827. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11828. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11829. break;
  11830. }
  11831. }
  11832. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  11833. internalTexture._cachedWrapR = texture.wrapR;
  11834. switch (texture.wrapV) {
  11835. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11836. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  11837. break;
  11838. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11839. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  11840. break;
  11841. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11842. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  11843. break;
  11844. }
  11845. }
  11846. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  11847. }
  11848. else if (internalTexture && internalTexture.isCube) {
  11849. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  11850. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  11851. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  11852. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  11853. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  11854. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  11855. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  11856. }
  11857. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  11858. }
  11859. else {
  11860. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  11861. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11862. internalTexture._cachedWrapU = texture.wrapU;
  11863. switch (texture.wrapU) {
  11864. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11865. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11866. break;
  11867. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11868. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11869. break;
  11870. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11871. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11872. break;
  11873. }
  11874. }
  11875. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11876. internalTexture._cachedWrapV = texture.wrapV;
  11877. switch (texture.wrapV) {
  11878. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11879. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11880. break;
  11881. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11882. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11883. break;
  11884. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11885. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11886. break;
  11887. }
  11888. }
  11889. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  11890. }
  11891. return true;
  11892. };
  11893. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  11894. if (channel < 0 || !uniform) {
  11895. return;
  11896. }
  11897. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  11898. this._textureUnits = new Int32Array(textures.length);
  11899. }
  11900. for (var i = 0; i < textures.length; i++) {
  11901. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  11902. }
  11903. this._gl.uniform1iv(uniform, this._textureUnits);
  11904. for (var index = 0; index < textures.length; index++) {
  11905. this._setTexture(this._textureUnits[index], textures[index], true);
  11906. }
  11907. };
  11908. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  11909. var internalTexture = texture.getInternalTexture();
  11910. if (!internalTexture) {
  11911. return;
  11912. }
  11913. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  11914. var value = texture.anisotropicFilteringLevel;
  11915. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  11916. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  11917. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  11918. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  11919. }
  11920. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  11921. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  11922. internalTexture._cachedAnisotropicFilteringLevel = value;
  11923. }
  11924. };
  11925. Engine.prototype.readPixels = function (x, y, width, height) {
  11926. var data = new Uint8Array(height * width * 4);
  11927. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  11928. return data;
  11929. };
  11930. /**
  11931. * Add an externaly attached data from its key.
  11932. * This method call will fail and return false, if such key already exists.
  11933. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  11934. * @param key the unique key that identifies the data
  11935. * @param data the data object to associate to the key for this Engine instance
  11936. * @return true if no such key were already present and the data was added successfully, false otherwise
  11937. */
  11938. Engine.prototype.addExternalData = function (key, data) {
  11939. if (!this._externalData) {
  11940. this._externalData = new BABYLON.StringDictionary();
  11941. }
  11942. return this._externalData.add(key, data);
  11943. };
  11944. /**
  11945. * Get an externaly attached data from its key
  11946. * @param key the unique key that identifies the data
  11947. * @return the associated data, if present (can be null), or undefined if not present
  11948. */
  11949. Engine.prototype.getExternalData = function (key) {
  11950. if (!this._externalData) {
  11951. this._externalData = new BABYLON.StringDictionary();
  11952. }
  11953. return this._externalData.get(key);
  11954. };
  11955. /**
  11956. * Get an externaly attached data from its key, create it using a factory if it's not already present
  11957. * @param key the unique key that identifies the data
  11958. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  11959. * @return the associated data, can be null if the factory returned null.
  11960. */
  11961. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  11962. if (!this._externalData) {
  11963. this._externalData = new BABYLON.StringDictionary();
  11964. }
  11965. return this._externalData.getOrAddWithFactory(key, factory);
  11966. };
  11967. /**
  11968. * Remove an externaly attached data from the Engine instance
  11969. * @param key the unique key that identifies the data
  11970. * @return true if the data was successfully removed, false if it doesn't exist
  11971. */
  11972. Engine.prototype.removeExternalData = function (key) {
  11973. if (!this._externalData) {
  11974. this._externalData = new BABYLON.StringDictionary();
  11975. }
  11976. return this._externalData.remove(key);
  11977. };
  11978. Engine.prototype.unbindAllAttributes = function () {
  11979. if (this._mustWipeVertexAttributes) {
  11980. this._mustWipeVertexAttributes = false;
  11981. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11982. this._gl.disableVertexAttribArray(i);
  11983. this._vertexAttribArraysEnabled[i] = false;
  11984. this._currentBufferPointers[i].active = false;
  11985. }
  11986. return;
  11987. }
  11988. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  11989. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  11990. continue;
  11991. }
  11992. this._gl.disableVertexAttribArray(i);
  11993. this._vertexAttribArraysEnabled[i] = false;
  11994. this._currentBufferPointers[i].active = false;
  11995. }
  11996. };
  11997. Engine.prototype.releaseEffects = function () {
  11998. for (var name in this._compiledEffects) {
  11999. this._deleteProgram(this._compiledEffects[name]._program);
  12000. }
  12001. this._compiledEffects = {};
  12002. };
  12003. // Dispose
  12004. Engine.prototype.dispose = function () {
  12005. this.hideLoadingUI();
  12006. this.stopRenderLoop();
  12007. // Release postProcesses
  12008. while (this.postProcesses.length) {
  12009. this.postProcesses[0].dispose();
  12010. }
  12011. // Empty texture
  12012. if (this._emptyTexture) {
  12013. this._releaseTexture(this._emptyTexture);
  12014. this._emptyTexture = null;
  12015. }
  12016. if (this._emptyCubeTexture) {
  12017. this._releaseTexture(this._emptyCubeTexture);
  12018. this._emptyCubeTexture = null;
  12019. }
  12020. // Rescale PP
  12021. if (this._rescalePostProcess) {
  12022. this._rescalePostProcess.dispose();
  12023. }
  12024. // Release scenes
  12025. while (this.scenes.length) {
  12026. this.scenes[0].dispose();
  12027. }
  12028. // Release audio engine
  12029. if (Engine.audioEngine) {
  12030. Engine.audioEngine.dispose();
  12031. }
  12032. // Release effects
  12033. this.releaseEffects();
  12034. // Unbind
  12035. this.unbindAllAttributes();
  12036. if (this._dummyFramebuffer) {
  12037. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  12038. }
  12039. //WebVR
  12040. this.disableVR();
  12041. // Events
  12042. if (BABYLON.Tools.IsWindowObjectExist()) {
  12043. window.removeEventListener("blur", this._onBlur);
  12044. window.removeEventListener("focus", this._onFocus);
  12045. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  12046. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  12047. if (this._renderingCanvas) {
  12048. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  12049. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  12050. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  12051. if (!this._doNotHandleContextLost) {
  12052. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  12053. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  12054. }
  12055. }
  12056. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  12057. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  12058. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  12059. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  12060. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  12061. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  12062. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  12063. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  12064. if (this._onVrDisplayConnect) {
  12065. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12066. if (this._onVrDisplayDisconnect) {
  12067. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12068. }
  12069. if (this._onVrDisplayPresentChange) {
  12070. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12071. }
  12072. this._onVrDisplayConnect = null;
  12073. this._onVrDisplayDisconnect = null;
  12074. }
  12075. }
  12076. // Remove from Instances
  12077. var index = Engine.Instances.indexOf(this);
  12078. if (index >= 0) {
  12079. Engine.Instances.splice(index, 1);
  12080. }
  12081. this._workingCanvas = null;
  12082. this._workingContext = null;
  12083. this._currentBufferPointers = [];
  12084. this._renderingCanvas = null;
  12085. this._currentProgram = null;
  12086. this.onResizeObservable.clear();
  12087. this.onCanvasBlurObservable.clear();
  12088. this.onCanvasFocusObservable.clear();
  12089. this.onCanvasPointerOutObservable.clear();
  12090. this.onBeginFrameObservable.clear();
  12091. this.onEndFrameObservable.clear();
  12092. BABYLON.Effect.ResetCache();
  12093. };
  12094. // Loading screen
  12095. Engine.prototype.displayLoadingUI = function () {
  12096. if (!BABYLON.Tools.IsWindowObjectExist()) {
  12097. return;
  12098. }
  12099. var loadingScreen = this.loadingScreen;
  12100. if (loadingScreen) {
  12101. loadingScreen.displayLoadingUI();
  12102. }
  12103. };
  12104. Engine.prototype.hideLoadingUI = function () {
  12105. if (!BABYLON.Tools.IsWindowObjectExist()) {
  12106. return;
  12107. }
  12108. var loadingScreen = this.loadingScreen;
  12109. if (loadingScreen) {
  12110. loadingScreen.hideLoadingUI();
  12111. }
  12112. };
  12113. Object.defineProperty(Engine.prototype, "loadingScreen", {
  12114. get: function () {
  12115. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  12116. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  12117. return this._loadingScreen;
  12118. },
  12119. set: function (loadingScreen) {
  12120. this._loadingScreen = loadingScreen;
  12121. },
  12122. enumerable: true,
  12123. configurable: true
  12124. });
  12125. Object.defineProperty(Engine.prototype, "loadingUIText", {
  12126. set: function (text) {
  12127. this.loadingScreen.loadingUIText = text;
  12128. },
  12129. enumerable: true,
  12130. configurable: true
  12131. });
  12132. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  12133. set: function (color) {
  12134. this.loadingScreen.loadingUIBackgroundColor = color;
  12135. },
  12136. enumerable: true,
  12137. configurable: true
  12138. });
  12139. Engine.prototype.attachContextLostEvent = function (callback) {
  12140. if (this._renderingCanvas) {
  12141. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  12142. }
  12143. };
  12144. Engine.prototype.attachContextRestoredEvent = function (callback) {
  12145. if (this._renderingCanvas) {
  12146. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  12147. }
  12148. };
  12149. Engine.prototype.getVertexShaderSource = function (program) {
  12150. var shaders = this._gl.getAttachedShaders(program);
  12151. if (!shaders) {
  12152. return null;
  12153. }
  12154. return this._gl.getShaderSource(shaders[0]);
  12155. };
  12156. Engine.prototype.getFragmentShaderSource = function (program) {
  12157. var shaders = this._gl.getAttachedShaders(program);
  12158. if (!shaders) {
  12159. return null;
  12160. }
  12161. return this._gl.getShaderSource(shaders[1]);
  12162. };
  12163. Engine.prototype.getError = function () {
  12164. return this._gl.getError();
  12165. };
  12166. // FPS
  12167. Engine.prototype.getFps = function () {
  12168. return this._fps;
  12169. };
  12170. Engine.prototype.getDeltaTime = function () {
  12171. return this._deltaTime;
  12172. };
  12173. Engine.prototype._measureFps = function () {
  12174. this._performanceMonitor.sampleFrame();
  12175. this._fps = this._performanceMonitor.averageFPS;
  12176. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  12177. };
  12178. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  12179. if (faceIndex === void 0) { faceIndex = -1; }
  12180. var gl = this._gl;
  12181. if (!this._dummyFramebuffer) {
  12182. var dummy = gl.createFramebuffer();
  12183. if (!dummy) {
  12184. throw new Error("Unable to create dummy framebuffer");
  12185. }
  12186. this._dummyFramebuffer = dummy;
  12187. }
  12188. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  12189. if (faceIndex > -1) {
  12190. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12191. }
  12192. else {
  12193. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  12194. }
  12195. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  12196. var buffer;
  12197. switch (readType) {
  12198. case gl.UNSIGNED_BYTE:
  12199. buffer = new Uint8Array(4 * width * height);
  12200. readType = gl.UNSIGNED_BYTE;
  12201. break;
  12202. default:
  12203. buffer = new Float32Array(4 * width * height);
  12204. readType = gl.FLOAT;
  12205. break;
  12206. }
  12207. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  12208. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  12209. return buffer;
  12210. };
  12211. Engine.prototype._canRenderToFloatFramebuffer = function () {
  12212. if (this._webGLVersion > 1) {
  12213. return this._caps.colorBufferFloat;
  12214. }
  12215. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  12216. };
  12217. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  12218. if (this._webGLVersion > 1) {
  12219. return this._caps.colorBufferFloat;
  12220. }
  12221. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  12222. };
  12223. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  12224. Engine.prototype._canRenderToFramebuffer = function (type) {
  12225. var gl = this._gl;
  12226. //clear existing errors
  12227. while (gl.getError() !== gl.NO_ERROR) { }
  12228. var successful = true;
  12229. var texture = gl.createTexture();
  12230. gl.bindTexture(gl.TEXTURE_2D, texture);
  12231. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  12232. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12233. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12234. var fb = gl.createFramebuffer();
  12235. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  12236. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  12237. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  12238. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  12239. successful = successful && (gl.getError() === gl.NO_ERROR);
  12240. //try render by clearing frame buffer's color buffer
  12241. if (successful) {
  12242. gl.clear(gl.COLOR_BUFFER_BIT);
  12243. successful = successful && (gl.getError() === gl.NO_ERROR);
  12244. }
  12245. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  12246. if (successful) {
  12247. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  12248. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  12249. var readFormat = gl.RGBA;
  12250. var readType = gl.UNSIGNED_BYTE;
  12251. var buffer = new Uint8Array(4);
  12252. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  12253. successful = successful && (gl.getError() === gl.NO_ERROR);
  12254. }
  12255. //clean up
  12256. gl.deleteTexture(texture);
  12257. gl.deleteFramebuffer(fb);
  12258. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  12259. //clear accumulated errors
  12260. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  12261. return successful;
  12262. };
  12263. Engine.prototype._getWebGLTextureType = function (type) {
  12264. if (type === Engine.TEXTURETYPE_FLOAT) {
  12265. return this._gl.FLOAT;
  12266. }
  12267. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  12268. // Add Half Float Constant.
  12269. return this._gl.HALF_FLOAT_OES;
  12270. }
  12271. return this._gl.UNSIGNED_BYTE;
  12272. };
  12273. ;
  12274. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  12275. if (this._webGLVersion === 1) {
  12276. return this._gl.RGBA;
  12277. }
  12278. if (type === Engine.TEXTURETYPE_FLOAT) {
  12279. return this._gl.RGBA32F;
  12280. }
  12281. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  12282. return this._gl.RGBA16F;
  12283. }
  12284. return this._gl.RGBA;
  12285. };
  12286. ;
  12287. Engine.prototype.createQuery = function () {
  12288. return this._gl.createQuery();
  12289. };
  12290. Engine.prototype.deleteQuery = function (query) {
  12291. this._gl.deleteQuery(query);
  12292. return this;
  12293. };
  12294. Engine.prototype.isQueryResultAvailable = function (query) {
  12295. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  12296. };
  12297. Engine.prototype.getQueryResult = function (query) {
  12298. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  12299. };
  12300. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  12301. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  12302. this._gl.beginQuery(glAlgorithm, query);
  12303. return this;
  12304. };
  12305. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  12306. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  12307. this._gl.endQuery(glAlgorithm);
  12308. return this;
  12309. };
  12310. /* Time queries */
  12311. Engine.prototype._createTimeQuery = function () {
  12312. var timerQuery = this._caps.timerQuery;
  12313. if (timerQuery.createQueryEXT) {
  12314. return timerQuery.createQueryEXT();
  12315. }
  12316. return this.createQuery();
  12317. };
  12318. Engine.prototype._deleteTimeQuery = function (query) {
  12319. var timerQuery = this._caps.timerQuery;
  12320. if (timerQuery.deleteQueryEXT) {
  12321. timerQuery.deleteQueryEXT(query);
  12322. return;
  12323. }
  12324. this.deleteQuery(query);
  12325. };
  12326. Engine.prototype._getTimeQueryResult = function (query) {
  12327. var timerQuery = this._caps.timerQuery;
  12328. if (timerQuery.getQueryObjectEXT) {
  12329. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  12330. }
  12331. return this.getQueryResult(query);
  12332. };
  12333. Engine.prototype._getTimeQueryAvailability = function (query) {
  12334. var timerQuery = this._caps.timerQuery;
  12335. if (timerQuery.getQueryObjectEXT) {
  12336. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  12337. }
  12338. return this.isQueryResultAvailable(query);
  12339. };
  12340. Engine.prototype.startTimeQuery = function () {
  12341. var timerQuery = this._caps.timerQuery;
  12342. if (!timerQuery) {
  12343. return null;
  12344. }
  12345. var token = new BABYLON._TimeToken();
  12346. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12347. if (this._caps.canUseTimestampForTimerQuery) {
  12348. token._startTimeQuery = this._createTimeQuery();
  12349. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  12350. }
  12351. else {
  12352. if (this._currentNonTimestampToken) {
  12353. return this._currentNonTimestampToken;
  12354. }
  12355. token._timeElapsedQuery = this._createTimeQuery();
  12356. if (timerQuery.beginQueryEXT) {
  12357. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12358. }
  12359. else {
  12360. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12361. }
  12362. this._currentNonTimestampToken = token;
  12363. }
  12364. return token;
  12365. };
  12366. Engine.prototype.endTimeQuery = function (token) {
  12367. var timerQuery = this._caps.timerQuery;
  12368. if (!timerQuery || !token) {
  12369. return -1;
  12370. }
  12371. if (this._caps.canUseTimestampForTimerQuery) {
  12372. if (!token._startTimeQuery) {
  12373. return -1;
  12374. }
  12375. if (!token._endTimeQuery) {
  12376. token._endTimeQuery = this._createTimeQuery();
  12377. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  12378. }
  12379. }
  12380. else if (!token._timeElapsedQueryEnded) {
  12381. if (!token._timeElapsedQuery) {
  12382. return -1;
  12383. }
  12384. if (timerQuery.endQueryEXT) {
  12385. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  12386. }
  12387. else {
  12388. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  12389. }
  12390. token._timeElapsedQueryEnded = true;
  12391. }
  12392. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12393. var available = false;
  12394. if (token._endTimeQuery) {
  12395. available = this._getTimeQueryAvailability(token._endTimeQuery);
  12396. }
  12397. else if (token._timeElapsedQuery) {
  12398. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  12399. }
  12400. if (available && !disjoint) {
  12401. var result = 0;
  12402. if (this._caps.canUseTimestampForTimerQuery) {
  12403. if (!token._startTimeQuery || !token._endTimeQuery) {
  12404. return -1;
  12405. }
  12406. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  12407. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  12408. result = timeEnd - timeStart;
  12409. this._deleteTimeQuery(token._startTimeQuery);
  12410. this._deleteTimeQuery(token._endTimeQuery);
  12411. token._startTimeQuery = null;
  12412. token._endTimeQuery = null;
  12413. }
  12414. else {
  12415. if (!token._timeElapsedQuery) {
  12416. return -1;
  12417. }
  12418. result = this._getTimeQueryResult(token._timeElapsedQuery);
  12419. this._deleteTimeQuery(token._timeElapsedQuery);
  12420. token._timeElapsedQuery = null;
  12421. token._timeElapsedQueryEnded = false;
  12422. this._currentNonTimestampToken = null;
  12423. }
  12424. return result;
  12425. }
  12426. return -1;
  12427. };
  12428. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  12429. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  12430. };
  12431. // Transform feedback
  12432. Engine.prototype.createTransformFeedback = function () {
  12433. return this._gl.createTransformFeedback();
  12434. };
  12435. Engine.prototype.deleteTransformFeedback = function (value) {
  12436. this._gl.deleteTransformFeedback(value);
  12437. };
  12438. Engine.prototype.bindTransformFeedback = function (value) {
  12439. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  12440. };
  12441. Engine.prototype.beginTransformFeedback = function (usePoints) {
  12442. if (usePoints === void 0) { usePoints = true; }
  12443. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  12444. };
  12445. Engine.prototype.endTransformFeedback = function () {
  12446. this._gl.endTransformFeedback();
  12447. };
  12448. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  12449. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  12450. };
  12451. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  12452. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  12453. };
  12454. // Statics
  12455. Engine.isSupported = function () {
  12456. try {
  12457. var tempcanvas = document.createElement("canvas");
  12458. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  12459. return gl != null && !!window.WebGLRenderingContext;
  12460. }
  12461. catch (e) {
  12462. return false;
  12463. }
  12464. };
  12465. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  12466. Engine.WebGL2UniformBuffersExceptionList = ["Chrome/63"];
  12467. Engine.Instances = new Array();
  12468. // Const statics
  12469. Engine._ALPHA_DISABLE = 0;
  12470. Engine._ALPHA_ADD = 1;
  12471. Engine._ALPHA_COMBINE = 2;
  12472. Engine._ALPHA_SUBTRACT = 3;
  12473. Engine._ALPHA_MULTIPLY = 4;
  12474. Engine._ALPHA_MAXIMIZED = 5;
  12475. Engine._ALPHA_ONEONE = 6;
  12476. Engine._ALPHA_PREMULTIPLIED = 7;
  12477. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  12478. Engine._ALPHA_INTERPOLATE = 9;
  12479. Engine._ALPHA_SCREENMODE = 10;
  12480. Engine._DELAYLOADSTATE_NONE = 0;
  12481. Engine._DELAYLOADSTATE_LOADED = 1;
  12482. Engine._DELAYLOADSTATE_LOADING = 2;
  12483. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  12484. Engine._TEXTUREFORMAT_ALPHA = 0;
  12485. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  12486. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  12487. Engine._TEXTUREFORMAT_RGB = 4;
  12488. Engine._TEXTUREFORMAT_RGBA = 5;
  12489. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  12490. Engine._TEXTURETYPE_FLOAT = 1;
  12491. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  12492. // Depht or Stencil test Constants.
  12493. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  12494. 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.
  12495. 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.
  12496. 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.
  12497. 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.
  12498. 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.
  12499. 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.
  12500. 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.
  12501. // Stencil Actions Constants.
  12502. Engine._KEEP = 0x1E00;
  12503. Engine._REPLACE = 0x1E01;
  12504. Engine._INCR = 0x1E02;
  12505. Engine._DECR = 0x1E03;
  12506. Engine._INVERT = 0x150A;
  12507. Engine._INCR_WRAP = 0x8507;
  12508. Engine._DECR_WRAP = 0x8508;
  12509. // Texture rescaling mode
  12510. Engine._SCALEMODE_FLOOR = 1;
  12511. Engine._SCALEMODE_NEAREST = 2;
  12512. Engine._SCALEMODE_CEILING = 3;
  12513. // Updatable statics so stick with vars here
  12514. Engine.CollisionsEpsilon = 0.001;
  12515. Engine.CodeRepository = "src/";
  12516. Engine.ShadersRepository = "src/Shaders/";
  12517. return Engine;
  12518. }());
  12519. BABYLON.Engine = Engine;
  12520. })(BABYLON || (BABYLON = {}));
  12521. //# sourceMappingURL=babylon.engine.js.map
  12522. var BABYLON;
  12523. (function (BABYLON) {
  12524. /**
  12525. * Node is the basic class for all scene objects (Mesh, Light Camera).
  12526. */
  12527. var Node = /** @class */ (function () {
  12528. /**
  12529. * @constructor
  12530. * @param {string} name - the name and id to be given to this node
  12531. * @param {BABYLON.Scene} the scene this node will be added to
  12532. */
  12533. function Node(name, scene) {
  12534. if (scene === void 0) { scene = null; }
  12535. this.state = "";
  12536. this.metadata = null;
  12537. this.doNotSerialize = false;
  12538. this.animations = new Array();
  12539. this._ranges = {};
  12540. this._isEnabled = true;
  12541. this._isReady = true;
  12542. this._currentRenderId = -1;
  12543. this._parentRenderId = -1;
  12544. /**
  12545. * An event triggered when the mesh is disposed.
  12546. * @type {BABYLON.Observable}
  12547. */
  12548. this.onDisposeObservable = new BABYLON.Observable();
  12549. // Behaviors
  12550. this._behaviors = new Array();
  12551. this.name = name;
  12552. this.id = name;
  12553. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  12554. this.uniqueId = this._scene.getUniqueId();
  12555. this._initCache();
  12556. }
  12557. Object.defineProperty(Node.prototype, "parent", {
  12558. get: function () {
  12559. return this._parentNode;
  12560. },
  12561. set: function (parent) {
  12562. if (this._parentNode === parent) {
  12563. return;
  12564. }
  12565. if (this._parentNode) {
  12566. var index = this._parentNode._children.indexOf(this);
  12567. if (index !== -1) {
  12568. this._parentNode._children.splice(index, 1);
  12569. }
  12570. }
  12571. this._parentNode = parent;
  12572. if (this._parentNode) {
  12573. if (!this._parentNode._children) {
  12574. this._parentNode._children = new Array();
  12575. }
  12576. this._parentNode._children.push(this);
  12577. }
  12578. },
  12579. enumerable: true,
  12580. configurable: true
  12581. });
  12582. Node.prototype.getClassName = function () {
  12583. return "Node";
  12584. };
  12585. Object.defineProperty(Node.prototype, "onDispose", {
  12586. set: function (callback) {
  12587. if (this._onDisposeObserver) {
  12588. this.onDisposeObservable.remove(this._onDisposeObserver);
  12589. }
  12590. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  12591. },
  12592. enumerable: true,
  12593. configurable: true
  12594. });
  12595. Node.prototype.getScene = function () {
  12596. return this._scene;
  12597. };
  12598. Node.prototype.getEngine = function () {
  12599. return this._scene.getEngine();
  12600. };
  12601. Node.prototype.addBehavior = function (behavior) {
  12602. var _this = this;
  12603. var index = this._behaviors.indexOf(behavior);
  12604. if (index !== -1) {
  12605. return this;
  12606. }
  12607. behavior.init();
  12608. if (this._scene.isLoading) {
  12609. // We defer the attach when the scene will be loaded
  12610. var observer = this._scene.onDataLoadedObservable.add(function () {
  12611. behavior.attach(_this);
  12612. setTimeout(function () {
  12613. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  12614. _this._scene.onDataLoadedObservable.remove(observer);
  12615. }, 0);
  12616. });
  12617. }
  12618. else {
  12619. behavior.attach(this);
  12620. }
  12621. this._behaviors.push(behavior);
  12622. return this;
  12623. };
  12624. Node.prototype.removeBehavior = function (behavior) {
  12625. var index = this._behaviors.indexOf(behavior);
  12626. if (index === -1) {
  12627. return this;
  12628. }
  12629. this._behaviors[index].detach();
  12630. this._behaviors.splice(index, 1);
  12631. return this;
  12632. };
  12633. Object.defineProperty(Node.prototype, "behaviors", {
  12634. get: function () {
  12635. return this._behaviors;
  12636. },
  12637. enumerable: true,
  12638. configurable: true
  12639. });
  12640. Node.prototype.getBehaviorByName = function (name) {
  12641. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12642. var behavior = _a[_i];
  12643. if (behavior.name === name) {
  12644. return behavior;
  12645. }
  12646. }
  12647. return null;
  12648. };
  12649. // override it in derived class
  12650. Node.prototype.getWorldMatrix = function () {
  12651. return BABYLON.Matrix.Identity();
  12652. };
  12653. // override it in derived class if you add new variables to the cache
  12654. // and call the parent class method
  12655. Node.prototype._initCache = function () {
  12656. this._cache = {};
  12657. this._cache.parent = undefined;
  12658. };
  12659. Node.prototype.updateCache = function (force) {
  12660. if (!force && this.isSynchronized())
  12661. return;
  12662. this._cache.parent = this.parent;
  12663. this._updateCache();
  12664. };
  12665. // override it in derived class if you add new variables to the cache
  12666. // and call the parent class method if !ignoreParentClass
  12667. Node.prototype._updateCache = function (ignoreParentClass) {
  12668. };
  12669. // override it in derived class if you add new variables to the cache
  12670. Node.prototype._isSynchronized = function () {
  12671. return true;
  12672. };
  12673. Node.prototype._markSyncedWithParent = function () {
  12674. if (this.parent) {
  12675. this._parentRenderId = this.parent._currentRenderId;
  12676. }
  12677. };
  12678. Node.prototype.isSynchronizedWithParent = function () {
  12679. if (!this.parent) {
  12680. return true;
  12681. }
  12682. if (this._parentRenderId !== this.parent._currentRenderId) {
  12683. return false;
  12684. }
  12685. return this.parent.isSynchronized();
  12686. };
  12687. Node.prototype.isSynchronized = function (updateCache) {
  12688. var check = this.hasNewParent();
  12689. check = check || !this.isSynchronizedWithParent();
  12690. check = check || !this._isSynchronized();
  12691. if (updateCache)
  12692. this.updateCache(true);
  12693. return !check;
  12694. };
  12695. Node.prototype.hasNewParent = function (update) {
  12696. if (this._cache.parent === this.parent)
  12697. return false;
  12698. if (update)
  12699. this._cache.parent = this.parent;
  12700. return true;
  12701. };
  12702. /**
  12703. * Is this node ready to be used/rendered
  12704. * @return {boolean} is it ready
  12705. */
  12706. Node.prototype.isReady = function () {
  12707. return this._isReady;
  12708. };
  12709. /**
  12710. * Is this node enabled.
  12711. * If the node has a parent and is enabled, the parent will be inspected as well.
  12712. * @return {boolean} whether this node (and its parent) is enabled.
  12713. * @see setEnabled
  12714. */
  12715. Node.prototype.isEnabled = function () {
  12716. if (!this._isEnabled) {
  12717. return false;
  12718. }
  12719. if (this.parent) {
  12720. return this.parent.isEnabled();
  12721. }
  12722. return true;
  12723. };
  12724. /**
  12725. * Set the enabled state of this node.
  12726. * @param {boolean} value - the new enabled state
  12727. * @see isEnabled
  12728. */
  12729. Node.prototype.setEnabled = function (value) {
  12730. this._isEnabled = value;
  12731. };
  12732. /**
  12733. * Is this node a descendant of the given node.
  12734. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  12735. * @param {BABYLON.Node} ancestor - The parent node to inspect
  12736. * @see parent
  12737. */
  12738. Node.prototype.isDescendantOf = function (ancestor) {
  12739. if (this.parent) {
  12740. if (this.parent === ancestor) {
  12741. return true;
  12742. }
  12743. return this.parent.isDescendantOf(ancestor);
  12744. }
  12745. return false;
  12746. };
  12747. /**
  12748. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  12749. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  12750. * @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.
  12751. * @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.
  12752. */
  12753. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  12754. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  12755. if (!this._children) {
  12756. return;
  12757. }
  12758. for (var index = 0; index < this._children.length; index++) {
  12759. var item = this._children[index];
  12760. if (!predicate || predicate(item)) {
  12761. results.push(item);
  12762. }
  12763. if (!directDescendantsOnly) {
  12764. item._getDescendants(results, false, predicate);
  12765. }
  12766. }
  12767. };
  12768. /**
  12769. * Will return all nodes that have this node as ascendant.
  12770. * @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.
  12771. * @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.
  12772. * @return {BABYLON.Node[]} all children nodes of all types.
  12773. */
  12774. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  12775. var results = new Array();
  12776. this._getDescendants(results, directDescendantsOnly, predicate);
  12777. return results;
  12778. };
  12779. /**
  12780. * Get all child-meshes of this node.
  12781. */
  12782. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  12783. var results = [];
  12784. this._getDescendants(results, directDescendantsOnly, function (node) {
  12785. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  12786. });
  12787. return results;
  12788. };
  12789. /**
  12790. * Get all child-transformNodes of this node.
  12791. */
  12792. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  12793. var results = [];
  12794. this._getDescendants(results, directDescendantsOnly, function (node) {
  12795. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  12796. });
  12797. return results;
  12798. };
  12799. /**
  12800. * Get all direct children of this node.
  12801. */
  12802. Node.prototype.getChildren = function (predicate) {
  12803. return this.getDescendants(true, predicate);
  12804. };
  12805. Node.prototype._setReady = function (state) {
  12806. if (state === this._isReady) {
  12807. return;
  12808. }
  12809. if (!state) {
  12810. this._isReady = false;
  12811. return;
  12812. }
  12813. this._isReady = true;
  12814. if (this.onReady) {
  12815. this.onReady(this);
  12816. }
  12817. };
  12818. Node.prototype.getAnimationByName = function (name) {
  12819. for (var i = 0; i < this.animations.length; i++) {
  12820. var animation = this.animations[i];
  12821. if (animation.name === name) {
  12822. return animation;
  12823. }
  12824. }
  12825. return null;
  12826. };
  12827. Node.prototype.createAnimationRange = function (name, from, to) {
  12828. // check name not already in use
  12829. if (!this._ranges[name]) {
  12830. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  12831. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12832. if (this.animations[i]) {
  12833. this.animations[i].createRange(name, from, to);
  12834. }
  12835. }
  12836. }
  12837. };
  12838. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  12839. if (deleteFrames === void 0) { deleteFrames = true; }
  12840. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12841. if (this.animations[i]) {
  12842. this.animations[i].deleteRange(name, deleteFrames);
  12843. }
  12844. }
  12845. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  12846. };
  12847. Node.prototype.getAnimationRange = function (name) {
  12848. return this._ranges[name];
  12849. };
  12850. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  12851. var range = this.getAnimationRange(name);
  12852. if (!range) {
  12853. return;
  12854. }
  12855. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  12856. };
  12857. Node.prototype.serializeAnimationRanges = function () {
  12858. var serializationRanges = [];
  12859. for (var name in this._ranges) {
  12860. var localRange = this._ranges[name];
  12861. if (!localRange) {
  12862. continue;
  12863. }
  12864. var range = {};
  12865. range.name = name;
  12866. range.from = localRange.from;
  12867. range.to = localRange.to;
  12868. serializationRanges.push(range);
  12869. }
  12870. return serializationRanges;
  12871. };
  12872. // override it in derived class
  12873. Node.prototype.computeWorldMatrix = function (force) {
  12874. return BABYLON.Matrix.Identity();
  12875. };
  12876. Node.prototype.dispose = function () {
  12877. this.parent = null;
  12878. // Callback
  12879. this.onDisposeObservable.notifyObservers(this);
  12880. this.onDisposeObservable.clear();
  12881. // Behaviors
  12882. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12883. var behavior = _a[_i];
  12884. behavior.detach();
  12885. }
  12886. this._behaviors = [];
  12887. };
  12888. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  12889. if (parsedNode.ranges) {
  12890. for (var index = 0; index < parsedNode.ranges.length; index++) {
  12891. var data = parsedNode.ranges[index];
  12892. node.createAnimationRange(data.name, data.from, data.to);
  12893. }
  12894. }
  12895. };
  12896. __decorate([
  12897. BABYLON.serialize()
  12898. ], Node.prototype, "name", void 0);
  12899. __decorate([
  12900. BABYLON.serialize()
  12901. ], Node.prototype, "id", void 0);
  12902. __decorate([
  12903. BABYLON.serialize()
  12904. ], Node.prototype, "uniqueId", void 0);
  12905. __decorate([
  12906. BABYLON.serialize()
  12907. ], Node.prototype, "state", void 0);
  12908. __decorate([
  12909. BABYLON.serialize()
  12910. ], Node.prototype, "metadata", void 0);
  12911. return Node;
  12912. }());
  12913. BABYLON.Node = Node;
  12914. })(BABYLON || (BABYLON = {}));
  12915. //# sourceMappingURL=babylon.node.js.map
  12916. var BABYLON;
  12917. (function (BABYLON) {
  12918. var BoundingSphere = /** @class */ (function () {
  12919. function BoundingSphere(minimum, maximum) {
  12920. this.minimum = minimum;
  12921. this.maximum = maximum;
  12922. this._tempRadiusVector = BABYLON.Vector3.Zero();
  12923. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  12924. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  12925. this.radius = distance * 0.5;
  12926. this.centerWorld = BABYLON.Vector3.Zero();
  12927. this._update(BABYLON.Matrix.Identity());
  12928. }
  12929. // Methods
  12930. BoundingSphere.prototype._update = function (world) {
  12931. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  12932. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  12933. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  12934. };
  12935. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  12936. for (var i = 0; i < 6; i++) {
  12937. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  12938. return false;
  12939. }
  12940. return true;
  12941. };
  12942. BoundingSphere.prototype.intersectsPoint = function (point) {
  12943. var x = this.centerWorld.x - point.x;
  12944. var y = this.centerWorld.y - point.y;
  12945. var z = this.centerWorld.z - point.z;
  12946. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12947. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  12948. return false;
  12949. return true;
  12950. };
  12951. // Statics
  12952. BoundingSphere.Intersects = function (sphere0, sphere1) {
  12953. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  12954. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  12955. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  12956. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12957. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  12958. return false;
  12959. return true;
  12960. };
  12961. return BoundingSphere;
  12962. }());
  12963. BABYLON.BoundingSphere = BoundingSphere;
  12964. })(BABYLON || (BABYLON = {}));
  12965. //# sourceMappingURL=babylon.boundingSphere.js.map
  12966. var BABYLON;
  12967. (function (BABYLON) {
  12968. var BoundingBox = /** @class */ (function () {
  12969. function BoundingBox(minimum, maximum) {
  12970. this.minimum = minimum;
  12971. this.maximum = maximum;
  12972. this.vectors = new Array();
  12973. this.vectorsWorld = new Array();
  12974. // Bounding vectors
  12975. this.vectors.push(this.minimum.clone());
  12976. this.vectors.push(this.maximum.clone());
  12977. this.vectors.push(this.minimum.clone());
  12978. this.vectors[2].x = this.maximum.x;
  12979. this.vectors.push(this.minimum.clone());
  12980. this.vectors[3].y = this.maximum.y;
  12981. this.vectors.push(this.minimum.clone());
  12982. this.vectors[4].z = this.maximum.z;
  12983. this.vectors.push(this.maximum.clone());
  12984. this.vectors[5].z = this.minimum.z;
  12985. this.vectors.push(this.maximum.clone());
  12986. this.vectors[6].x = this.minimum.x;
  12987. this.vectors.push(this.maximum.clone());
  12988. this.vectors[7].y = this.minimum.y;
  12989. // OBB
  12990. this.center = this.maximum.add(this.minimum).scale(0.5);
  12991. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  12992. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  12993. // World
  12994. for (var index = 0; index < this.vectors.length; index++) {
  12995. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  12996. }
  12997. this.minimumWorld = BABYLON.Vector3.Zero();
  12998. this.maximumWorld = BABYLON.Vector3.Zero();
  12999. this.centerWorld = BABYLON.Vector3.Zero();
  13000. this.extendSizeWorld = BABYLON.Vector3.Zero();
  13001. this._update(BABYLON.Matrix.Identity());
  13002. }
  13003. // Methods
  13004. BoundingBox.prototype.getWorldMatrix = function () {
  13005. return this._worldMatrix;
  13006. };
  13007. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  13008. this._worldMatrix.copyFrom(matrix);
  13009. return this;
  13010. };
  13011. BoundingBox.prototype._update = function (world) {
  13012. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  13013. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  13014. for (var index = 0; index < this.vectors.length; index++) {
  13015. var v = this.vectorsWorld[index];
  13016. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  13017. if (v.x < this.minimumWorld.x)
  13018. this.minimumWorld.x = v.x;
  13019. if (v.y < this.minimumWorld.y)
  13020. this.minimumWorld.y = v.y;
  13021. if (v.z < this.minimumWorld.z)
  13022. this.minimumWorld.z = v.z;
  13023. if (v.x > this.maximumWorld.x)
  13024. this.maximumWorld.x = v.x;
  13025. if (v.y > this.maximumWorld.y)
  13026. this.maximumWorld.y = v.y;
  13027. if (v.z > this.maximumWorld.z)
  13028. this.maximumWorld.z = v.z;
  13029. }
  13030. // Extend
  13031. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  13032. this.extendSizeWorld.scaleInPlace(0.5);
  13033. // OBB
  13034. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  13035. this.centerWorld.scaleInPlace(0.5);
  13036. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  13037. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  13038. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  13039. this._worldMatrix = world;
  13040. };
  13041. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  13042. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  13043. };
  13044. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13045. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  13046. };
  13047. BoundingBox.prototype.intersectsPoint = function (point) {
  13048. var delta = -BABYLON.Epsilon;
  13049. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  13050. return false;
  13051. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  13052. return false;
  13053. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  13054. return false;
  13055. return true;
  13056. };
  13057. BoundingBox.prototype.intersectsSphere = function (sphere) {
  13058. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  13059. };
  13060. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  13061. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  13062. return false;
  13063. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  13064. return false;
  13065. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  13066. return false;
  13067. return true;
  13068. };
  13069. // Statics
  13070. BoundingBox.Intersects = function (box0, box1) {
  13071. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  13072. return false;
  13073. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  13074. return false;
  13075. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  13076. return false;
  13077. return true;
  13078. };
  13079. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  13080. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  13081. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  13082. return (num <= (sphereRadius * sphereRadius));
  13083. };
  13084. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  13085. for (var p = 0; p < 6; p++) {
  13086. for (var i = 0; i < 8; i++) {
  13087. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  13088. return false;
  13089. }
  13090. }
  13091. }
  13092. return true;
  13093. };
  13094. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  13095. for (var p = 0; p < 6; p++) {
  13096. var inCount = 8;
  13097. for (var i = 0; i < 8; i++) {
  13098. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  13099. --inCount;
  13100. }
  13101. else {
  13102. break;
  13103. }
  13104. }
  13105. if (inCount === 0)
  13106. return false;
  13107. }
  13108. return true;
  13109. };
  13110. return BoundingBox;
  13111. }());
  13112. BABYLON.BoundingBox = BoundingBox;
  13113. })(BABYLON || (BABYLON = {}));
  13114. //# sourceMappingURL=babylon.boundingBox.js.map
  13115. var BABYLON;
  13116. (function (BABYLON) {
  13117. var computeBoxExtents = function (axis, box) {
  13118. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  13119. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  13120. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  13121. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  13122. var r = r0 + r1 + r2;
  13123. return {
  13124. min: p - r,
  13125. max: p + r
  13126. };
  13127. };
  13128. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  13129. var axisOverlap = function (axis, box0, box1) {
  13130. var result0 = computeBoxExtents(axis, box0);
  13131. var result1 = computeBoxExtents(axis, box1);
  13132. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  13133. };
  13134. var BoundingInfo = /** @class */ (function () {
  13135. function BoundingInfo(minimum, maximum) {
  13136. this.minimum = minimum;
  13137. this.maximum = maximum;
  13138. this._isLocked = false;
  13139. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  13140. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  13141. }
  13142. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  13143. get: function () {
  13144. return this._isLocked;
  13145. },
  13146. set: function (value) {
  13147. this._isLocked = value;
  13148. },
  13149. enumerable: true,
  13150. configurable: true
  13151. });
  13152. // Methods
  13153. BoundingInfo.prototype.update = function (world) {
  13154. if (this._isLocked) {
  13155. return;
  13156. }
  13157. this.boundingBox._update(world);
  13158. this.boundingSphere._update(world);
  13159. };
  13160. /**
  13161. * Recreate the bounding info to be centered around a specific point given a specific extend.
  13162. * @param center New center of the bounding info
  13163. * @param extend New extend of the bounding info
  13164. */
  13165. BoundingInfo.prototype.centerOn = function (center, extend) {
  13166. this.minimum = center.subtract(extend);
  13167. this.maximum = center.add(extend);
  13168. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  13169. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  13170. return this;
  13171. };
  13172. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  13173. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  13174. return false;
  13175. return this.boundingBox.isInFrustum(frustumPlanes);
  13176. };
  13177. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  13178. /**
  13179. * Gets the world distance between the min and max points of the bounding box
  13180. */
  13181. get: function () {
  13182. var boundingBox = this.boundingBox;
  13183. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  13184. return size.length();
  13185. },
  13186. enumerable: true,
  13187. configurable: true
  13188. });
  13189. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13190. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  13191. };
  13192. BoundingInfo.prototype._checkCollision = function (collider) {
  13193. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  13194. };
  13195. BoundingInfo.prototype.intersectsPoint = function (point) {
  13196. if (!this.boundingSphere.centerWorld) {
  13197. return false;
  13198. }
  13199. if (!this.boundingSphere.intersectsPoint(point)) {
  13200. return false;
  13201. }
  13202. if (!this.boundingBox.intersectsPoint(point)) {
  13203. return false;
  13204. }
  13205. return true;
  13206. };
  13207. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  13208. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  13209. return false;
  13210. }
  13211. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  13212. return false;
  13213. }
  13214. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  13215. return false;
  13216. }
  13217. if (!precise) {
  13218. return true;
  13219. }
  13220. var box0 = this.boundingBox;
  13221. var box1 = boundingInfo.boundingBox;
  13222. if (!axisOverlap(box0.directions[0], box0, box1))
  13223. return false;
  13224. if (!axisOverlap(box0.directions[1], box0, box1))
  13225. return false;
  13226. if (!axisOverlap(box0.directions[2], box0, box1))
  13227. return false;
  13228. if (!axisOverlap(box1.directions[0], box0, box1))
  13229. return false;
  13230. if (!axisOverlap(box1.directions[1], box0, box1))
  13231. return false;
  13232. if (!axisOverlap(box1.directions[2], box0, box1))
  13233. return false;
  13234. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  13235. return false;
  13236. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  13237. return false;
  13238. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  13239. return false;
  13240. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  13241. return false;
  13242. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  13243. return false;
  13244. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  13245. return false;
  13246. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  13247. return false;
  13248. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  13249. return false;
  13250. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  13251. return false;
  13252. return true;
  13253. };
  13254. return BoundingInfo;
  13255. }());
  13256. BABYLON.BoundingInfo = BoundingInfo;
  13257. })(BABYLON || (BABYLON = {}));
  13258. //# sourceMappingURL=babylon.boundingInfo.js.map
  13259. var BABYLON;
  13260. (function (BABYLON) {
  13261. var TransformNode = /** @class */ (function (_super) {
  13262. __extends(TransformNode, _super);
  13263. function TransformNode(name, scene, isPure) {
  13264. if (scene === void 0) { scene = null; }
  13265. if (isPure === void 0) { isPure = true; }
  13266. var _this = _super.call(this, name, scene) || this;
  13267. // Properties
  13268. _this._rotation = BABYLON.Vector3.Zero();
  13269. _this._scaling = BABYLON.Vector3.One();
  13270. _this._isDirty = false;
  13271. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  13272. _this.scalingDeterminant = 1;
  13273. _this.infiniteDistance = false;
  13274. _this.position = BABYLON.Vector3.Zero();
  13275. _this._localWorld = BABYLON.Matrix.Zero();
  13276. _this._worldMatrix = BABYLON.Matrix.Zero();
  13277. _this._worldMatrixDeterminant = 0;
  13278. _this._absolutePosition = BABYLON.Vector3.Zero();
  13279. _this._pivotMatrix = BABYLON.Matrix.Identity();
  13280. _this._postMultiplyPivotMatrix = false;
  13281. _this._isWorldMatrixFrozen = false;
  13282. /**
  13283. * An event triggered after the world matrix is updated
  13284. * @type {BABYLON.Observable}
  13285. */
  13286. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  13287. _this._nonUniformScaling = false;
  13288. if (isPure) {
  13289. _this.getScene().addTransformNode(_this);
  13290. }
  13291. return _this;
  13292. }
  13293. Object.defineProperty(TransformNode.prototype, "rotation", {
  13294. /**
  13295. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  13296. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  13297. * Default : (0.0, 0.0, 0.0)
  13298. */
  13299. get: function () {
  13300. return this._rotation;
  13301. },
  13302. set: function (newRotation) {
  13303. this._rotation = newRotation;
  13304. },
  13305. enumerable: true,
  13306. configurable: true
  13307. });
  13308. Object.defineProperty(TransformNode.prototype, "scaling", {
  13309. /**
  13310. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13311. * Default : (1.0, 1.0, 1.0)
  13312. */
  13313. get: function () {
  13314. return this._scaling;
  13315. },
  13316. /**
  13317. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13318. * Default : (1.0, 1.0, 1.0)
  13319. */
  13320. set: function (newScaling) {
  13321. this._scaling = newScaling;
  13322. },
  13323. enumerable: true,
  13324. configurable: true
  13325. });
  13326. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  13327. /**
  13328. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  13329. * It's null by default.
  13330. * 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)
  13331. */
  13332. get: function () {
  13333. return this._rotationQuaternion;
  13334. },
  13335. set: function (quaternion) {
  13336. this._rotationQuaternion = quaternion;
  13337. //reset the rotation vector.
  13338. if (quaternion && this.rotation.length()) {
  13339. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  13340. }
  13341. },
  13342. enumerable: true,
  13343. configurable: true
  13344. });
  13345. /**
  13346. * Returns the latest update of the World matrix
  13347. * Returns a Matrix.
  13348. */
  13349. TransformNode.prototype.getWorldMatrix = function () {
  13350. if (this._currentRenderId !== this.getScene().getRenderId()) {
  13351. this.computeWorldMatrix();
  13352. }
  13353. return this._worldMatrix;
  13354. };
  13355. /**
  13356. * Returns the latest update of the World matrix determinant.
  13357. */
  13358. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  13359. if (this._currentRenderId !== this.getScene().getRenderId()) {
  13360. this._worldMatrixDeterminant = this.computeWorldMatrix().determinant();
  13361. }
  13362. return this._worldMatrixDeterminant;
  13363. };
  13364. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  13365. /**
  13366. * Returns directly the latest state of the mesh World matrix.
  13367. * A Matrix is returned.
  13368. */
  13369. get: function () {
  13370. return this._worldMatrix;
  13371. },
  13372. enumerable: true,
  13373. configurable: true
  13374. });
  13375. /**
  13376. * Copies the paramater passed Matrix into the mesh Pose matrix.
  13377. * Returns the AbstractMesh.
  13378. */
  13379. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  13380. this._poseMatrix.copyFrom(matrix);
  13381. return this;
  13382. };
  13383. /**
  13384. * Returns the mesh Pose matrix.
  13385. * Returned object : Matrix
  13386. */
  13387. TransformNode.prototype.getPoseMatrix = function () {
  13388. return this._poseMatrix;
  13389. };
  13390. TransformNode.prototype._isSynchronized = function () {
  13391. if (this._isDirty) {
  13392. return false;
  13393. }
  13394. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  13395. return false;
  13396. if (this._cache.pivotMatrixUpdated) {
  13397. return false;
  13398. }
  13399. if (this.infiniteDistance) {
  13400. return false;
  13401. }
  13402. if (!this._cache.position.equals(this.position))
  13403. return false;
  13404. if (this.rotationQuaternion) {
  13405. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13406. return false;
  13407. }
  13408. if (!this._cache.rotation.equals(this.rotation))
  13409. return false;
  13410. if (!this._cache.scaling.equals(this.scaling))
  13411. return false;
  13412. return true;
  13413. };
  13414. TransformNode.prototype._initCache = function () {
  13415. _super.prototype._initCache.call(this);
  13416. this._cache.localMatrixUpdated = false;
  13417. this._cache.position = BABYLON.Vector3.Zero();
  13418. this._cache.scaling = BABYLON.Vector3.Zero();
  13419. this._cache.rotation = BABYLON.Vector3.Zero();
  13420. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  13421. this._cache.billboardMode = -1;
  13422. };
  13423. TransformNode.prototype.markAsDirty = function (property) {
  13424. if (property === "rotation") {
  13425. this.rotationQuaternion = null;
  13426. }
  13427. this._currentRenderId = Number.MAX_VALUE;
  13428. this._isDirty = true;
  13429. return this;
  13430. };
  13431. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  13432. /**
  13433. * Returns the current mesh absolute position.
  13434. * Retuns a Vector3.
  13435. */
  13436. get: function () {
  13437. return this._absolutePosition;
  13438. },
  13439. enumerable: true,
  13440. configurable: true
  13441. });
  13442. /**
  13443. * Sets a new pivot matrix to the mesh.
  13444. * Returns the AbstractMesh.
  13445. */
  13446. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  13447. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  13448. this._pivotMatrix = matrix.clone();
  13449. this._cache.pivotMatrixUpdated = true;
  13450. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  13451. if (this._postMultiplyPivotMatrix) {
  13452. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  13453. }
  13454. return this;
  13455. };
  13456. /**
  13457. * Returns the mesh pivot matrix.
  13458. * Default : Identity.
  13459. * A Matrix is returned.
  13460. */
  13461. TransformNode.prototype.getPivotMatrix = function () {
  13462. return this._pivotMatrix;
  13463. };
  13464. /**
  13465. * Prevents the World matrix to be computed any longer.
  13466. * Returns the AbstractMesh.
  13467. */
  13468. TransformNode.prototype.freezeWorldMatrix = function () {
  13469. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  13470. this.computeWorldMatrix(true);
  13471. this._isWorldMatrixFrozen = true;
  13472. return this;
  13473. };
  13474. /**
  13475. * Allows back the World matrix computation.
  13476. * Returns the AbstractMesh.
  13477. */
  13478. TransformNode.prototype.unfreezeWorldMatrix = function () {
  13479. this._isWorldMatrixFrozen = false;
  13480. this.computeWorldMatrix(true);
  13481. return this;
  13482. };
  13483. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  13484. /**
  13485. * True if the World matrix has been frozen.
  13486. * Returns a boolean.
  13487. */
  13488. get: function () {
  13489. return this._isWorldMatrixFrozen;
  13490. },
  13491. enumerable: true,
  13492. configurable: true
  13493. });
  13494. /**
  13495. * Retuns the mesh absolute position in the World.
  13496. * Returns a Vector3.
  13497. */
  13498. TransformNode.prototype.getAbsolutePosition = function () {
  13499. this.computeWorldMatrix();
  13500. return this._absolutePosition;
  13501. };
  13502. /**
  13503. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13504. * Returns the AbstractMesh.
  13505. */
  13506. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  13507. if (!absolutePosition) {
  13508. return this;
  13509. }
  13510. var absolutePositionX;
  13511. var absolutePositionY;
  13512. var absolutePositionZ;
  13513. if (absolutePosition.x === undefined) {
  13514. if (arguments.length < 3) {
  13515. return this;
  13516. }
  13517. absolutePositionX = arguments[0];
  13518. absolutePositionY = arguments[1];
  13519. absolutePositionZ = arguments[2];
  13520. }
  13521. else {
  13522. absolutePositionX = absolutePosition.x;
  13523. absolutePositionY = absolutePosition.y;
  13524. absolutePositionZ = absolutePosition.z;
  13525. }
  13526. if (this.parent) {
  13527. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13528. invertParentWorldMatrix.invert();
  13529. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13530. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13531. }
  13532. else {
  13533. this.position.x = absolutePositionX;
  13534. this.position.y = absolutePositionY;
  13535. this.position.z = absolutePositionZ;
  13536. }
  13537. return this;
  13538. };
  13539. /**
  13540. * Sets the mesh position in its local space.
  13541. * Returns the AbstractMesh.
  13542. */
  13543. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  13544. this.computeWorldMatrix();
  13545. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13546. return this;
  13547. };
  13548. /**
  13549. * Returns the mesh position in the local space from the current World matrix values.
  13550. * Returns a new Vector3.
  13551. */
  13552. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  13553. this.computeWorldMatrix();
  13554. var invLocalWorldMatrix = this._localWorld.clone();
  13555. invLocalWorldMatrix.invert();
  13556. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13557. };
  13558. /**
  13559. * Translates the mesh along the passed Vector3 in its local space.
  13560. * Returns the AbstractMesh.
  13561. */
  13562. TransformNode.prototype.locallyTranslate = function (vector3) {
  13563. this.computeWorldMatrix(true);
  13564. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13565. return this;
  13566. };
  13567. /**
  13568. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  13569. * @param targetPoint the position (must be in same space as current mesh) to look at
  13570. * @param yawCor optional yaw (y-axis) correction in radians
  13571. * @param pitchCor optional pitch (x-axis) correction in radians
  13572. * @param rollCor optional roll (z-axis) correction in radians
  13573. * @param space the choosen space of the target
  13574. * @returns the TransformNode.
  13575. */
  13576. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13577. if (yawCor === void 0) { yawCor = 0; }
  13578. if (pitchCor === void 0) { pitchCor = 0; }
  13579. if (rollCor === void 0) { rollCor = 0; }
  13580. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13581. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  13582. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13583. targetPoint.subtractToRef(pos, dv);
  13584. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13585. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13586. var pitch = Math.atan2(dv.y, len);
  13587. if (this.rotationQuaternion) {
  13588. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13589. }
  13590. else {
  13591. this.rotation.x = pitch + pitchCor;
  13592. this.rotation.y = yaw + yawCor;
  13593. this.rotation.z = rollCor;
  13594. }
  13595. return this;
  13596. };
  13597. /**
  13598. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13599. * This Vector3 is expressed in the World space.
  13600. */
  13601. TransformNode.prototype.getDirection = function (localAxis) {
  13602. var result = BABYLON.Vector3.Zero();
  13603. this.getDirectionToRef(localAxis, result);
  13604. return result;
  13605. };
  13606. /**
  13607. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13608. * localAxis is expressed in the mesh local space.
  13609. * result is computed in the Wordl space from the mesh World matrix.
  13610. * Returns the AbstractMesh.
  13611. */
  13612. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  13613. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13614. return this;
  13615. };
  13616. TransformNode.prototype.setPivotPoint = function (point, space) {
  13617. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13618. if (this.getScene().getRenderId() == 0) {
  13619. this.computeWorldMatrix(true);
  13620. }
  13621. var wm = this.getWorldMatrix();
  13622. if (space == BABYLON.Space.WORLD) {
  13623. var tmat = BABYLON.Tmp.Matrix[0];
  13624. wm.invertToRef(tmat);
  13625. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13626. }
  13627. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13628. this._pivotMatrix.m[12] = -point.x;
  13629. this._pivotMatrix.m[13] = -point.y;
  13630. this._pivotMatrix.m[14] = -point.z;
  13631. this._cache.pivotMatrixUpdated = true;
  13632. return this;
  13633. };
  13634. /**
  13635. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13636. */
  13637. TransformNode.prototype.getPivotPoint = function () {
  13638. var point = BABYLON.Vector3.Zero();
  13639. this.getPivotPointToRef(point);
  13640. return point;
  13641. };
  13642. /**
  13643. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13644. * Returns the AbstractMesh.
  13645. */
  13646. TransformNode.prototype.getPivotPointToRef = function (result) {
  13647. result.x = -this._pivotMatrix.m[12];
  13648. result.y = -this._pivotMatrix.m[13];
  13649. result.z = -this._pivotMatrix.m[14];
  13650. return this;
  13651. };
  13652. /**
  13653. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13654. */
  13655. TransformNode.prototype.getAbsolutePivotPoint = function () {
  13656. var point = BABYLON.Vector3.Zero();
  13657. this.getAbsolutePivotPointToRef(point);
  13658. return point;
  13659. };
  13660. /**
  13661. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13662. * Returns the AbstractMesh.
  13663. */
  13664. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  13665. result.x = this._pivotMatrix.m[12];
  13666. result.y = this._pivotMatrix.m[13];
  13667. result.z = this._pivotMatrix.m[14];
  13668. this.getPivotPointToRef(result);
  13669. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13670. return this;
  13671. };
  13672. /**
  13673. * Defines the passed node as the parent of the current node.
  13674. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  13675. * Returns the TransformNode.
  13676. */
  13677. TransformNode.prototype.setParent = function (node) {
  13678. if (node == null) {
  13679. var rotation = BABYLON.Tmp.Quaternion[0];
  13680. var position = BABYLON.Tmp.Vector3[0];
  13681. var scale = BABYLON.Tmp.Vector3[1];
  13682. if (this.parent && this.parent.computeWorldMatrix) {
  13683. this.parent.computeWorldMatrix(true);
  13684. }
  13685. this.computeWorldMatrix(true);
  13686. this.getWorldMatrix().decompose(scale, rotation, position);
  13687. if (this.rotationQuaternion) {
  13688. this.rotationQuaternion.copyFrom(rotation);
  13689. }
  13690. else {
  13691. rotation.toEulerAnglesToRef(this.rotation);
  13692. }
  13693. this.scaling.x = scale.x;
  13694. this.scaling.y = scale.y;
  13695. this.scaling.z = scale.z;
  13696. this.position.x = position.x;
  13697. this.position.y = position.y;
  13698. this.position.z = position.z;
  13699. }
  13700. else {
  13701. var rotation = BABYLON.Tmp.Quaternion[0];
  13702. var position = BABYLON.Tmp.Vector3[0];
  13703. var scale = BABYLON.Tmp.Vector3[1];
  13704. var diffMatrix = BABYLON.Tmp.Matrix[0];
  13705. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  13706. this.computeWorldMatrix(true);
  13707. node.computeWorldMatrix(true);
  13708. node.getWorldMatrix().invertToRef(invParentMatrix);
  13709. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  13710. diffMatrix.decompose(scale, rotation, position);
  13711. if (this.rotationQuaternion) {
  13712. this.rotationQuaternion.copyFrom(rotation);
  13713. }
  13714. else {
  13715. rotation.toEulerAnglesToRef(this.rotation);
  13716. }
  13717. this.position.x = position.x;
  13718. this.position.y = position.y;
  13719. this.position.z = position.z;
  13720. this.scaling.x = scale.x;
  13721. this.scaling.y = scale.y;
  13722. this.scaling.z = scale.z;
  13723. }
  13724. this.parent = node;
  13725. return this;
  13726. };
  13727. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  13728. get: function () {
  13729. return this._nonUniformScaling;
  13730. },
  13731. enumerable: true,
  13732. configurable: true
  13733. });
  13734. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  13735. if (this._nonUniformScaling === value) {
  13736. return false;
  13737. }
  13738. this._nonUniformScaling = true;
  13739. return true;
  13740. };
  13741. /**
  13742. * Attach the current TransformNode to another TransformNode associated with a bone
  13743. * @param bone Bone affecting the TransformNode
  13744. * @param affectedTransformNode TransformNode associated with the bone
  13745. */
  13746. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  13747. this._transformToBoneReferal = affectedTransformNode;
  13748. this.parent = bone;
  13749. if (bone.getWorldMatrix().determinant() < 0) {
  13750. this.scalingDeterminant *= -1;
  13751. }
  13752. return this;
  13753. };
  13754. TransformNode.prototype.detachFromBone = function () {
  13755. if (!this.parent) {
  13756. return this;
  13757. }
  13758. if (this.parent.getWorldMatrix().determinant() < 0) {
  13759. this.scalingDeterminant *= -1;
  13760. }
  13761. this._transformToBoneReferal = null;
  13762. this.parent = null;
  13763. return this;
  13764. };
  13765. /**
  13766. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  13767. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13768. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13769. * The passed axis is also normalized.
  13770. * Returns the AbstractMesh.
  13771. */
  13772. TransformNode.prototype.rotate = function (axis, amount, space) {
  13773. axis.normalize();
  13774. if (!this.rotationQuaternion) {
  13775. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13776. this.rotation = BABYLON.Vector3.Zero();
  13777. }
  13778. var rotationQuaternion;
  13779. if (!space || space === BABYLON.Space.LOCAL) {
  13780. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  13781. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  13782. }
  13783. else {
  13784. if (this.parent) {
  13785. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13786. invertParentWorldMatrix.invert();
  13787. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  13788. }
  13789. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  13790. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13791. }
  13792. return this;
  13793. };
  13794. /**
  13795. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  13796. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13797. * The passed axis is also normalized.
  13798. * Returns the AbstractMesh.
  13799. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  13800. */
  13801. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  13802. axis.normalize();
  13803. if (!this.rotationQuaternion) {
  13804. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13805. this.rotation.copyFromFloats(0, 0, 0);
  13806. }
  13807. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  13808. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  13809. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  13810. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  13811. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  13812. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  13813. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  13814. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  13815. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13816. return this;
  13817. };
  13818. /**
  13819. * Translates the mesh along the axis vector for the passed distance in the given space.
  13820. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13821. * Returns the AbstractMesh.
  13822. */
  13823. TransformNode.prototype.translate = function (axis, distance, space) {
  13824. var displacementVector = axis.scale(distance);
  13825. if (!space || space === BABYLON.Space.LOCAL) {
  13826. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  13827. this.setPositionWithLocalVector(tempV3);
  13828. }
  13829. else {
  13830. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  13831. }
  13832. return this;
  13833. };
  13834. /**
  13835. * Adds a rotation step to the mesh current rotation.
  13836. * x, y, z are Euler angles expressed in radians.
  13837. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  13838. * This means this rotation is made in the mesh local space only.
  13839. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  13840. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  13841. * ```javascript
  13842. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  13843. * ```
  13844. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  13845. * 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.
  13846. * Returns the AbstractMesh.
  13847. */
  13848. TransformNode.prototype.addRotation = function (x, y, z) {
  13849. var rotationQuaternion;
  13850. if (this.rotationQuaternion) {
  13851. rotationQuaternion = this.rotationQuaternion;
  13852. }
  13853. else {
  13854. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  13855. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  13856. }
  13857. var accumulation = BABYLON.Tmp.Quaternion[0];
  13858. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  13859. rotationQuaternion.multiplyInPlace(accumulation);
  13860. if (!this.rotationQuaternion) {
  13861. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  13862. }
  13863. return this;
  13864. };
  13865. /**
  13866. * Computes the mesh World matrix and returns it.
  13867. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  13868. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  13869. * If the parameter `force`is set to `true`, the actual computation is done.
  13870. * Returns the mesh World Matrix.
  13871. */
  13872. TransformNode.prototype.computeWorldMatrix = function (force) {
  13873. if (this._isWorldMatrixFrozen) {
  13874. return this._worldMatrix;
  13875. }
  13876. if (!force && this.isSynchronized(true)) {
  13877. return this._worldMatrix;
  13878. }
  13879. this._cache.position.copyFrom(this.position);
  13880. this._cache.scaling.copyFrom(this.scaling);
  13881. this._cache.pivotMatrixUpdated = false;
  13882. this._cache.billboardMode = this.billboardMode;
  13883. this._currentRenderId = this.getScene().getRenderId();
  13884. this._isDirty = false;
  13885. // Scaling
  13886. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  13887. // Rotation
  13888. //rotate, if quaternion is set and rotation was used
  13889. if (this.rotationQuaternion) {
  13890. var len = this.rotation.length();
  13891. if (len) {
  13892. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  13893. this.rotation.copyFromFloats(0, 0, 0);
  13894. }
  13895. }
  13896. if (this.rotationQuaternion) {
  13897. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  13898. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13899. }
  13900. else {
  13901. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  13902. this._cache.rotation.copyFrom(this.rotation);
  13903. }
  13904. // Translation
  13905. var camera = this.getScene().activeCamera;
  13906. if (this.infiniteDistance && !this.parent && camera) {
  13907. var cameraWorldMatrix = camera.getWorldMatrix();
  13908. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  13909. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  13910. }
  13911. else {
  13912. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  13913. }
  13914. // Composing transformations
  13915. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  13916. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13917. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  13918. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  13919. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  13920. // Need to decompose each rotation here
  13921. var currentPosition = BABYLON.Tmp.Vector3[3];
  13922. if (this.parent && this.parent.getWorldMatrix) {
  13923. if (this._transformToBoneReferal) {
  13924. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13925. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  13926. }
  13927. else {
  13928. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  13929. }
  13930. }
  13931. else {
  13932. currentPosition.copyFrom(this.position);
  13933. }
  13934. currentPosition.subtractInPlace(camera.globalPosition);
  13935. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  13936. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  13937. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  13938. }
  13939. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  13940. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  13941. }
  13942. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  13943. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  13944. }
  13945. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  13946. }
  13947. else {
  13948. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  13949. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  13950. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  13951. }
  13952. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  13953. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13954. }
  13955. // Local world
  13956. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  13957. // Parent
  13958. if (this.parent && this.parent.getWorldMatrix) {
  13959. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  13960. if (this._transformToBoneReferal) {
  13961. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13962. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  13963. }
  13964. else {
  13965. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  13966. }
  13967. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  13968. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  13969. this._worldMatrix.copyFrom(this._localWorld);
  13970. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  13971. }
  13972. else {
  13973. if (this._transformToBoneReferal) {
  13974. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13975. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  13976. }
  13977. else {
  13978. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  13979. }
  13980. }
  13981. this._markSyncedWithParent();
  13982. }
  13983. else {
  13984. this._worldMatrix.copyFrom(this._localWorld);
  13985. }
  13986. // Post multiply inverse of pivotMatrix
  13987. if (this._postMultiplyPivotMatrix) {
  13988. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  13989. }
  13990. // Normal matrix
  13991. if (this.scaling.isNonUniform) {
  13992. this._updateNonUniformScalingState(true);
  13993. }
  13994. else if (this.parent && this.parent._nonUniformScaling) {
  13995. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  13996. }
  13997. else {
  13998. this._updateNonUniformScalingState(false);
  13999. }
  14000. this._afterComputeWorldMatrix();
  14001. // Absolute position
  14002. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  14003. // Callbacks
  14004. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  14005. if (!this._poseMatrix) {
  14006. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  14007. }
  14008. return this._worldMatrix;
  14009. };
  14010. TransformNode.prototype._afterComputeWorldMatrix = function () {
  14011. };
  14012. /**
  14013. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  14014. * @param func: callback function to add
  14015. *
  14016. * Returns the TransformNode.
  14017. */
  14018. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  14019. this.onAfterWorldMatrixUpdateObservable.add(func);
  14020. return this;
  14021. };
  14022. /**
  14023. * Removes a registered callback function.
  14024. * Returns the TransformNode.
  14025. */
  14026. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  14027. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  14028. return this;
  14029. };
  14030. /**
  14031. * Clone the current transform node
  14032. * Returns the new transform node
  14033. * @param name Name of the new clone
  14034. * @param newParent New parent for the clone
  14035. * @param doNotCloneChildren Do not clone children hierarchy
  14036. */
  14037. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14038. var _this = this;
  14039. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  14040. result.name = name;
  14041. result.id = name;
  14042. if (newParent) {
  14043. result.parent = newParent;
  14044. }
  14045. if (!doNotCloneChildren) {
  14046. // Children
  14047. var directDescendants = this.getDescendants(true);
  14048. for (var index = 0; index < directDescendants.length; index++) {
  14049. var child = directDescendants[index];
  14050. if (child.clone) {
  14051. child.clone(name + "." + child.name, result);
  14052. }
  14053. }
  14054. }
  14055. return result;
  14056. };
  14057. TransformNode.prototype.serialize = function (currentSerializationObject) {
  14058. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  14059. serializationObject.type = this.getClassName();
  14060. // Parent
  14061. if (this.parent) {
  14062. serializationObject.parentId = this.parent.id;
  14063. }
  14064. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  14065. serializationObject.tags = BABYLON.Tags.GetTags(this);
  14066. }
  14067. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  14068. serializationObject.isEnabled = this.isEnabled();
  14069. // Parent
  14070. if (this.parent) {
  14071. serializationObject.parentId = this.parent.id;
  14072. }
  14073. return serializationObject;
  14074. };
  14075. // Statics
  14076. /**
  14077. * Returns a new TransformNode object parsed from the source provided.
  14078. * The parameter `parsedMesh` is the source.
  14079. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  14080. */
  14081. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  14082. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  14083. if (BABYLON.Tags) {
  14084. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  14085. }
  14086. if (parsedTransformNode.localMatrix) {
  14087. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  14088. }
  14089. else if (parsedTransformNode.pivotMatrix) {
  14090. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  14091. }
  14092. transformNode.setEnabled(parsedTransformNode.isEnabled);
  14093. // Parent
  14094. if (parsedTransformNode.parentId) {
  14095. transformNode._waitingParentId = parsedTransformNode.parentId;
  14096. }
  14097. return transformNode;
  14098. };
  14099. /**
  14100. * Disposes the TransformNode.
  14101. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  14102. * Returns nothing.
  14103. */
  14104. TransformNode.prototype.dispose = function (doNotRecurse) {
  14105. // Animations
  14106. this.getScene().stopAnimation(this);
  14107. // Remove from scene
  14108. this.getScene().removeTransformNode(this);
  14109. this._cache = {};
  14110. if (!doNotRecurse) {
  14111. // Children
  14112. var objects = this.getDescendants(true);
  14113. for (var index = 0; index < objects.length; index++) {
  14114. objects[index].dispose();
  14115. }
  14116. }
  14117. else {
  14118. var childMeshes = this.getChildMeshes(true);
  14119. for (index = 0; index < childMeshes.length; index++) {
  14120. var child = childMeshes[index];
  14121. child.parent = null;
  14122. child.computeWorldMatrix(true);
  14123. }
  14124. }
  14125. this.onAfterWorldMatrixUpdateObservable.clear();
  14126. _super.prototype.dispose.call(this);
  14127. };
  14128. // Statics
  14129. TransformNode.BILLBOARDMODE_NONE = 0;
  14130. TransformNode.BILLBOARDMODE_X = 1;
  14131. TransformNode.BILLBOARDMODE_Y = 2;
  14132. TransformNode.BILLBOARDMODE_Z = 4;
  14133. TransformNode.BILLBOARDMODE_ALL = 7;
  14134. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  14135. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  14136. __decorate([
  14137. BABYLON.serializeAsVector3()
  14138. ], TransformNode.prototype, "_rotation", void 0);
  14139. __decorate([
  14140. BABYLON.serializeAsQuaternion()
  14141. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  14142. __decorate([
  14143. BABYLON.serializeAsVector3()
  14144. ], TransformNode.prototype, "_scaling", void 0);
  14145. __decorate([
  14146. BABYLON.serialize()
  14147. ], TransformNode.prototype, "billboardMode", void 0);
  14148. __decorate([
  14149. BABYLON.serialize()
  14150. ], TransformNode.prototype, "scalingDeterminant", void 0);
  14151. __decorate([
  14152. BABYLON.serialize()
  14153. ], TransformNode.prototype, "infiniteDistance", void 0);
  14154. __decorate([
  14155. BABYLON.serializeAsVector3()
  14156. ], TransformNode.prototype, "position", void 0);
  14157. return TransformNode;
  14158. }(BABYLON.Node));
  14159. BABYLON.TransformNode = TransformNode;
  14160. })(BABYLON || (BABYLON = {}));
  14161. //# sourceMappingURL=babylon.transformNode.js.map
  14162. var BABYLON;
  14163. (function (BABYLON) {
  14164. var AbstractMesh = /** @class */ (function (_super) {
  14165. __extends(AbstractMesh, _super);
  14166. // Constructor
  14167. function AbstractMesh(name, scene) {
  14168. if (scene === void 0) { scene = null; }
  14169. var _this = _super.call(this, name, scene, false) || this;
  14170. _this._facetNb = 0; // facet number
  14171. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  14172. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  14173. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  14174. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  14175. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  14176. _this._subDiv = {
  14177. max: 1,
  14178. X: 1,
  14179. Y: 1,
  14180. Z: 1
  14181. };
  14182. _this._facetDepthSort = false; // is the facet depth sort to be computed
  14183. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  14184. // Events
  14185. /**
  14186. * An event triggered when this mesh collides with another one
  14187. * @type {BABYLON.Observable}
  14188. */
  14189. _this.onCollideObservable = new BABYLON.Observable();
  14190. /**
  14191. * An event triggered when the collision's position changes
  14192. * @type {BABYLON.Observable}
  14193. */
  14194. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  14195. /**
  14196. * An event triggered when material is changed
  14197. * @type {BABYLON.Observable}
  14198. */
  14199. _this.onMaterialChangedObservable = new BABYLON.Observable();
  14200. // Properties
  14201. _this.definedFacingForward = true; // orientation for POV movement & rotation
  14202. /**
  14203. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  14204. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  14205. * or
  14206. * 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.
  14207. * for more info check WebGl documentations
  14208. */
  14209. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  14210. /**
  14211. * 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:
  14212. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  14213. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  14214. * 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.
  14215. */
  14216. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  14217. /**
  14218. * 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.
  14219. * The default value is -1 which means don't break the query and wait till the result.
  14220. */
  14221. _this.occlusionRetryCount = -1;
  14222. _this._occlusionInternalRetryCounter = 0;
  14223. _this._isOccluded = false;
  14224. _this._isOcclusionQueryInProgress = false;
  14225. _this.visibility = 1.0;
  14226. _this.alphaIndex = Number.MAX_VALUE;
  14227. _this.isVisible = true;
  14228. _this.isPickable = true;
  14229. _this.showBoundingBox = false;
  14230. _this.showSubMeshesBoundingBox = false;
  14231. _this.isBlocker = false;
  14232. _this.enablePointerMoveEvents = false;
  14233. _this.renderingGroupId = 0;
  14234. _this._receiveShadows = false;
  14235. _this.renderOutline = false;
  14236. _this.outlineColor = BABYLON.Color3.Red();
  14237. _this.outlineWidth = 0.02;
  14238. _this.renderOverlay = false;
  14239. _this.overlayColor = BABYLON.Color3.Red();
  14240. _this.overlayAlpha = 0.5;
  14241. _this._hasVertexAlpha = false;
  14242. _this._useVertexColors = true;
  14243. _this._computeBonesUsingShaders = true;
  14244. _this._numBoneInfluencers = 4;
  14245. _this._applyFog = true;
  14246. _this.useOctreeForRenderingSelection = true;
  14247. _this.useOctreeForPicking = true;
  14248. _this.useOctreeForCollisions = true;
  14249. _this._layerMask = 0x0FFFFFFF;
  14250. /**
  14251. * True if the mesh must be rendered in any case.
  14252. */
  14253. _this.alwaysSelectAsActiveMesh = false;
  14254. /**
  14255. * This scene's action manager
  14256. * @type {BABYLON.ActionManager}
  14257. */
  14258. _this.actionManager = null;
  14259. // Physics
  14260. _this.physicsImpostor = null;
  14261. // Collisions
  14262. _this._checkCollisions = false;
  14263. _this._collisionMask = -1;
  14264. _this._collisionGroup = -1;
  14265. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  14266. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  14267. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  14268. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  14269. // Edges
  14270. _this.edgesWidth = 1;
  14271. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  14272. // Cache
  14273. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  14274. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  14275. _this._isDisposed = false;
  14276. _this._renderId = 0;
  14277. _this._intersectionsInProgress = new Array();
  14278. _this._unIndexed = false;
  14279. _this._lightSources = new Array();
  14280. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14281. if (collidedMesh === void 0) { collidedMesh = null; }
  14282. //TODO move this to the collision coordinator!
  14283. if (_this.getScene().workerCollisions)
  14284. newPosition.multiplyInPlace(_this._collider._radius);
  14285. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  14286. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  14287. _this.position.addInPlace(_this._diffPositionForCollisions);
  14288. }
  14289. if (collidedMesh) {
  14290. _this.onCollideObservable.notifyObservers(collidedMesh);
  14291. }
  14292. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  14293. };
  14294. _this.getScene().addMesh(_this);
  14295. _this._resyncLightSources();
  14296. return _this;
  14297. }
  14298. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  14299. get: function () {
  14300. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  14301. },
  14302. enumerable: true,
  14303. configurable: true
  14304. });
  14305. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  14306. get: function () {
  14307. return BABYLON.TransformNode.BILLBOARDMODE_X;
  14308. },
  14309. enumerable: true,
  14310. configurable: true
  14311. });
  14312. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  14313. get: function () {
  14314. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  14315. },
  14316. enumerable: true,
  14317. configurable: true
  14318. });
  14319. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  14320. get: function () {
  14321. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  14322. },
  14323. enumerable: true,
  14324. configurable: true
  14325. });
  14326. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  14327. get: function () {
  14328. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  14329. },
  14330. enumerable: true,
  14331. configurable: true
  14332. });
  14333. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  14334. /**
  14335. * Read-only : the number of facets in the mesh
  14336. */
  14337. get: function () {
  14338. return this._facetNb;
  14339. },
  14340. enumerable: true,
  14341. configurable: true
  14342. });
  14343. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  14344. /**
  14345. * The number (integer) of subdivisions per axis in the partioning space
  14346. */
  14347. get: function () {
  14348. return this._partitioningSubdivisions;
  14349. },
  14350. set: function (nb) {
  14351. this._partitioningSubdivisions = nb;
  14352. },
  14353. enumerable: true,
  14354. configurable: true
  14355. });
  14356. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  14357. /**
  14358. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  14359. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  14360. */
  14361. get: function () {
  14362. return this._partitioningBBoxRatio;
  14363. },
  14364. set: function (ratio) {
  14365. this._partitioningBBoxRatio = ratio;
  14366. },
  14367. enumerable: true,
  14368. configurable: true
  14369. });
  14370. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  14371. /**
  14372. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  14373. * Works only for updatable meshes.
  14374. * Doesn't work with multi-materials.
  14375. */
  14376. get: function () {
  14377. return this._facetDepthSort;
  14378. },
  14379. set: function (sort) {
  14380. this._facetDepthSort = sort;
  14381. },
  14382. enumerable: true,
  14383. configurable: true
  14384. });
  14385. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  14386. /**
  14387. * The location (Vector3) where the facet depth sort must be computed from.
  14388. * By default, the active camera position.
  14389. * Used only when facet depth sort is enabled.
  14390. */
  14391. get: function () {
  14392. return this._facetDepthSortFrom;
  14393. },
  14394. set: function (location) {
  14395. this._facetDepthSortFrom = location;
  14396. },
  14397. enumerable: true,
  14398. configurable: true
  14399. });
  14400. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  14401. /**
  14402. * Read-only boolean : is the feature facetData enabled ?
  14403. */
  14404. get: function () {
  14405. return this._facetDataEnabled;
  14406. },
  14407. enumerable: true,
  14408. configurable: true
  14409. });
  14410. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  14411. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  14412. return false;
  14413. }
  14414. this._markSubMeshesAsMiscDirty();
  14415. return true;
  14416. };
  14417. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  14418. set: function (callback) {
  14419. if (this._onCollideObserver) {
  14420. this.onCollideObservable.remove(this._onCollideObserver);
  14421. }
  14422. this._onCollideObserver = this.onCollideObservable.add(callback);
  14423. },
  14424. enumerable: true,
  14425. configurable: true
  14426. });
  14427. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  14428. set: function (callback) {
  14429. if (this._onCollisionPositionChangeObserver) {
  14430. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  14431. }
  14432. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  14433. },
  14434. enumerable: true,
  14435. configurable: true
  14436. });
  14437. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  14438. /**
  14439. * 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.
  14440. */
  14441. get: function () {
  14442. return this._isOccluded;
  14443. },
  14444. set: function (value) {
  14445. this._isOccluded = value;
  14446. },
  14447. enumerable: true,
  14448. configurable: true
  14449. });
  14450. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  14451. /**
  14452. * Flag to check the progress status of the query
  14453. */
  14454. get: function () {
  14455. return this._isOcclusionQueryInProgress;
  14456. },
  14457. enumerable: true,
  14458. configurable: true
  14459. });
  14460. Object.defineProperty(AbstractMesh.prototype, "material", {
  14461. get: function () {
  14462. return this._material;
  14463. },
  14464. set: function (value) {
  14465. if (this._material === value) {
  14466. return;
  14467. }
  14468. this._material = value;
  14469. if (this.onMaterialChangedObservable.hasObservers) {
  14470. this.onMaterialChangedObservable.notifyObservers(this);
  14471. }
  14472. if (!this.subMeshes) {
  14473. return;
  14474. }
  14475. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14476. var subMesh = _a[_i];
  14477. subMesh.setEffect(null);
  14478. }
  14479. },
  14480. enumerable: true,
  14481. configurable: true
  14482. });
  14483. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  14484. get: function () {
  14485. return this._receiveShadows;
  14486. },
  14487. set: function (value) {
  14488. if (this._receiveShadows === value) {
  14489. return;
  14490. }
  14491. this._receiveShadows = value;
  14492. this._markSubMeshesAsLightDirty();
  14493. },
  14494. enumerable: true,
  14495. configurable: true
  14496. });
  14497. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  14498. get: function () {
  14499. return this._hasVertexAlpha;
  14500. },
  14501. set: function (value) {
  14502. if (this._hasVertexAlpha === value) {
  14503. return;
  14504. }
  14505. this._hasVertexAlpha = value;
  14506. this._markSubMeshesAsAttributesDirty();
  14507. },
  14508. enumerable: true,
  14509. configurable: true
  14510. });
  14511. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  14512. get: function () {
  14513. return this._useVertexColors;
  14514. },
  14515. set: function (value) {
  14516. if (this._useVertexColors === value) {
  14517. return;
  14518. }
  14519. this._useVertexColors = value;
  14520. this._markSubMeshesAsAttributesDirty();
  14521. },
  14522. enumerable: true,
  14523. configurable: true
  14524. });
  14525. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  14526. get: function () {
  14527. return this._computeBonesUsingShaders;
  14528. },
  14529. set: function (value) {
  14530. if (this._computeBonesUsingShaders === value) {
  14531. return;
  14532. }
  14533. this._computeBonesUsingShaders = value;
  14534. this._markSubMeshesAsAttributesDirty();
  14535. },
  14536. enumerable: true,
  14537. configurable: true
  14538. });
  14539. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  14540. get: function () {
  14541. return this._numBoneInfluencers;
  14542. },
  14543. set: function (value) {
  14544. if (this._numBoneInfluencers === value) {
  14545. return;
  14546. }
  14547. this._numBoneInfluencers = value;
  14548. this._markSubMeshesAsAttributesDirty();
  14549. },
  14550. enumerable: true,
  14551. configurable: true
  14552. });
  14553. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  14554. get: function () {
  14555. return this._applyFog;
  14556. },
  14557. set: function (value) {
  14558. if (this._applyFog === value) {
  14559. return;
  14560. }
  14561. this._applyFog = value;
  14562. this._markSubMeshesAsMiscDirty();
  14563. },
  14564. enumerable: true,
  14565. configurable: true
  14566. });
  14567. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  14568. get: function () {
  14569. return this._layerMask;
  14570. },
  14571. set: function (value) {
  14572. if (value === this._layerMask) {
  14573. return;
  14574. }
  14575. this._layerMask = value;
  14576. this._resyncLightSources();
  14577. },
  14578. enumerable: true,
  14579. configurable: true
  14580. });
  14581. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  14582. get: function () {
  14583. return this._collisionMask;
  14584. },
  14585. set: function (mask) {
  14586. this._collisionMask = !isNaN(mask) ? mask : -1;
  14587. },
  14588. enumerable: true,
  14589. configurable: true
  14590. });
  14591. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  14592. get: function () {
  14593. return this._collisionGroup;
  14594. },
  14595. set: function (mask) {
  14596. this._collisionGroup = !isNaN(mask) ? mask : -1;
  14597. },
  14598. enumerable: true,
  14599. configurable: true
  14600. });
  14601. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  14602. get: function () {
  14603. return null;
  14604. },
  14605. enumerable: true,
  14606. configurable: true
  14607. });
  14608. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  14609. get: function () {
  14610. return this._skeleton;
  14611. },
  14612. set: function (value) {
  14613. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  14614. this._skeleton._unregisterMeshWithPoseMatrix(this);
  14615. }
  14616. if (value && value.needInitialSkinMatrix) {
  14617. value._registerMeshWithPoseMatrix(this);
  14618. }
  14619. this._skeleton = value;
  14620. if (!this._skeleton) {
  14621. this._bonesTransformMatrices = null;
  14622. }
  14623. this._markSubMeshesAsAttributesDirty();
  14624. },
  14625. enumerable: true,
  14626. configurable: true
  14627. });
  14628. /**
  14629. * Boolean : true if the mesh has been disposed.
  14630. */
  14631. AbstractMesh.prototype.isDisposed = function () {
  14632. return this._isDisposed;
  14633. };
  14634. /**
  14635. * Returns the string "AbstractMesh"
  14636. */
  14637. AbstractMesh.prototype.getClassName = function () {
  14638. return "AbstractMesh";
  14639. };
  14640. /**
  14641. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14642. */
  14643. AbstractMesh.prototype.toString = function (fullDetails) {
  14644. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  14645. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  14646. if (this._skeleton) {
  14647. ret += ", skeleton: " + this._skeleton.name;
  14648. }
  14649. if (fullDetails) {
  14650. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  14651. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  14652. }
  14653. return ret;
  14654. };
  14655. AbstractMesh.prototype._rebuild = function () {
  14656. if (this._occlusionQuery) {
  14657. this._occlusionQuery = null;
  14658. }
  14659. if (this._edgesRenderer) {
  14660. this._edgesRenderer._rebuild();
  14661. }
  14662. if (!this.subMeshes) {
  14663. return;
  14664. }
  14665. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14666. var subMesh = _a[_i];
  14667. subMesh._rebuild();
  14668. }
  14669. };
  14670. AbstractMesh.prototype._resyncLightSources = function () {
  14671. this._lightSources.length = 0;
  14672. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  14673. var light = _a[_i];
  14674. if (!light.isEnabled()) {
  14675. continue;
  14676. }
  14677. if (light.canAffectMesh(this)) {
  14678. this._lightSources.push(light);
  14679. }
  14680. }
  14681. this._markSubMeshesAsLightDirty();
  14682. };
  14683. AbstractMesh.prototype._resyncLighSource = function (light) {
  14684. var isIn = light.isEnabled() && light.canAffectMesh(this);
  14685. var index = this._lightSources.indexOf(light);
  14686. if (index === -1) {
  14687. if (!isIn) {
  14688. return;
  14689. }
  14690. this._lightSources.push(light);
  14691. }
  14692. else {
  14693. if (isIn) {
  14694. return;
  14695. }
  14696. this._lightSources.splice(index, 1);
  14697. }
  14698. this._markSubMeshesAsLightDirty();
  14699. };
  14700. AbstractMesh.prototype._removeLightSource = function (light) {
  14701. var index = this._lightSources.indexOf(light);
  14702. if (index === -1) {
  14703. return;
  14704. }
  14705. this._lightSources.splice(index, 1);
  14706. };
  14707. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  14708. if (!this.subMeshes) {
  14709. return;
  14710. }
  14711. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14712. var subMesh = _a[_i];
  14713. if (subMesh._materialDefines) {
  14714. func(subMesh._materialDefines);
  14715. }
  14716. }
  14717. };
  14718. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  14719. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  14720. };
  14721. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  14722. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  14723. };
  14724. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  14725. if (!this.subMeshes) {
  14726. return;
  14727. }
  14728. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14729. var subMesh = _a[_i];
  14730. var material = subMesh.getMaterial();
  14731. if (material) {
  14732. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  14733. }
  14734. }
  14735. };
  14736. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  14737. /**
  14738. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14739. * Default : (1.0, 1.0, 1.0)
  14740. */
  14741. get: function () {
  14742. return this._scaling;
  14743. },
  14744. /**
  14745. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14746. * Default : (1.0, 1.0, 1.0)
  14747. */
  14748. set: function (newScaling) {
  14749. this._scaling = newScaling;
  14750. if (this.physicsImpostor) {
  14751. this.physicsImpostor.forceUpdate();
  14752. }
  14753. },
  14754. enumerable: true,
  14755. configurable: true
  14756. });
  14757. // Methods
  14758. /**
  14759. * Disables the mesh edger rendering mode.
  14760. * Returns the AbstractMesh.
  14761. */
  14762. AbstractMesh.prototype.disableEdgesRendering = function () {
  14763. if (this._edgesRenderer) {
  14764. this._edgesRenderer.dispose();
  14765. this._edgesRenderer = null;
  14766. }
  14767. return this;
  14768. };
  14769. /**
  14770. * Enables the edge rendering mode on the mesh.
  14771. * This mode makes the mesh edges visible.
  14772. * Returns the AbstractMesh.
  14773. */
  14774. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  14775. if (epsilon === void 0) { epsilon = 0.95; }
  14776. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  14777. this.disableEdgesRendering();
  14778. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  14779. return this;
  14780. };
  14781. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  14782. /**
  14783. * Returns true if the mesh is blocked. Used by the class Mesh.
  14784. * Returns the boolean `false` by default.
  14785. */
  14786. get: function () {
  14787. return false;
  14788. },
  14789. enumerable: true,
  14790. configurable: true
  14791. });
  14792. /**
  14793. * Returns the mesh itself by default, used by the class Mesh.
  14794. * Returned type : AbstractMesh
  14795. */
  14796. AbstractMesh.prototype.getLOD = function (camera) {
  14797. return this;
  14798. };
  14799. /**
  14800. * Returns 0 by default, used by the class Mesh.
  14801. * Returns an integer.
  14802. */
  14803. AbstractMesh.prototype.getTotalVertices = function () {
  14804. return 0;
  14805. };
  14806. /**
  14807. * Returns null by default, used by the class Mesh.
  14808. * Returned type : integer array
  14809. */
  14810. AbstractMesh.prototype.getIndices = function () {
  14811. return null;
  14812. };
  14813. /**
  14814. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  14815. * Returned type : float array or Float32Array
  14816. */
  14817. AbstractMesh.prototype.getVerticesData = function (kind) {
  14818. return null;
  14819. };
  14820. /**
  14821. * Sets the vertex data of the mesh geometry for the requested `kind`.
  14822. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  14823. * The `data` are either a numeric array either a Float32Array.
  14824. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  14825. * 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).
  14826. * Note that a new underlying VertexBuffer object is created each call.
  14827. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  14828. *
  14829. * Possible `kind` values :
  14830. * - BABYLON.VertexBuffer.PositionKind
  14831. * - BABYLON.VertexBuffer.UVKind
  14832. * - BABYLON.VertexBuffer.UV2Kind
  14833. * - BABYLON.VertexBuffer.UV3Kind
  14834. * - BABYLON.VertexBuffer.UV4Kind
  14835. * - BABYLON.VertexBuffer.UV5Kind
  14836. * - BABYLON.VertexBuffer.UV6Kind
  14837. * - BABYLON.VertexBuffer.ColorKind
  14838. * - BABYLON.VertexBuffer.MatricesIndicesKind
  14839. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  14840. * - BABYLON.VertexBuffer.MatricesWeightsKind
  14841. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  14842. *
  14843. * Returns the Mesh.
  14844. */
  14845. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14846. return this;
  14847. };
  14848. /**
  14849. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  14850. * If the mesh has no geometry, it is simply returned as it is.
  14851. * The `data` are either a numeric array either a Float32Array.
  14852. * No new underlying VertexBuffer object is created.
  14853. * 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.
  14854. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  14855. *
  14856. * Possible `kind` values :
  14857. * - BABYLON.VertexBuffer.PositionKind
  14858. * - BABYLON.VertexBuffer.UVKind
  14859. * - BABYLON.VertexBuffer.UV2Kind
  14860. * - BABYLON.VertexBuffer.UV3Kind
  14861. * - BABYLON.VertexBuffer.UV4Kind
  14862. * - BABYLON.VertexBuffer.UV5Kind
  14863. * - BABYLON.VertexBuffer.UV6Kind
  14864. * - BABYLON.VertexBuffer.ColorKind
  14865. * - BABYLON.VertexBuffer.MatricesIndicesKind
  14866. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  14867. * - BABYLON.VertexBuffer.MatricesWeightsKind
  14868. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  14869. *
  14870. * Returns the Mesh.
  14871. */
  14872. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14873. return this;
  14874. };
  14875. /**
  14876. * Sets the mesh indices.
  14877. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  14878. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  14879. * This method creates a new index buffer each call.
  14880. * Returns the Mesh.
  14881. */
  14882. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  14883. return this;
  14884. };
  14885. /** Returns false by default, used by the class Mesh.
  14886. * Returns a boolean
  14887. */
  14888. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  14889. return false;
  14890. };
  14891. /**
  14892. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  14893. * Returns a BoundingInfo
  14894. */
  14895. AbstractMesh.prototype.getBoundingInfo = function () {
  14896. if (this._masterMesh) {
  14897. return this._masterMesh.getBoundingInfo();
  14898. }
  14899. if (!this._boundingInfo) {
  14900. // this._boundingInfo is being created here
  14901. this._updateBoundingInfo();
  14902. }
  14903. // cannot be null.
  14904. return this._boundingInfo;
  14905. };
  14906. /**
  14907. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  14908. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  14909. */
  14910. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  14911. if (includeDescendants === void 0) { includeDescendants = true; }
  14912. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  14913. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  14914. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  14915. if (maxDimension === 0) {
  14916. return this;
  14917. }
  14918. var scale = 1 / maxDimension;
  14919. this.scaling.scaleInPlace(scale);
  14920. return this;
  14921. };
  14922. /**
  14923. * Sets a mesh new object BoundingInfo.
  14924. * Returns the AbstractMesh.
  14925. */
  14926. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  14927. this._boundingInfo = boundingInfo;
  14928. return this;
  14929. };
  14930. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  14931. get: function () {
  14932. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  14933. },
  14934. enumerable: true,
  14935. configurable: true
  14936. });
  14937. AbstractMesh.prototype._preActivate = function () {
  14938. };
  14939. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  14940. };
  14941. AbstractMesh.prototype._activate = function (renderId) {
  14942. this._renderId = renderId;
  14943. };
  14944. /**
  14945. * Returns the latest update of the World matrix
  14946. * Returns a Matrix.
  14947. */
  14948. AbstractMesh.prototype.getWorldMatrix = function () {
  14949. if (this._masterMesh) {
  14950. return this._masterMesh.getWorldMatrix();
  14951. }
  14952. return _super.prototype.getWorldMatrix.call(this);
  14953. };
  14954. /**
  14955. * Returns the latest update of the World matrix determinant.
  14956. */
  14957. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  14958. if (this._masterMesh) {
  14959. return this._masterMesh._getWorldMatrixDeterminant();
  14960. }
  14961. return _super.prototype._getWorldMatrixDeterminant.call(this);
  14962. };
  14963. // ================================== Point of View Movement =================================
  14964. /**
  14965. * Perform relative position change from the point of view of behind the front of the mesh.
  14966. * This is performed taking into account the meshes current rotation, so you do not have to care.
  14967. * Supports definition of mesh facing forward or backward.
  14968. * @param {number} amountRight
  14969. * @param {number} amountUp
  14970. * @param {number} amountForward
  14971. *
  14972. * Returns the AbstractMesh.
  14973. */
  14974. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  14975. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  14976. return this;
  14977. };
  14978. /**
  14979. * Calculate relative position change from the point of view of behind the front of the mesh.
  14980. * This is performed taking into account the meshes current rotation, so you do not have to care.
  14981. * Supports definition of mesh facing forward or backward.
  14982. * @param {number} amountRight
  14983. * @param {number} amountUp
  14984. * @param {number} amountForward
  14985. *
  14986. * Returns a new Vector3.
  14987. */
  14988. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  14989. var rotMatrix = new BABYLON.Matrix();
  14990. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14991. rotQuaternion.toRotationMatrix(rotMatrix);
  14992. var translationDelta = BABYLON.Vector3.Zero();
  14993. var defForwardMult = this.definedFacingForward ? -1 : 1;
  14994. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  14995. return translationDelta;
  14996. };
  14997. // ================================== Point of View Rotation =================================
  14998. /**
  14999. * Perform relative rotation change from the point of view of behind the front of the mesh.
  15000. * Supports definition of mesh facing forward or backward.
  15001. * @param {number} flipBack
  15002. * @param {number} twirlClockwise
  15003. * @param {number} tiltRight
  15004. *
  15005. * Returns the AbstractMesh.
  15006. */
  15007. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  15008. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  15009. return this;
  15010. };
  15011. /**
  15012. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  15013. * Supports definition of mesh facing forward or backward.
  15014. * @param {number} flipBack
  15015. * @param {number} twirlClockwise
  15016. * @param {number} tiltRight
  15017. *
  15018. * Returns a new Vector3.
  15019. */
  15020. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  15021. var defForwardMult = this.definedFacingForward ? 1 : -1;
  15022. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  15023. };
  15024. /**
  15025. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  15026. * @param includeDescendants Include bounding info from descendants as well (true by default).
  15027. */
  15028. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  15029. if (includeDescendants === void 0) { includeDescendants = true; }
  15030. this.computeWorldMatrix(true);
  15031. var min;
  15032. var max;
  15033. var boundingInfo = this.getBoundingInfo();
  15034. if (!this.subMeshes) {
  15035. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15036. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  15037. }
  15038. else {
  15039. min = boundingInfo.boundingBox.minimumWorld;
  15040. max = boundingInfo.boundingBox.maximumWorld;
  15041. }
  15042. if (includeDescendants) {
  15043. var descendants = this.getDescendants(false);
  15044. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  15045. var descendant = descendants_1[_i];
  15046. var childMesh = descendant;
  15047. childMesh.computeWorldMatrix(true);
  15048. //make sure we have the needed params to get mix and max
  15049. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  15050. continue;
  15051. }
  15052. var childBoundingInfo = childMesh.getBoundingInfo();
  15053. var boundingBox = childBoundingInfo.boundingBox;
  15054. var minBox = boundingBox.minimumWorld;
  15055. var maxBox = boundingBox.maximumWorld;
  15056. BABYLON.Tools.CheckExtends(minBox, min, max);
  15057. BABYLON.Tools.CheckExtends(maxBox, min, max);
  15058. }
  15059. }
  15060. return {
  15061. min: min,
  15062. max: max
  15063. };
  15064. };
  15065. /**
  15066. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  15067. * Returns the AbstractMesh.
  15068. */
  15069. AbstractMesh.prototype._updateBoundingInfo = function () {
  15070. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  15071. this._boundingInfo.update(this.worldMatrixFromCache);
  15072. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  15073. return this;
  15074. };
  15075. /**
  15076. * Update a mesh's children BoundingInfo objects only.
  15077. * Returns the AbstractMesh.
  15078. */
  15079. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  15080. if (!this.subMeshes) {
  15081. return this;
  15082. }
  15083. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  15084. var subMesh = this.subMeshes[subIndex];
  15085. if (!subMesh.IsGlobal) {
  15086. subMesh.updateBoundingInfo(matrix);
  15087. }
  15088. }
  15089. return this;
  15090. };
  15091. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  15092. // Bounding info
  15093. this._updateBoundingInfo();
  15094. };
  15095. /**
  15096. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  15097. * A mesh is in the frustum if its bounding box intersects the frustum.
  15098. * Boolean returned.
  15099. */
  15100. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  15101. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  15102. };
  15103. /**
  15104. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  15105. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  15106. * Boolean returned.
  15107. */
  15108. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15109. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  15110. ;
  15111. };
  15112. /**
  15113. * True if the mesh intersects another mesh or a SolidParticle object.
  15114. * 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)
  15115. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  15116. * Returns a boolean.
  15117. */
  15118. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  15119. if (precise === void 0) { precise = false; }
  15120. if (!this._boundingInfo || !mesh._boundingInfo) {
  15121. return false;
  15122. }
  15123. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  15124. return true;
  15125. }
  15126. if (includeDescendants) {
  15127. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  15128. var child = _a[_i];
  15129. if (child.intersectsMesh(mesh, precise, true)) {
  15130. return true;
  15131. }
  15132. }
  15133. }
  15134. return false;
  15135. };
  15136. /**
  15137. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  15138. * Returns a boolean.
  15139. */
  15140. AbstractMesh.prototype.intersectsPoint = function (point) {
  15141. if (!this._boundingInfo) {
  15142. return false;
  15143. }
  15144. return this._boundingInfo.intersectsPoint(point);
  15145. };
  15146. AbstractMesh.prototype.getPhysicsImpostor = function () {
  15147. return this.physicsImpostor;
  15148. };
  15149. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  15150. if (camera === void 0) { camera = null; }
  15151. if (!camera) {
  15152. camera = this.getScene().activeCamera;
  15153. }
  15154. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  15155. };
  15156. /**
  15157. * Returns the distance from the mesh to the active camera.
  15158. * Returns a float.
  15159. */
  15160. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  15161. if (camera === void 0) { camera = null; }
  15162. if (!camera) {
  15163. camera = this.getScene().activeCamera;
  15164. }
  15165. return this.absolutePosition.subtract(camera.position).length();
  15166. };
  15167. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  15168. if (!this.physicsImpostor) {
  15169. return this;
  15170. }
  15171. this.physicsImpostor.applyImpulse(force, contactPoint);
  15172. return this;
  15173. };
  15174. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  15175. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  15176. return this;
  15177. }
  15178. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  15179. mainPivot: pivot1,
  15180. connectedPivot: pivot2,
  15181. nativeParams: options
  15182. });
  15183. return this;
  15184. };
  15185. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  15186. // Collisions
  15187. /**
  15188. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  15189. * Default `false`.
  15190. */
  15191. get: function () {
  15192. return this._checkCollisions;
  15193. },
  15194. set: function (collisionEnabled) {
  15195. this._checkCollisions = collisionEnabled;
  15196. if (this.getScene().workerCollisions) {
  15197. this.getScene().collisionCoordinator.onMeshUpdated(this);
  15198. }
  15199. },
  15200. enumerable: true,
  15201. configurable: true
  15202. });
  15203. Object.defineProperty(AbstractMesh.prototype, "collider", {
  15204. /**
  15205. * Gets Collider object used to compute collisions (not physics)
  15206. */
  15207. get: function () {
  15208. return this._collider;
  15209. },
  15210. enumerable: true,
  15211. configurable: true
  15212. });
  15213. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  15214. var globalPosition = this.getAbsolutePosition();
  15215. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  15216. if (!this._collider) {
  15217. this._collider = new BABYLON.Collider();
  15218. }
  15219. this._collider._radius = this.ellipsoid;
  15220. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  15221. return this;
  15222. };
  15223. // Submeshes octree
  15224. /**
  15225. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  15226. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  15227. * Returns an Octree of submeshes.
  15228. */
  15229. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  15230. if (maxCapacity === void 0) { maxCapacity = 64; }
  15231. if (maxDepth === void 0) { maxDepth = 2; }
  15232. if (!this._submeshesOctree) {
  15233. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  15234. }
  15235. this.computeWorldMatrix(true);
  15236. var boundingInfo = this.getBoundingInfo();
  15237. // Update octree
  15238. var bbox = boundingInfo.boundingBox;
  15239. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  15240. return this._submeshesOctree;
  15241. };
  15242. // Collisions
  15243. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  15244. this._generatePointsArray();
  15245. if (!this._positions) {
  15246. return this;
  15247. }
  15248. // Transformation
  15249. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  15250. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  15251. subMesh._lastColliderWorldVertices = [];
  15252. subMesh._trianglePlanes = [];
  15253. var start = subMesh.verticesStart;
  15254. var end = (subMesh.verticesStart + subMesh.verticesCount);
  15255. for (var i = start; i < end; i++) {
  15256. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  15257. }
  15258. }
  15259. // Collide
  15260. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  15261. if (collider.collisionFound) {
  15262. collider.collidedMesh = this;
  15263. }
  15264. return this;
  15265. };
  15266. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  15267. var subMeshes;
  15268. var len;
  15269. // Octrees
  15270. if (this._submeshesOctree && this.useOctreeForCollisions) {
  15271. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  15272. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  15273. len = intersections.length;
  15274. subMeshes = intersections.data;
  15275. }
  15276. else {
  15277. subMeshes = this.subMeshes;
  15278. len = subMeshes.length;
  15279. }
  15280. for (var index = 0; index < len; index++) {
  15281. var subMesh = subMeshes[index];
  15282. // Bounding test
  15283. if (len > 1 && !subMesh._checkCollision(collider))
  15284. continue;
  15285. this._collideForSubMesh(subMesh, transformMatrix, collider);
  15286. }
  15287. return this;
  15288. };
  15289. AbstractMesh.prototype._checkCollision = function (collider) {
  15290. // Bounding box test
  15291. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  15292. return this;
  15293. // Transformation matrix
  15294. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  15295. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  15296. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  15297. return this;
  15298. };
  15299. // Picking
  15300. AbstractMesh.prototype._generatePointsArray = function () {
  15301. return false;
  15302. };
  15303. /**
  15304. * Checks if the passed Ray intersects with the mesh.
  15305. * Returns an object PickingInfo.
  15306. */
  15307. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  15308. var pickingInfo = new BABYLON.PickingInfo();
  15309. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  15310. return pickingInfo;
  15311. }
  15312. if (!this._generatePointsArray()) {
  15313. return pickingInfo;
  15314. }
  15315. var intersectInfo = null;
  15316. // Octrees
  15317. var subMeshes;
  15318. var len;
  15319. if (this._submeshesOctree && this.useOctreeForPicking) {
  15320. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  15321. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  15322. len = intersections.length;
  15323. subMeshes = intersections.data;
  15324. }
  15325. else {
  15326. subMeshes = this.subMeshes;
  15327. len = subMeshes.length;
  15328. }
  15329. for (var index = 0; index < len; index++) {
  15330. var subMesh = subMeshes[index];
  15331. // Bounding test
  15332. if (len > 1 && !subMesh.canIntersects(ray))
  15333. continue;
  15334. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  15335. if (currentIntersectInfo) {
  15336. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  15337. intersectInfo = currentIntersectInfo;
  15338. intersectInfo.subMeshId = index;
  15339. if (fastCheck) {
  15340. break;
  15341. }
  15342. }
  15343. }
  15344. }
  15345. if (intersectInfo) {
  15346. // Get picked point
  15347. var world = this.getWorldMatrix();
  15348. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  15349. var direction = ray.direction.clone();
  15350. direction = direction.scale(intersectInfo.distance);
  15351. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  15352. var pickedPoint = worldOrigin.add(worldDirection);
  15353. // Return result
  15354. pickingInfo.hit = true;
  15355. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  15356. pickingInfo.pickedPoint = pickedPoint;
  15357. pickingInfo.pickedMesh = this;
  15358. pickingInfo.bu = intersectInfo.bu || 0;
  15359. pickingInfo.bv = intersectInfo.bv || 0;
  15360. pickingInfo.faceId = intersectInfo.faceId;
  15361. pickingInfo.subMeshId = intersectInfo.subMeshId;
  15362. return pickingInfo;
  15363. }
  15364. return pickingInfo;
  15365. };
  15366. /**
  15367. * Clones the mesh, used by the class Mesh.
  15368. * Just returns `null` for an AbstractMesh.
  15369. */
  15370. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15371. return null;
  15372. };
  15373. /**
  15374. * Disposes all the mesh submeshes.
  15375. * Returns the AbstractMesh.
  15376. */
  15377. AbstractMesh.prototype.releaseSubMeshes = function () {
  15378. if (this.subMeshes) {
  15379. while (this.subMeshes.length) {
  15380. this.subMeshes[0].dispose();
  15381. }
  15382. }
  15383. else {
  15384. this.subMeshes = new Array();
  15385. }
  15386. return this;
  15387. };
  15388. /**
  15389. * Disposes the AbstractMesh.
  15390. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15391. * Returns nothing.
  15392. */
  15393. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  15394. var _this = this;
  15395. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  15396. var index;
  15397. // Action manager
  15398. if (this.actionManager) {
  15399. this.actionManager.dispose();
  15400. this.actionManager = null;
  15401. }
  15402. // Skeleton
  15403. this.skeleton = null;
  15404. // Physics
  15405. if (this.physicsImpostor) {
  15406. this.physicsImpostor.dispose();
  15407. }
  15408. // Intersections in progress
  15409. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  15410. var other = this._intersectionsInProgress[index];
  15411. var pos = other._intersectionsInProgress.indexOf(this);
  15412. other._intersectionsInProgress.splice(pos, 1);
  15413. }
  15414. this._intersectionsInProgress = [];
  15415. // Lights
  15416. var lights = this.getScene().lights;
  15417. lights.forEach(function (light) {
  15418. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  15419. if (meshIndex !== -1) {
  15420. light.includedOnlyMeshes.splice(meshIndex, 1);
  15421. }
  15422. meshIndex = light.excludedMeshes.indexOf(_this);
  15423. if (meshIndex !== -1) {
  15424. light.excludedMeshes.splice(meshIndex, 1);
  15425. }
  15426. // Shadow generators
  15427. var generator = light.getShadowGenerator();
  15428. if (generator) {
  15429. var shadowMap = generator.getShadowMap();
  15430. if (shadowMap && shadowMap.renderList) {
  15431. meshIndex = shadowMap.renderList.indexOf(_this);
  15432. if (meshIndex !== -1) {
  15433. shadowMap.renderList.splice(meshIndex, 1);
  15434. }
  15435. }
  15436. }
  15437. });
  15438. // Edges
  15439. if (this._edgesRenderer) {
  15440. this._edgesRenderer.dispose();
  15441. this._edgesRenderer = null;
  15442. }
  15443. // SubMeshes
  15444. if (this.getClassName() !== "InstancedMesh") {
  15445. this.releaseSubMeshes();
  15446. }
  15447. // Octree
  15448. var sceneOctree = this.getScene().selectionOctree;
  15449. if (sceneOctree) {
  15450. var index = sceneOctree.dynamicContent.indexOf(this);
  15451. if (index !== -1) {
  15452. sceneOctree.dynamicContent.splice(index, 1);
  15453. }
  15454. }
  15455. // Query
  15456. var engine = this.getScene().getEngine();
  15457. if (this._occlusionQuery) {
  15458. this._isOcclusionQueryInProgress = false;
  15459. engine.deleteQuery(this._occlusionQuery);
  15460. this._occlusionQuery = null;
  15461. }
  15462. // Engine
  15463. engine.wipeCaches();
  15464. // Remove from scene
  15465. this.getScene().removeMesh(this);
  15466. if (disposeMaterialAndTextures) {
  15467. if (this.material) {
  15468. this.material.dispose(false, true);
  15469. }
  15470. }
  15471. if (!doNotRecurse) {
  15472. // Particles
  15473. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  15474. if (this.getScene().particleSystems[index].emitter === this) {
  15475. this.getScene().particleSystems[index].dispose();
  15476. index--;
  15477. }
  15478. }
  15479. }
  15480. // facet data
  15481. if (this._facetDataEnabled) {
  15482. this.disableFacetData();
  15483. }
  15484. this.onAfterWorldMatrixUpdateObservable.clear();
  15485. this.onCollideObservable.clear();
  15486. this.onCollisionPositionChangeObservable.clear();
  15487. this._isDisposed = true;
  15488. _super.prototype.dispose.call(this, doNotRecurse);
  15489. };
  15490. /**
  15491. * Adds the passed mesh as a child to the current mesh.
  15492. * Returns the AbstractMesh.
  15493. */
  15494. AbstractMesh.prototype.addChild = function (mesh) {
  15495. mesh.setParent(this);
  15496. return this;
  15497. };
  15498. /**
  15499. * Removes the passed mesh from the current mesh children list.
  15500. * Returns the AbstractMesh.
  15501. */
  15502. AbstractMesh.prototype.removeChild = function (mesh) {
  15503. mesh.setParent(null);
  15504. return this;
  15505. };
  15506. // Facet data
  15507. /**
  15508. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  15509. * Returns the AbstractMesh.
  15510. */
  15511. AbstractMesh.prototype._initFacetData = function () {
  15512. if (!this._facetNormals) {
  15513. this._facetNormals = new Array();
  15514. }
  15515. if (!this._facetPositions) {
  15516. this._facetPositions = new Array();
  15517. }
  15518. if (!this._facetPartitioning) {
  15519. this._facetPartitioning = new Array();
  15520. }
  15521. this._facetNb = (this.getIndices().length / 3) | 0;
  15522. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  15523. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  15524. for (var f = 0; f < this._facetNb; f++) {
  15525. this._facetNormals[f] = BABYLON.Vector3.Zero();
  15526. this._facetPositions[f] = BABYLON.Vector3.Zero();
  15527. }
  15528. this._facetDataEnabled = true;
  15529. return this;
  15530. };
  15531. /**
  15532. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  15533. * This method can be called within the render loop.
  15534. * 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.
  15535. * Returns the AbstractMesh.
  15536. */
  15537. AbstractMesh.prototype.updateFacetData = function () {
  15538. if (!this._facetDataEnabled) {
  15539. this._initFacetData();
  15540. }
  15541. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15542. var indices = this.getIndices();
  15543. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15544. var bInfo = this.getBoundingInfo();
  15545. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  15546. // init arrays, matrix and sort function on first call
  15547. this._facetDepthSortEnabled = true;
  15548. if (indices instanceof Uint16Array) {
  15549. this._depthSortedIndices = new Uint16Array(indices);
  15550. }
  15551. else if (indices instanceof Uint32Array) {
  15552. this._depthSortedIndices = new Uint32Array(indices);
  15553. }
  15554. else {
  15555. var needs32bits = false;
  15556. for (var i = 0; i < indices.length; i++) {
  15557. if (indices[i] > 65535) {
  15558. needs32bits = true;
  15559. break;
  15560. }
  15561. }
  15562. if (needs32bits) {
  15563. this._depthSortedIndices = new Uint32Array(indices);
  15564. }
  15565. else {
  15566. this._depthSortedIndices = new Uint16Array(indices);
  15567. }
  15568. }
  15569. this._facetDepthSortFunction = function (f1, f2) {
  15570. return (f2.sqDistance - f1.sqDistance);
  15571. };
  15572. if (!this._facetDepthSortFrom) {
  15573. var camera = this.getScene().activeCamera;
  15574. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  15575. }
  15576. this._depthSortedFacets = [];
  15577. for (var f = 0; f < this._facetNb; f++) {
  15578. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  15579. this._depthSortedFacets.push(depthSortedFacet);
  15580. }
  15581. this._invertedMatrix = BABYLON.Matrix.Identity();
  15582. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  15583. }
  15584. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  15585. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  15586. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  15587. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  15588. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  15589. this._subDiv.max = this._partitioningSubdivisions;
  15590. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  15591. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  15592. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  15593. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  15594. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  15595. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  15596. // set the parameters for ComputeNormals()
  15597. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  15598. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  15599. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  15600. this._facetParameters.bInfo = bInfo;
  15601. this._facetParameters.bbSize = this._bbSize;
  15602. this._facetParameters.subDiv = this._subDiv;
  15603. this._facetParameters.ratio = this.partitioningBBoxRatio;
  15604. this._facetParameters.depthSort = this._facetDepthSort;
  15605. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  15606. this.computeWorldMatrix(true);
  15607. this._worldMatrix.invertToRef(this._invertedMatrix);
  15608. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  15609. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  15610. }
  15611. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  15612. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  15613. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  15614. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  15615. var l = (this._depthSortedIndices.length / 3) | 0;
  15616. for (var f = 0; f < l; f++) {
  15617. var sind = this._depthSortedFacets[f].ind;
  15618. this._depthSortedIndices[f * 3] = indices[sind];
  15619. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  15620. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  15621. }
  15622. this.updateIndices(this._depthSortedIndices);
  15623. }
  15624. return this;
  15625. };
  15626. /**
  15627. * Returns the facetLocalNormals array.
  15628. * The normals are expressed in the mesh local space.
  15629. */
  15630. AbstractMesh.prototype.getFacetLocalNormals = function () {
  15631. if (!this._facetNormals) {
  15632. this.updateFacetData();
  15633. }
  15634. return this._facetNormals;
  15635. };
  15636. /**
  15637. * Returns the facetLocalPositions array.
  15638. * The facet positions are expressed in the mesh local space.
  15639. */
  15640. AbstractMesh.prototype.getFacetLocalPositions = function () {
  15641. if (!this._facetPositions) {
  15642. this.updateFacetData();
  15643. }
  15644. return this._facetPositions;
  15645. };
  15646. /**
  15647. * Returns the facetLocalPartioning array.
  15648. */
  15649. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  15650. if (!this._facetPartitioning) {
  15651. this.updateFacetData();
  15652. }
  15653. return this._facetPartitioning;
  15654. };
  15655. /**
  15656. * Returns the i-th facet position in the world system.
  15657. * This method allocates a new Vector3 per call.
  15658. */
  15659. AbstractMesh.prototype.getFacetPosition = function (i) {
  15660. var pos = BABYLON.Vector3.Zero();
  15661. this.getFacetPositionToRef(i, pos);
  15662. return pos;
  15663. };
  15664. /**
  15665. * Sets the reference Vector3 with the i-th facet position in the world system.
  15666. * Returns the AbstractMesh.
  15667. */
  15668. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  15669. var localPos = (this.getFacetLocalPositions())[i];
  15670. var world = this.getWorldMatrix();
  15671. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  15672. return this;
  15673. };
  15674. /**
  15675. * Returns the i-th facet normal in the world system.
  15676. * This method allocates a new Vector3 per call.
  15677. */
  15678. AbstractMesh.prototype.getFacetNormal = function (i) {
  15679. var norm = BABYLON.Vector3.Zero();
  15680. this.getFacetNormalToRef(i, norm);
  15681. return norm;
  15682. };
  15683. /**
  15684. * Sets the reference Vector3 with the i-th facet normal in the world system.
  15685. * Returns the AbstractMesh.
  15686. */
  15687. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  15688. var localNorm = (this.getFacetLocalNormals())[i];
  15689. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  15690. return this;
  15691. };
  15692. /**
  15693. * 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).
  15694. */
  15695. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  15696. var bInfo = this.getBoundingInfo();
  15697. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  15698. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  15699. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  15700. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  15701. return null;
  15702. }
  15703. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  15704. };
  15705. /**
  15706. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  15707. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  15708. * 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.
  15709. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  15710. * 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.
  15711. */
  15712. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  15713. if (checkFace === void 0) { checkFace = false; }
  15714. if (facing === void 0) { facing = true; }
  15715. var world = this.getWorldMatrix();
  15716. var invMat = BABYLON.Tmp.Matrix[5];
  15717. world.invertToRef(invMat);
  15718. var invVect = BABYLON.Tmp.Vector3[8];
  15719. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  15720. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  15721. if (projected) {
  15722. // tranform the local computed projected vector to world coordinates
  15723. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  15724. }
  15725. return closest;
  15726. };
  15727. /**
  15728. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  15729. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  15730. * 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.
  15731. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  15732. * 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.
  15733. */
  15734. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  15735. if (checkFace === void 0) { checkFace = false; }
  15736. if (facing === void 0) { facing = true; }
  15737. var closest = null;
  15738. var tmpx = 0.0;
  15739. var tmpy = 0.0;
  15740. var tmpz = 0.0;
  15741. var d = 0.0; // tmp dot facet normal * facet position
  15742. var t0 = 0.0;
  15743. var projx = 0.0;
  15744. var projy = 0.0;
  15745. var projz = 0.0;
  15746. // Get all the facets in the same partitioning block than (x, y, z)
  15747. var facetPositions = this.getFacetLocalPositions();
  15748. var facetNormals = this.getFacetLocalNormals();
  15749. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  15750. if (!facetsInBlock) {
  15751. return null;
  15752. }
  15753. // Get the closest facet to (x, y, z)
  15754. var shortest = Number.MAX_VALUE; // init distance vars
  15755. var tmpDistance = shortest;
  15756. var fib; // current facet in the block
  15757. var norm; // current facet normal
  15758. var p0; // current facet barycenter position
  15759. // loop on all the facets in the current partitioning block
  15760. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  15761. fib = facetsInBlock[idx];
  15762. norm = facetNormals[fib];
  15763. p0 = facetPositions[fib];
  15764. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  15765. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  15766. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  15767. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  15768. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  15769. projx = x + norm.x * t0;
  15770. projy = y + norm.y * t0;
  15771. projz = z + norm.z * t0;
  15772. tmpx = projx - x;
  15773. tmpy = projy - y;
  15774. tmpz = projz - z;
  15775. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  15776. if (tmpDistance < shortest) {
  15777. shortest = tmpDistance;
  15778. closest = fib;
  15779. if (projected) {
  15780. projected.x = projx;
  15781. projected.y = projy;
  15782. projected.z = projz;
  15783. }
  15784. }
  15785. }
  15786. }
  15787. return closest;
  15788. };
  15789. /**
  15790. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  15791. */
  15792. AbstractMesh.prototype.getFacetDataParameters = function () {
  15793. return this._facetParameters;
  15794. };
  15795. /**
  15796. * Disables the feature FacetData and frees the related memory.
  15797. * Returns the AbstractMesh.
  15798. */
  15799. AbstractMesh.prototype.disableFacetData = function () {
  15800. if (this._facetDataEnabled) {
  15801. this._facetDataEnabled = false;
  15802. this._facetPositions = new Array();
  15803. this._facetNormals = new Array();
  15804. this._facetPartitioning = new Array();
  15805. this._facetParameters = null;
  15806. this._depthSortedIndices = new Uint32Array(0);
  15807. }
  15808. return this;
  15809. };
  15810. /**
  15811. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  15812. * Returns the mesh.
  15813. */
  15814. AbstractMesh.prototype.updateIndices = function (indices) {
  15815. return this;
  15816. };
  15817. /**
  15818. * The mesh Geometry. Actually used by the Mesh object.
  15819. * Returns a blank geometry object.
  15820. */
  15821. /**
  15822. * Creates new normals data for the mesh.
  15823. * @param updatable.
  15824. */
  15825. AbstractMesh.prototype.createNormals = function (updatable) {
  15826. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15827. var indices = this.getIndices();
  15828. var normals;
  15829. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15830. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15831. }
  15832. else {
  15833. normals = [];
  15834. }
  15835. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  15836. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  15837. };
  15838. /**
  15839. * Align the mesh with a normal.
  15840. * Returns the mesh.
  15841. */
  15842. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  15843. if (!upDirection) {
  15844. upDirection = BABYLON.Axis.Y;
  15845. }
  15846. var axisX = BABYLON.Tmp.Vector3[0];
  15847. var axisZ = BABYLON.Tmp.Vector3[1];
  15848. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  15849. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  15850. if (this.rotationQuaternion) {
  15851. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  15852. }
  15853. else {
  15854. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  15855. }
  15856. return this;
  15857. };
  15858. AbstractMesh.prototype.checkOcclusionQuery = function () {
  15859. var engine = this.getEngine();
  15860. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  15861. this._isOccluded = false;
  15862. return;
  15863. }
  15864. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  15865. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  15866. if (isOcclusionQueryAvailable) {
  15867. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  15868. this._isOcclusionQueryInProgress = false;
  15869. this._occlusionInternalRetryCounter = 0;
  15870. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  15871. }
  15872. else {
  15873. this._occlusionInternalRetryCounter++;
  15874. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  15875. this._isOcclusionQueryInProgress = false;
  15876. this._occlusionInternalRetryCounter = 0;
  15877. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  15878. // if strict continue the last state of the object.
  15879. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  15880. }
  15881. else {
  15882. return;
  15883. }
  15884. }
  15885. }
  15886. var scene = this.getScene();
  15887. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  15888. if (!this._occlusionQuery) {
  15889. this._occlusionQuery = engine.createQuery();
  15890. }
  15891. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  15892. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  15893. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  15894. this._isOcclusionQueryInProgress = true;
  15895. };
  15896. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  15897. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  15898. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  15899. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  15900. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  15901. return AbstractMesh;
  15902. }(BABYLON.TransformNode));
  15903. BABYLON.AbstractMesh = AbstractMesh;
  15904. })(BABYLON || (BABYLON = {}));
  15905. //# sourceMappingURL=babylon.abstractMesh.js.map
  15906. var BABYLON;
  15907. (function (BABYLON) {
  15908. var Light = /** @class */ (function (_super) {
  15909. __extends(Light, _super);
  15910. /**
  15911. * Creates a Light object in the scene.
  15912. * Documentation : http://doc.babylonjs.com/tutorials/lights
  15913. */
  15914. function Light(name, scene) {
  15915. var _this = _super.call(this, name, scene) || this;
  15916. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  15917. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  15918. _this.intensity = 1.0;
  15919. _this.range = Number.MAX_VALUE;
  15920. /**
  15921. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  15922. * of light.
  15923. */
  15924. _this._photometricScale = 1.0;
  15925. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  15926. _this._radius = 0.00001;
  15927. _this.renderPriority = 0;
  15928. /**
  15929. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  15930. * the current shadow generator.
  15931. */
  15932. _this.shadowEnabled = true;
  15933. _this._excludeWithLayerMask = 0;
  15934. _this._includeOnlyWithLayerMask = 0;
  15935. _this._lightmapMode = 0;
  15936. _this._excludedMeshesIds = new Array();
  15937. _this._includedOnlyMeshesIds = new Array();
  15938. _this.getScene().addLight(_this);
  15939. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  15940. _this._buildUniformLayout();
  15941. _this.includedOnlyMeshes = new Array();
  15942. _this.excludedMeshes = new Array();
  15943. _this._resyncMeshes();
  15944. return _this;
  15945. }
  15946. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  15947. /**
  15948. * If every light affecting the material is in this lightmapMode,
  15949. * material.lightmapTexture adds or multiplies
  15950. * (depends on material.useLightmapAsShadowmap)
  15951. * after every other light calculations.
  15952. */
  15953. get: function () {
  15954. return Light._LIGHTMAP_DEFAULT;
  15955. },
  15956. enumerable: true,
  15957. configurable: true
  15958. });
  15959. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  15960. /**
  15961. * material.lightmapTexture as only diffuse lighting from this light
  15962. * adds pnly specular lighting from this light
  15963. * adds dynamic shadows
  15964. */
  15965. get: function () {
  15966. return Light._LIGHTMAP_SPECULAR;
  15967. },
  15968. enumerable: true,
  15969. configurable: true
  15970. });
  15971. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  15972. /**
  15973. * material.lightmapTexture as only lighting
  15974. * no light calculation from this light
  15975. * only adds dynamic shadows from this light
  15976. */
  15977. get: function () {
  15978. return Light._LIGHTMAP_SHADOWSONLY;
  15979. },
  15980. enumerable: true,
  15981. configurable: true
  15982. });
  15983. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  15984. /**
  15985. * Each light type uses the default quantity according to its type:
  15986. * point/spot lights use luminous intensity
  15987. * directional lights use illuminance
  15988. */
  15989. get: function () {
  15990. return Light._INTENSITYMODE_AUTOMATIC;
  15991. },
  15992. enumerable: true,
  15993. configurable: true
  15994. });
  15995. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  15996. /**
  15997. * lumen (lm)
  15998. */
  15999. get: function () {
  16000. return Light._INTENSITYMODE_LUMINOUSPOWER;
  16001. },
  16002. enumerable: true,
  16003. configurable: true
  16004. });
  16005. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  16006. /**
  16007. * candela (lm/sr)
  16008. */
  16009. get: function () {
  16010. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  16011. },
  16012. enumerable: true,
  16013. configurable: true
  16014. });
  16015. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  16016. /**
  16017. * lux (lm/m^2)
  16018. */
  16019. get: function () {
  16020. return Light._INTENSITYMODE_ILLUMINANCE;
  16021. },
  16022. enumerable: true,
  16023. configurable: true
  16024. });
  16025. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  16026. /**
  16027. * nit (cd/m^2)
  16028. */
  16029. get: function () {
  16030. return Light._INTENSITYMODE_LUMINANCE;
  16031. },
  16032. enumerable: true,
  16033. configurable: true
  16034. });
  16035. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  16036. /**
  16037. * Light type const id of the point light.
  16038. */
  16039. get: function () {
  16040. return Light._LIGHTTYPEID_POINTLIGHT;
  16041. },
  16042. enumerable: true,
  16043. configurable: true
  16044. });
  16045. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  16046. /**
  16047. * Light type const id of the directional light.
  16048. */
  16049. get: function () {
  16050. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  16051. },
  16052. enumerable: true,
  16053. configurable: true
  16054. });
  16055. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  16056. /**
  16057. * Light type const id of the spot light.
  16058. */
  16059. get: function () {
  16060. return Light._LIGHTTYPEID_SPOTLIGHT;
  16061. },
  16062. enumerable: true,
  16063. configurable: true
  16064. });
  16065. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  16066. /**
  16067. * Light type const id of the hemispheric light.
  16068. */
  16069. get: function () {
  16070. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  16071. },
  16072. enumerable: true,
  16073. configurable: true
  16074. });
  16075. Object.defineProperty(Light.prototype, "intensityMode", {
  16076. /**
  16077. * Gets the photometric scale used to interpret the intensity.
  16078. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  16079. */
  16080. get: function () {
  16081. return this._intensityMode;
  16082. },
  16083. /**
  16084. * Sets the photometric scale used to interpret the intensity.
  16085. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  16086. */
  16087. set: function (value) {
  16088. this._intensityMode = value;
  16089. this._computePhotometricScale();
  16090. },
  16091. enumerable: true,
  16092. configurable: true
  16093. });
  16094. ;
  16095. ;
  16096. Object.defineProperty(Light.prototype, "radius", {
  16097. /**
  16098. * Gets the light radius used by PBR Materials to simulate soft area lights.
  16099. */
  16100. get: function () {
  16101. return this._radius;
  16102. },
  16103. /**
  16104. * sets the light radius used by PBR Materials to simulate soft area lights.
  16105. */
  16106. set: function (value) {
  16107. this._radius = value;
  16108. this._computePhotometricScale();
  16109. },
  16110. enumerable: true,
  16111. configurable: true
  16112. });
  16113. ;
  16114. ;
  16115. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  16116. get: function () {
  16117. return this._includedOnlyMeshes;
  16118. },
  16119. set: function (value) {
  16120. this._includedOnlyMeshes = value;
  16121. this._hookArrayForIncludedOnly(value);
  16122. },
  16123. enumerable: true,
  16124. configurable: true
  16125. });
  16126. Object.defineProperty(Light.prototype, "excludedMeshes", {
  16127. get: function () {
  16128. return this._excludedMeshes;
  16129. },
  16130. set: function (value) {
  16131. this._excludedMeshes = value;
  16132. this._hookArrayForExcluded(value);
  16133. },
  16134. enumerable: true,
  16135. configurable: true
  16136. });
  16137. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  16138. get: function () {
  16139. return this._excludeWithLayerMask;
  16140. },
  16141. set: function (value) {
  16142. this._excludeWithLayerMask = value;
  16143. this._resyncMeshes();
  16144. },
  16145. enumerable: true,
  16146. configurable: true
  16147. });
  16148. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  16149. get: function () {
  16150. return this._includeOnlyWithLayerMask;
  16151. },
  16152. set: function (value) {
  16153. this._includeOnlyWithLayerMask = value;
  16154. this._resyncMeshes();
  16155. },
  16156. enumerable: true,
  16157. configurable: true
  16158. });
  16159. Object.defineProperty(Light.prototype, "lightmapMode", {
  16160. get: function () {
  16161. return this._lightmapMode;
  16162. },
  16163. set: function (value) {
  16164. if (this._lightmapMode === value) {
  16165. return;
  16166. }
  16167. this._lightmapMode = value;
  16168. this._markMeshesAsLightDirty();
  16169. },
  16170. enumerable: true,
  16171. configurable: true
  16172. });
  16173. Light.prototype._buildUniformLayout = function () {
  16174. // Overridden
  16175. };
  16176. /**
  16177. * Returns the string "Light".
  16178. */
  16179. Light.prototype.getClassName = function () {
  16180. return "Light";
  16181. };
  16182. /**
  16183. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16184. */
  16185. Light.prototype.toString = function (fullDetails) {
  16186. var ret = "Name: " + this.name;
  16187. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  16188. if (this.animations) {
  16189. for (var i = 0; i < this.animations.length; i++) {
  16190. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16191. }
  16192. }
  16193. if (fullDetails) {
  16194. }
  16195. return ret;
  16196. };
  16197. /**
  16198. * Set the enabled state of this node.
  16199. * @param {boolean} value - the new enabled state
  16200. * @see isEnabled
  16201. */
  16202. Light.prototype.setEnabled = function (value) {
  16203. _super.prototype.setEnabled.call(this, value);
  16204. this._resyncMeshes();
  16205. };
  16206. /**
  16207. * Returns the Light associated shadow generator.
  16208. */
  16209. Light.prototype.getShadowGenerator = function () {
  16210. return this._shadowGenerator;
  16211. };
  16212. /**
  16213. * Returns a Vector3, the absolute light position in the World.
  16214. */
  16215. Light.prototype.getAbsolutePosition = function () {
  16216. return BABYLON.Vector3.Zero();
  16217. };
  16218. Light.prototype.transferToEffect = function (effect, lightIndex) {
  16219. };
  16220. Light.prototype._getWorldMatrix = function () {
  16221. return BABYLON.Matrix.Identity();
  16222. };
  16223. /**
  16224. * Boolean : True if the light will affect the passed mesh.
  16225. */
  16226. Light.prototype.canAffectMesh = function (mesh) {
  16227. if (!mesh) {
  16228. return true;
  16229. }
  16230. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  16231. return false;
  16232. }
  16233. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  16234. return false;
  16235. }
  16236. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  16237. return false;
  16238. }
  16239. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  16240. return false;
  16241. }
  16242. return true;
  16243. };
  16244. /**
  16245. * Returns the light World matrix.
  16246. */
  16247. Light.prototype.getWorldMatrix = function () {
  16248. this._currentRenderId = this.getScene().getRenderId();
  16249. var worldMatrix = this._getWorldMatrix();
  16250. if (this.parent && this.parent.getWorldMatrix) {
  16251. if (!this._parentedWorldMatrix) {
  16252. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  16253. }
  16254. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  16255. this._markSyncedWithParent();
  16256. return this._parentedWorldMatrix;
  16257. }
  16258. return worldMatrix;
  16259. };
  16260. /**
  16261. * Sort function to order lights for rendering.
  16262. * @param a First Light object to compare to second.
  16263. * @param b Second Light object to compare first.
  16264. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  16265. */
  16266. Light.compareLightsPriority = function (a, b) {
  16267. //shadow-casting lights have priority over non-shadow-casting lights
  16268. //the renderPrioirty is a secondary sort criterion
  16269. if (a.shadowEnabled !== b.shadowEnabled) {
  16270. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  16271. }
  16272. return b.renderPriority - a.renderPriority;
  16273. };
  16274. /**
  16275. * Disposes the light.
  16276. */
  16277. Light.prototype.dispose = function () {
  16278. if (this._shadowGenerator) {
  16279. this._shadowGenerator.dispose();
  16280. this._shadowGenerator = null;
  16281. }
  16282. // Animations
  16283. this.getScene().stopAnimation(this);
  16284. // Remove from meshes
  16285. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  16286. var mesh = _a[_i];
  16287. mesh._removeLightSource(this);
  16288. }
  16289. this._uniformBuffer.dispose();
  16290. // Remove from scene
  16291. this.getScene().removeLight(this);
  16292. _super.prototype.dispose.call(this);
  16293. };
  16294. /**
  16295. * Returns the light type ID (integer).
  16296. */
  16297. Light.prototype.getTypeID = function () {
  16298. return 0;
  16299. };
  16300. /**
  16301. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  16302. */
  16303. Light.prototype.getScaledIntensity = function () {
  16304. return this._photometricScale * this.intensity;
  16305. };
  16306. /**
  16307. * Returns a new Light object, named "name", from the current one.
  16308. */
  16309. Light.prototype.clone = function (name) {
  16310. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  16311. if (!constructor) {
  16312. return null;
  16313. }
  16314. return BABYLON.SerializationHelper.Clone(constructor, this);
  16315. };
  16316. /**
  16317. * Serializes the current light into a Serialization object.
  16318. * Returns the serialized object.
  16319. */
  16320. Light.prototype.serialize = function () {
  16321. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  16322. // Type
  16323. serializationObject.type = this.getTypeID();
  16324. // Parent
  16325. if (this.parent) {
  16326. serializationObject.parentId = this.parent.id;
  16327. }
  16328. // Inclusion / exclusions
  16329. if (this.excludedMeshes.length > 0) {
  16330. serializationObject.excludedMeshesIds = [];
  16331. this.excludedMeshes.forEach(function (mesh) {
  16332. serializationObject.excludedMeshesIds.push(mesh.id);
  16333. });
  16334. }
  16335. if (this.includedOnlyMeshes.length > 0) {
  16336. serializationObject.includedOnlyMeshesIds = [];
  16337. this.includedOnlyMeshes.forEach(function (mesh) {
  16338. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  16339. });
  16340. }
  16341. // Animations
  16342. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16343. serializationObject.ranges = this.serializeAnimationRanges();
  16344. return serializationObject;
  16345. };
  16346. /**
  16347. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  16348. * This new light is named "name" and added to the passed scene.
  16349. */
  16350. Light.GetConstructorFromName = function (type, name, scene) {
  16351. switch (type) {
  16352. case 0:
  16353. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  16354. case 1:
  16355. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  16356. case 2:
  16357. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  16358. case 3:
  16359. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  16360. }
  16361. return null;
  16362. };
  16363. /**
  16364. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  16365. */
  16366. Light.Parse = function (parsedLight, scene) {
  16367. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  16368. if (!constructor) {
  16369. return null;
  16370. }
  16371. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  16372. // Inclusion / exclusions
  16373. if (parsedLight.excludedMeshesIds) {
  16374. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  16375. }
  16376. if (parsedLight.includedOnlyMeshesIds) {
  16377. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  16378. }
  16379. // Parent
  16380. if (parsedLight.parentId) {
  16381. light._waitingParentId = parsedLight.parentId;
  16382. }
  16383. // Animations
  16384. if (parsedLight.animations) {
  16385. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  16386. var parsedAnimation = parsedLight.animations[animationIndex];
  16387. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16388. }
  16389. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  16390. }
  16391. if (parsedLight.autoAnimate) {
  16392. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  16393. }
  16394. return light;
  16395. };
  16396. Light.prototype._hookArrayForExcluded = function (array) {
  16397. var _this = this;
  16398. var oldPush = array.push;
  16399. array.push = function () {
  16400. var items = [];
  16401. for (var _i = 0; _i < arguments.length; _i++) {
  16402. items[_i] = arguments[_i];
  16403. }
  16404. var result = oldPush.apply(array, items);
  16405. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  16406. var item = items_1[_a];
  16407. item._resyncLighSource(_this);
  16408. }
  16409. return result;
  16410. };
  16411. var oldSplice = array.splice;
  16412. array.splice = function (index, deleteCount) {
  16413. var deleted = oldSplice.apply(array, [index, deleteCount]);
  16414. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  16415. var item = deleted_1[_i];
  16416. item._resyncLighSource(_this);
  16417. }
  16418. return deleted;
  16419. };
  16420. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  16421. var item = array_1[_i];
  16422. item._resyncLighSource(this);
  16423. }
  16424. };
  16425. Light.prototype._hookArrayForIncludedOnly = function (array) {
  16426. var _this = this;
  16427. var oldPush = array.push;
  16428. array.push = function () {
  16429. var items = [];
  16430. for (var _i = 0; _i < arguments.length; _i++) {
  16431. items[_i] = arguments[_i];
  16432. }
  16433. var result = oldPush.apply(array, items);
  16434. _this._resyncMeshes();
  16435. return result;
  16436. };
  16437. var oldSplice = array.splice;
  16438. array.splice = function (index, deleteCount) {
  16439. var deleted = oldSplice.apply(array, [index, deleteCount]);
  16440. _this._resyncMeshes();
  16441. return deleted;
  16442. };
  16443. this._resyncMeshes();
  16444. };
  16445. Light.prototype._resyncMeshes = function () {
  16446. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  16447. var mesh = _a[_i];
  16448. mesh._resyncLighSource(this);
  16449. }
  16450. };
  16451. Light.prototype._markMeshesAsLightDirty = function () {
  16452. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  16453. var mesh = _a[_i];
  16454. if (mesh._lightSources.indexOf(this) !== -1) {
  16455. mesh._markSubMeshesAsLightDirty();
  16456. }
  16457. }
  16458. };
  16459. /**
  16460. * Recomputes the cached photometric scale if needed.
  16461. */
  16462. Light.prototype._computePhotometricScale = function () {
  16463. this._photometricScale = this._getPhotometricScale();
  16464. this.getScene().resetCachedMaterial();
  16465. };
  16466. /**
  16467. * Returns the Photometric Scale according to the light type and intensity mode.
  16468. */
  16469. Light.prototype._getPhotometricScale = function () {
  16470. var photometricScale = 0.0;
  16471. var lightTypeID = this.getTypeID();
  16472. //get photometric mode
  16473. var photometricMode = this.intensityMode;
  16474. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  16475. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  16476. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  16477. }
  16478. else {
  16479. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  16480. }
  16481. }
  16482. //compute photometric scale
  16483. switch (lightTypeID) {
  16484. case Light.LIGHTTYPEID_POINTLIGHT:
  16485. case Light.LIGHTTYPEID_SPOTLIGHT:
  16486. switch (photometricMode) {
  16487. case Light.INTENSITYMODE_LUMINOUSPOWER:
  16488. photometricScale = 1.0 / (4.0 * Math.PI);
  16489. break;
  16490. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  16491. photometricScale = 1.0;
  16492. break;
  16493. case Light.INTENSITYMODE_LUMINANCE:
  16494. photometricScale = this.radius * this.radius;
  16495. break;
  16496. }
  16497. break;
  16498. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  16499. switch (photometricMode) {
  16500. case Light.INTENSITYMODE_ILLUMINANCE:
  16501. photometricScale = 1.0;
  16502. break;
  16503. case Light.INTENSITYMODE_LUMINANCE:
  16504. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  16505. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  16506. var apexAngleRadians = this.radius;
  16507. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  16508. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  16509. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  16510. photometricScale = solidAngle;
  16511. break;
  16512. }
  16513. break;
  16514. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  16515. // No fall off in hemisperic light.
  16516. photometricScale = 1.0;
  16517. break;
  16518. }
  16519. return photometricScale;
  16520. };
  16521. Light.prototype._reorderLightsInScene = function () {
  16522. var scene = this.getScene();
  16523. if (this._renderPriority != 0) {
  16524. scene.requireLightSorting = true;
  16525. }
  16526. this.getScene().sortLightsByPriority();
  16527. };
  16528. //lightmapMode Consts
  16529. Light._LIGHTMAP_DEFAULT = 0;
  16530. Light._LIGHTMAP_SPECULAR = 1;
  16531. Light._LIGHTMAP_SHADOWSONLY = 2;
  16532. // Intensity Mode Consts
  16533. Light._INTENSITYMODE_AUTOMATIC = 0;
  16534. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  16535. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  16536. Light._INTENSITYMODE_ILLUMINANCE = 3;
  16537. Light._INTENSITYMODE_LUMINANCE = 4;
  16538. // Light types ids const.
  16539. Light._LIGHTTYPEID_POINTLIGHT = 0;
  16540. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  16541. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  16542. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  16543. __decorate([
  16544. BABYLON.serializeAsColor3()
  16545. ], Light.prototype, "diffuse", void 0);
  16546. __decorate([
  16547. BABYLON.serializeAsColor3()
  16548. ], Light.prototype, "specular", void 0);
  16549. __decorate([
  16550. BABYLON.serialize()
  16551. ], Light.prototype, "intensity", void 0);
  16552. __decorate([
  16553. BABYLON.serialize()
  16554. ], Light.prototype, "range", void 0);
  16555. __decorate([
  16556. BABYLON.serialize()
  16557. ], Light.prototype, "intensityMode", null);
  16558. __decorate([
  16559. BABYLON.serialize()
  16560. ], Light.prototype, "radius", null);
  16561. __decorate([
  16562. BABYLON.serialize()
  16563. ], Light.prototype, "_renderPriority", void 0);
  16564. __decorate([
  16565. BABYLON.expandToProperty("_reorderLightsInScene")
  16566. ], Light.prototype, "renderPriority", void 0);
  16567. __decorate([
  16568. BABYLON.serialize()
  16569. ], Light.prototype, "shadowEnabled", void 0);
  16570. __decorate([
  16571. BABYLON.serialize("excludeWithLayerMask")
  16572. ], Light.prototype, "_excludeWithLayerMask", void 0);
  16573. __decorate([
  16574. BABYLON.serialize("includeOnlyWithLayerMask")
  16575. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  16576. __decorate([
  16577. BABYLON.serialize("lightmapMode")
  16578. ], Light.prototype, "_lightmapMode", void 0);
  16579. return Light;
  16580. }(BABYLON.Node));
  16581. BABYLON.Light = Light;
  16582. })(BABYLON || (BABYLON = {}));
  16583. //# sourceMappingURL=babylon.light.js.map
  16584. var BABYLON;
  16585. (function (BABYLON) {
  16586. var Camera = /** @class */ (function (_super) {
  16587. __extends(Camera, _super);
  16588. function Camera(name, position, scene) {
  16589. var _this = _super.call(this, name, scene) || this;
  16590. _this.upVector = BABYLON.Vector3.Up();
  16591. _this.orthoLeft = null;
  16592. _this.orthoRight = null;
  16593. _this.orthoBottom = null;
  16594. _this.orthoTop = null;
  16595. _this.fov = 0.8;
  16596. _this.minZ = 1;
  16597. _this.maxZ = 10000.0;
  16598. _this.inertia = 0.9;
  16599. _this.mode = Camera.PERSPECTIVE_CAMERA;
  16600. _this.isIntermediate = false;
  16601. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  16602. _this.layerMask = 0x0FFFFFFF;
  16603. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  16604. // Camera rig members
  16605. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  16606. _this._rigCameras = new Array();
  16607. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  16608. _this._skipRendering = false;
  16609. _this.customRenderTargets = new Array();
  16610. // Observables
  16611. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  16612. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  16613. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  16614. _this.onRestoreStateObservable = new BABYLON.Observable();
  16615. // Cache
  16616. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  16617. _this._projectionMatrix = new BABYLON.Matrix();
  16618. _this._doNotComputeProjectionMatrix = false;
  16619. _this._postProcesses = new Array();
  16620. _this._transformMatrix = BABYLON.Matrix.Zero();
  16621. _this._activeMeshes = new BABYLON.SmartArray(256);
  16622. _this._globalPosition = BABYLON.Vector3.Zero();
  16623. _this._refreshFrustumPlanes = true;
  16624. _this.getScene().addCamera(_this);
  16625. if (!_this.getScene().activeCamera) {
  16626. _this.getScene().activeCamera = _this;
  16627. }
  16628. _this.position = position;
  16629. return _this;
  16630. }
  16631. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  16632. get: function () {
  16633. return Camera._PERSPECTIVE_CAMERA;
  16634. },
  16635. enumerable: true,
  16636. configurable: true
  16637. });
  16638. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  16639. get: function () {
  16640. return Camera._ORTHOGRAPHIC_CAMERA;
  16641. },
  16642. enumerable: true,
  16643. configurable: true
  16644. });
  16645. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  16646. get: function () {
  16647. return Camera._FOVMODE_VERTICAL_FIXED;
  16648. },
  16649. enumerable: true,
  16650. configurable: true
  16651. });
  16652. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  16653. get: function () {
  16654. return Camera._FOVMODE_HORIZONTAL_FIXED;
  16655. },
  16656. enumerable: true,
  16657. configurable: true
  16658. });
  16659. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  16660. get: function () {
  16661. return Camera._RIG_MODE_NONE;
  16662. },
  16663. enumerable: true,
  16664. configurable: true
  16665. });
  16666. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  16667. get: function () {
  16668. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  16669. },
  16670. enumerable: true,
  16671. configurable: true
  16672. });
  16673. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  16674. get: function () {
  16675. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  16676. },
  16677. enumerable: true,
  16678. configurable: true
  16679. });
  16680. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  16681. get: function () {
  16682. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16683. },
  16684. enumerable: true,
  16685. configurable: true
  16686. });
  16687. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  16688. get: function () {
  16689. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  16690. },
  16691. enumerable: true,
  16692. configurable: true
  16693. });
  16694. Object.defineProperty(Camera, "RIG_MODE_VR", {
  16695. get: function () {
  16696. return Camera._RIG_MODE_VR;
  16697. },
  16698. enumerable: true,
  16699. configurable: true
  16700. });
  16701. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  16702. get: function () {
  16703. return Camera._RIG_MODE_WEBVR;
  16704. },
  16705. enumerable: true,
  16706. configurable: true
  16707. });
  16708. /**
  16709. * Store current camera state (fov, position, etc..)
  16710. */
  16711. Camera.prototype.storeState = function () {
  16712. this._stateStored = true;
  16713. this._storedFov = this.fov;
  16714. return this;
  16715. };
  16716. /**
  16717. * Restores the camera state values if it has been stored. You must call storeState() first
  16718. */
  16719. Camera.prototype._restoreStateValues = function () {
  16720. if (!this._stateStored) {
  16721. return false;
  16722. }
  16723. this.fov = this._storedFov;
  16724. return true;
  16725. };
  16726. /**
  16727. * Restored camera state. You must call storeState() first
  16728. */
  16729. Camera.prototype.restoreState = function () {
  16730. if (this._restoreStateValues()) {
  16731. this.onRestoreStateObservable.notifyObservers(this);
  16732. return true;
  16733. }
  16734. return false;
  16735. };
  16736. Camera.prototype.getClassName = function () {
  16737. return "Camera";
  16738. };
  16739. /**
  16740. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16741. */
  16742. Camera.prototype.toString = function (fullDetails) {
  16743. var ret = "Name: " + this.name;
  16744. ret += ", type: " + this.getClassName();
  16745. if (this.animations) {
  16746. for (var i = 0; i < this.animations.length; i++) {
  16747. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16748. }
  16749. }
  16750. if (fullDetails) {
  16751. }
  16752. return ret;
  16753. };
  16754. Object.defineProperty(Camera.prototype, "globalPosition", {
  16755. get: function () {
  16756. return this._globalPosition;
  16757. },
  16758. enumerable: true,
  16759. configurable: true
  16760. });
  16761. Camera.prototype.getActiveMeshes = function () {
  16762. return this._activeMeshes;
  16763. };
  16764. Camera.prototype.isActiveMesh = function (mesh) {
  16765. return (this._activeMeshes.indexOf(mesh) !== -1);
  16766. };
  16767. //Cache
  16768. Camera.prototype._initCache = function () {
  16769. _super.prototype._initCache.call(this);
  16770. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16771. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16772. this._cache.mode = undefined;
  16773. this._cache.minZ = undefined;
  16774. this._cache.maxZ = undefined;
  16775. this._cache.fov = undefined;
  16776. this._cache.fovMode = undefined;
  16777. this._cache.aspectRatio = undefined;
  16778. this._cache.orthoLeft = undefined;
  16779. this._cache.orthoRight = undefined;
  16780. this._cache.orthoBottom = undefined;
  16781. this._cache.orthoTop = undefined;
  16782. this._cache.renderWidth = undefined;
  16783. this._cache.renderHeight = undefined;
  16784. };
  16785. Camera.prototype._updateCache = function (ignoreParentClass) {
  16786. if (!ignoreParentClass) {
  16787. _super.prototype._updateCache.call(this);
  16788. }
  16789. this._cache.position.copyFrom(this.position);
  16790. this._cache.upVector.copyFrom(this.upVector);
  16791. };
  16792. // Synchronized
  16793. Camera.prototype._isSynchronized = function () {
  16794. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  16795. };
  16796. Camera.prototype._isSynchronizedViewMatrix = function () {
  16797. if (!_super.prototype._isSynchronized.call(this))
  16798. return false;
  16799. return this._cache.position.equals(this.position)
  16800. && this._cache.upVector.equals(this.upVector)
  16801. && this.isSynchronizedWithParent();
  16802. };
  16803. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  16804. var check = this._cache.mode === this.mode
  16805. && this._cache.minZ === this.minZ
  16806. && this._cache.maxZ === this.maxZ;
  16807. if (!check) {
  16808. return false;
  16809. }
  16810. var engine = this.getEngine();
  16811. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16812. check = this._cache.fov === this.fov
  16813. && this._cache.fovMode === this.fovMode
  16814. && this._cache.aspectRatio === engine.getAspectRatio(this);
  16815. }
  16816. else {
  16817. check = this._cache.orthoLeft === this.orthoLeft
  16818. && this._cache.orthoRight === this.orthoRight
  16819. && this._cache.orthoBottom === this.orthoBottom
  16820. && this._cache.orthoTop === this.orthoTop
  16821. && this._cache.renderWidth === engine.getRenderWidth()
  16822. && this._cache.renderHeight === engine.getRenderHeight();
  16823. }
  16824. return check;
  16825. };
  16826. // Controls
  16827. Camera.prototype.attachControl = function (element, noPreventDefault) {
  16828. };
  16829. Camera.prototype.detachControl = function (element) {
  16830. };
  16831. Camera.prototype.update = function () {
  16832. this._checkInputs();
  16833. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16834. this._updateRigCameras();
  16835. }
  16836. };
  16837. Camera.prototype._checkInputs = function () {
  16838. this.onAfterCheckInputsObservable.notifyObservers(this);
  16839. };
  16840. Object.defineProperty(Camera.prototype, "rigCameras", {
  16841. get: function () {
  16842. return this._rigCameras;
  16843. },
  16844. enumerable: true,
  16845. configurable: true
  16846. });
  16847. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  16848. get: function () {
  16849. return this._rigPostProcess;
  16850. },
  16851. enumerable: true,
  16852. configurable: true
  16853. });
  16854. Camera.prototype._cascadePostProcessesToRigCams = function () {
  16855. // invalidate framebuffer
  16856. if (this._postProcesses.length > 0) {
  16857. this._postProcesses[0].markTextureDirty();
  16858. }
  16859. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  16860. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  16861. var cam = this._rigCameras[i];
  16862. var rigPostProcess = cam._rigPostProcess;
  16863. // for VR rig, there does not have to be a post process
  16864. if (rigPostProcess) {
  16865. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  16866. if (isPass) {
  16867. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  16868. cam.isIntermediate = this._postProcesses.length === 0;
  16869. }
  16870. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  16871. rigPostProcess.markTextureDirty();
  16872. }
  16873. else {
  16874. cam._postProcesses = this._postProcesses.slice(0);
  16875. }
  16876. }
  16877. };
  16878. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  16879. if (insertAt === void 0) { insertAt = null; }
  16880. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  16881. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  16882. return 0;
  16883. }
  16884. if (insertAt == null || insertAt < 0) {
  16885. this._postProcesses.push(postProcess);
  16886. }
  16887. else {
  16888. this._postProcesses.splice(insertAt, 0, postProcess);
  16889. }
  16890. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16891. return this._postProcesses.indexOf(postProcess);
  16892. };
  16893. Camera.prototype.detachPostProcess = function (postProcess) {
  16894. var idx = this._postProcesses.indexOf(postProcess);
  16895. if (idx !== -1) {
  16896. this._postProcesses.splice(idx, 1);
  16897. }
  16898. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16899. };
  16900. Camera.prototype.getWorldMatrix = function () {
  16901. if (!this._worldMatrix) {
  16902. this._worldMatrix = BABYLON.Matrix.Identity();
  16903. }
  16904. var viewMatrix = this.getViewMatrix();
  16905. viewMatrix.invertToRef(this._worldMatrix);
  16906. return this._worldMatrix;
  16907. };
  16908. Camera.prototype._getViewMatrix = function () {
  16909. return BABYLON.Matrix.Identity();
  16910. };
  16911. Camera.prototype.getViewMatrix = function (force) {
  16912. if (!force && this._isSynchronizedViewMatrix()) {
  16913. return this._computedViewMatrix;
  16914. }
  16915. this.updateCache();
  16916. this._computedViewMatrix = this._getViewMatrix();
  16917. this._currentRenderId = this.getScene().getRenderId();
  16918. this._refreshFrustumPlanes = true;
  16919. if (!this.parent || !this.parent.getWorldMatrix) {
  16920. this._globalPosition.copyFrom(this.position);
  16921. }
  16922. else {
  16923. if (!this._worldMatrix) {
  16924. this._worldMatrix = BABYLON.Matrix.Identity();
  16925. }
  16926. this._computedViewMatrix.invertToRef(this._worldMatrix);
  16927. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  16928. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  16929. this._computedViewMatrix.invert();
  16930. this._markSyncedWithParent();
  16931. }
  16932. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  16933. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  16934. }
  16935. this.onViewMatrixChangedObservable.notifyObservers(this);
  16936. return this._computedViewMatrix;
  16937. };
  16938. Camera.prototype.freezeProjectionMatrix = function (projection) {
  16939. this._doNotComputeProjectionMatrix = true;
  16940. if (projection !== undefined) {
  16941. this._projectionMatrix = projection;
  16942. }
  16943. };
  16944. ;
  16945. Camera.prototype.unfreezeProjectionMatrix = function () {
  16946. this._doNotComputeProjectionMatrix = false;
  16947. };
  16948. ;
  16949. Camera.prototype.getProjectionMatrix = function (force) {
  16950. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  16951. return this._projectionMatrix;
  16952. }
  16953. // Cache
  16954. this._cache.mode = this.mode;
  16955. this._cache.minZ = this.minZ;
  16956. this._cache.maxZ = this.maxZ;
  16957. // Matrix
  16958. this._refreshFrustumPlanes = true;
  16959. var engine = this.getEngine();
  16960. var scene = this.getScene();
  16961. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16962. this._cache.fov = this.fov;
  16963. this._cache.fovMode = this.fovMode;
  16964. this._cache.aspectRatio = engine.getAspectRatio(this);
  16965. if (this.minZ <= 0) {
  16966. this.minZ = 0.1;
  16967. }
  16968. if (scene.useRightHandedSystem) {
  16969. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16970. }
  16971. else {
  16972. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16973. }
  16974. }
  16975. else {
  16976. var halfWidth = engine.getRenderWidth() / 2.0;
  16977. var halfHeight = engine.getRenderHeight() / 2.0;
  16978. if (scene.useRightHandedSystem) {
  16979. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16980. }
  16981. else {
  16982. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16983. }
  16984. this._cache.orthoLeft = this.orthoLeft;
  16985. this._cache.orthoRight = this.orthoRight;
  16986. this._cache.orthoBottom = this.orthoBottom;
  16987. this._cache.orthoTop = this.orthoTop;
  16988. this._cache.renderWidth = engine.getRenderWidth();
  16989. this._cache.renderHeight = engine.getRenderHeight();
  16990. }
  16991. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  16992. return this._projectionMatrix;
  16993. };
  16994. Camera.prototype.getTranformationMatrix = function () {
  16995. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16996. return this._transformMatrix;
  16997. };
  16998. Camera.prototype.updateFrustumPlanes = function () {
  16999. if (!this._refreshFrustumPlanes) {
  17000. return;
  17001. }
  17002. this.getTranformationMatrix();
  17003. if (!this._frustumPlanes) {
  17004. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17005. }
  17006. else {
  17007. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17008. }
  17009. this._refreshFrustumPlanes = false;
  17010. };
  17011. Camera.prototype.isInFrustum = function (target) {
  17012. this.updateFrustumPlanes();
  17013. return target.isInFrustum(this._frustumPlanes);
  17014. };
  17015. Camera.prototype.isCompletelyInFrustum = function (target) {
  17016. this.updateFrustumPlanes();
  17017. return target.isCompletelyInFrustum(this._frustumPlanes);
  17018. };
  17019. Camera.prototype.getForwardRay = function (length, transform, origin) {
  17020. if (length === void 0) { length = 100; }
  17021. if (!transform) {
  17022. transform = this.getWorldMatrix();
  17023. }
  17024. if (!origin) {
  17025. origin = this.position;
  17026. }
  17027. var forward = new BABYLON.Vector3(0, 0, 1);
  17028. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  17029. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  17030. return new BABYLON.Ray(origin, direction, length);
  17031. };
  17032. Camera.prototype.dispose = function () {
  17033. // Observables
  17034. this.onViewMatrixChangedObservable.clear();
  17035. this.onProjectionMatrixChangedObservable.clear();
  17036. this.onAfterCheckInputsObservable.clear();
  17037. this.onRestoreStateObservable.clear();
  17038. // Inputs
  17039. if (this.inputs) {
  17040. this.inputs.clear();
  17041. }
  17042. // Animations
  17043. this.getScene().stopAnimation(this);
  17044. // Remove from scene
  17045. this.getScene().removeCamera(this);
  17046. while (this._rigCameras.length > 0) {
  17047. var camera = this._rigCameras.pop();
  17048. if (camera) {
  17049. camera.dispose();
  17050. }
  17051. }
  17052. // Postprocesses
  17053. if (this._rigPostProcess) {
  17054. this._rigPostProcess.dispose(this);
  17055. this._rigPostProcess = null;
  17056. this._postProcesses = [];
  17057. }
  17058. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  17059. this._rigPostProcess = null;
  17060. this._postProcesses = [];
  17061. }
  17062. else {
  17063. var i = this._postProcesses.length;
  17064. while (--i >= 0) {
  17065. this._postProcesses[i].dispose(this);
  17066. }
  17067. }
  17068. // Render targets
  17069. var i = this.customRenderTargets.length;
  17070. while (--i >= 0) {
  17071. this.customRenderTargets[i].dispose();
  17072. }
  17073. this.customRenderTargets = [];
  17074. // Active Meshes
  17075. this._activeMeshes.dispose();
  17076. _super.prototype.dispose.call(this);
  17077. };
  17078. Object.defineProperty(Camera.prototype, "leftCamera", {
  17079. // ---- Camera rigs section ----
  17080. get: function () {
  17081. if (this._rigCameras.length < 1) {
  17082. return null;
  17083. }
  17084. return this._rigCameras[0];
  17085. },
  17086. enumerable: true,
  17087. configurable: true
  17088. });
  17089. Object.defineProperty(Camera.prototype, "rightCamera", {
  17090. get: function () {
  17091. if (this._rigCameras.length < 2) {
  17092. return null;
  17093. }
  17094. return this._rigCameras[1];
  17095. },
  17096. enumerable: true,
  17097. configurable: true
  17098. });
  17099. Camera.prototype.getLeftTarget = function () {
  17100. if (this._rigCameras.length < 1) {
  17101. return null;
  17102. }
  17103. return this._rigCameras[0].getTarget();
  17104. };
  17105. Camera.prototype.getRightTarget = function () {
  17106. if (this._rigCameras.length < 2) {
  17107. return null;
  17108. }
  17109. return this._rigCameras[1].getTarget();
  17110. };
  17111. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  17112. if (this.cameraRigMode === mode) {
  17113. return;
  17114. }
  17115. while (this._rigCameras.length > 0) {
  17116. var camera = this._rigCameras.pop();
  17117. if (camera) {
  17118. camera.dispose();
  17119. }
  17120. }
  17121. this.cameraRigMode = mode;
  17122. this._cameraRigParams = {};
  17123. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  17124. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  17125. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  17126. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  17127. // create the rig cameras, unless none
  17128. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  17129. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  17130. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  17131. if (leftCamera && rightCamera) {
  17132. this._rigCameras.push(leftCamera);
  17133. this._rigCameras.push(rightCamera);
  17134. }
  17135. }
  17136. switch (this.cameraRigMode) {
  17137. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  17138. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  17139. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  17140. break;
  17141. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  17142. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  17143. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  17144. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  17145. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  17146. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  17147. break;
  17148. case Camera.RIG_MODE_VR:
  17149. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  17150. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  17151. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  17152. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  17153. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  17154. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  17155. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  17156. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  17157. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  17158. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  17159. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  17160. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  17161. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  17162. if (metrics.compensateDistortion) {
  17163. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  17164. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  17165. }
  17166. break;
  17167. case Camera.RIG_MODE_WEBVR:
  17168. if (rigParams.vrDisplay) {
  17169. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  17170. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  17171. //Left eye
  17172. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  17173. this._rigCameras[0].setCameraRigParameter("left", true);
  17174. //leaving this for future reference
  17175. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  17176. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  17177. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  17178. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  17179. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  17180. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  17181. this._rigCameras[0].parent = this;
  17182. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  17183. //Right eye
  17184. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  17185. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  17186. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  17187. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  17188. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  17189. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  17190. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  17191. this._rigCameras[1].parent = this;
  17192. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  17193. if (Camera.UseAlternateWebVRRendering) {
  17194. this._rigCameras[1]._skipRendering = true;
  17195. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  17196. }
  17197. }
  17198. break;
  17199. }
  17200. this._cascadePostProcessesToRigCams();
  17201. this.update();
  17202. };
  17203. Camera.prototype._getVRProjectionMatrix = function () {
  17204. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  17205. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  17206. return this._projectionMatrix;
  17207. };
  17208. Camera.prototype._updateCameraRotationMatrix = function () {
  17209. //Here for WebVR
  17210. };
  17211. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  17212. //Here for WebVR
  17213. };
  17214. /**
  17215. * This function MUST be overwritten by the different WebVR cameras available.
  17216. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  17217. */
  17218. Camera.prototype._getWebVRProjectionMatrix = function () {
  17219. return BABYLON.Matrix.Identity();
  17220. };
  17221. /**
  17222. * This function MUST be overwritten by the different WebVR cameras available.
  17223. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  17224. */
  17225. Camera.prototype._getWebVRViewMatrix = function () {
  17226. return BABYLON.Matrix.Identity();
  17227. };
  17228. Camera.prototype.setCameraRigParameter = function (name, value) {
  17229. if (!this._cameraRigParams) {
  17230. this._cameraRigParams = {};
  17231. }
  17232. this._cameraRigParams[name] = value;
  17233. //provisionnally:
  17234. if (name === "interaxialDistance") {
  17235. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  17236. }
  17237. };
  17238. /**
  17239. * needs to be overridden by children so sub has required properties to be copied
  17240. */
  17241. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  17242. return null;
  17243. };
  17244. /**
  17245. * May need to be overridden by children
  17246. */
  17247. Camera.prototype._updateRigCameras = function () {
  17248. for (var i = 0; i < this._rigCameras.length; i++) {
  17249. this._rigCameras[i].minZ = this.minZ;
  17250. this._rigCameras[i].maxZ = this.maxZ;
  17251. this._rigCameras[i].fov = this.fov;
  17252. }
  17253. // only update viewport when ANAGLYPH
  17254. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  17255. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  17256. }
  17257. };
  17258. Camera.prototype._setupInputs = function () {
  17259. };
  17260. Camera.prototype.serialize = function () {
  17261. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  17262. // Type
  17263. serializationObject.type = this.getClassName();
  17264. // Parent
  17265. if (this.parent) {
  17266. serializationObject.parentId = this.parent.id;
  17267. }
  17268. if (this.inputs) {
  17269. this.inputs.serialize(serializationObject);
  17270. }
  17271. // Animations
  17272. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17273. serializationObject.ranges = this.serializeAnimationRanges();
  17274. return serializationObject;
  17275. };
  17276. Camera.prototype.clone = function (name) {
  17277. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  17278. };
  17279. Camera.prototype.getDirection = function (localAxis) {
  17280. var result = BABYLON.Vector3.Zero();
  17281. this.getDirectionToRef(localAxis, result);
  17282. return result;
  17283. };
  17284. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  17285. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  17286. };
  17287. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  17288. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  17289. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  17290. switch (type) {
  17291. case "ArcRotateCamera":
  17292. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  17293. case "DeviceOrientationCamera":
  17294. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  17295. case "FollowCamera":
  17296. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  17297. case "ArcFollowCamera":
  17298. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  17299. case "GamepadCamera":
  17300. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  17301. case "TouchCamera":
  17302. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  17303. case "VirtualJoysticksCamera":
  17304. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  17305. case "WebVRFreeCamera":
  17306. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  17307. case "WebVRGamepadCamera":
  17308. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  17309. case "VRDeviceOrientationFreeCamera":
  17310. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  17311. case "VRDeviceOrientationGamepadCamera":
  17312. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  17313. case "AnaglyphArcRotateCamera":
  17314. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17315. case "AnaglyphFreeCamera":
  17316. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17317. case "AnaglyphGamepadCamera":
  17318. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17319. case "AnaglyphUniversalCamera":
  17320. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17321. case "StereoscopicArcRotateCamera":
  17322. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17323. case "StereoscopicFreeCamera":
  17324. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17325. case "StereoscopicGamepadCamera":
  17326. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17327. case "StereoscopicUniversalCamera":
  17328. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17329. case "FreeCamera":// Forcing Universal here
  17330. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  17331. default:// Universal Camera is the default value
  17332. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  17333. }
  17334. };
  17335. Camera.prototype.computeWorldMatrix = function () {
  17336. return this.getWorldMatrix();
  17337. };
  17338. Camera.Parse = function (parsedCamera, scene) {
  17339. var type = parsedCamera.type;
  17340. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  17341. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  17342. // Parent
  17343. if (parsedCamera.parentId) {
  17344. camera._waitingParentId = parsedCamera.parentId;
  17345. }
  17346. //If camera has an input manager, let it parse inputs settings
  17347. if (camera.inputs) {
  17348. camera.inputs.parse(parsedCamera);
  17349. camera._setupInputs();
  17350. }
  17351. if (camera.setPosition) {
  17352. camera.position.copyFromFloats(0, 0, 0);
  17353. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  17354. }
  17355. // Target
  17356. if (parsedCamera.target) {
  17357. if (camera.setTarget) {
  17358. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  17359. }
  17360. }
  17361. // Apply 3d rig, when found
  17362. if (parsedCamera.cameraRigMode) {
  17363. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  17364. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  17365. }
  17366. // Animations
  17367. if (parsedCamera.animations) {
  17368. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  17369. var parsedAnimation = parsedCamera.animations[animationIndex];
  17370. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17371. }
  17372. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  17373. }
  17374. if (parsedCamera.autoAnimate) {
  17375. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  17376. }
  17377. return camera;
  17378. };
  17379. // Statics
  17380. Camera._PERSPECTIVE_CAMERA = 0;
  17381. Camera._ORTHOGRAPHIC_CAMERA = 1;
  17382. Camera._FOVMODE_VERTICAL_FIXED = 0;
  17383. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  17384. Camera._RIG_MODE_NONE = 0;
  17385. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  17386. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  17387. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  17388. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  17389. Camera._RIG_MODE_VR = 20;
  17390. Camera._RIG_MODE_WEBVR = 21;
  17391. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  17392. Camera.UseAlternateWebVRRendering = false;
  17393. __decorate([
  17394. BABYLON.serializeAsVector3()
  17395. ], Camera.prototype, "position", void 0);
  17396. __decorate([
  17397. BABYLON.serializeAsVector3()
  17398. ], Camera.prototype, "upVector", void 0);
  17399. __decorate([
  17400. BABYLON.serialize()
  17401. ], Camera.prototype, "orthoLeft", void 0);
  17402. __decorate([
  17403. BABYLON.serialize()
  17404. ], Camera.prototype, "orthoRight", void 0);
  17405. __decorate([
  17406. BABYLON.serialize()
  17407. ], Camera.prototype, "orthoBottom", void 0);
  17408. __decorate([
  17409. BABYLON.serialize()
  17410. ], Camera.prototype, "orthoTop", void 0);
  17411. __decorate([
  17412. BABYLON.serialize()
  17413. ], Camera.prototype, "fov", void 0);
  17414. __decorate([
  17415. BABYLON.serialize()
  17416. ], Camera.prototype, "minZ", void 0);
  17417. __decorate([
  17418. BABYLON.serialize()
  17419. ], Camera.prototype, "maxZ", void 0);
  17420. __decorate([
  17421. BABYLON.serialize()
  17422. ], Camera.prototype, "inertia", void 0);
  17423. __decorate([
  17424. BABYLON.serialize()
  17425. ], Camera.prototype, "mode", void 0);
  17426. __decorate([
  17427. BABYLON.serialize()
  17428. ], Camera.prototype, "layerMask", void 0);
  17429. __decorate([
  17430. BABYLON.serialize()
  17431. ], Camera.prototype, "fovMode", void 0);
  17432. __decorate([
  17433. BABYLON.serialize()
  17434. ], Camera.prototype, "cameraRigMode", void 0);
  17435. __decorate([
  17436. BABYLON.serialize()
  17437. ], Camera.prototype, "interaxialDistance", void 0);
  17438. __decorate([
  17439. BABYLON.serialize()
  17440. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  17441. return Camera;
  17442. }(BABYLON.Node));
  17443. BABYLON.Camera = Camera;
  17444. })(BABYLON || (BABYLON = {}));
  17445. //# sourceMappingURL=babylon.camera.js.map
  17446. var BABYLON;
  17447. (function (BABYLON) {
  17448. var RenderingManager = /** @class */ (function () {
  17449. function RenderingManager(scene) {
  17450. this._renderingGroups = new Array();
  17451. this._autoClearDepthStencil = {};
  17452. this._customOpaqueSortCompareFn = {};
  17453. this._customAlphaTestSortCompareFn = {};
  17454. this._customTransparentSortCompareFn = {};
  17455. this._renderinGroupInfo = null;
  17456. this._scene = scene;
  17457. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  17458. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  17459. }
  17460. }
  17461. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  17462. if (depth === void 0) { depth = true; }
  17463. if (stencil === void 0) { stencil = true; }
  17464. if (this._depthStencilBufferAlreadyCleaned) {
  17465. return;
  17466. }
  17467. this._scene.getEngine().clear(null, false, depth, stencil);
  17468. this._depthStencilBufferAlreadyCleaned = true;
  17469. };
  17470. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  17471. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  17472. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  17473. var info = null;
  17474. if (observable) {
  17475. if (!this._renderinGroupInfo) {
  17476. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  17477. }
  17478. info = this._renderinGroupInfo;
  17479. info.scene = this._scene;
  17480. info.camera = this._scene.activeCamera;
  17481. }
  17482. // Dispatch sprites
  17483. if (renderSprites) {
  17484. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  17485. var manager = this._scene.spriteManagers[index];
  17486. this.dispatchSprites(manager);
  17487. }
  17488. }
  17489. // Render
  17490. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  17491. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  17492. var renderingGroup = this._renderingGroups[index];
  17493. if (!renderingGroup && !observable)
  17494. continue;
  17495. var renderingGroupMask = 0;
  17496. // Fire PRECLEAR stage
  17497. if (observable && info) {
  17498. renderingGroupMask = Math.pow(2, index);
  17499. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  17500. info.renderingGroupId = index;
  17501. observable.notifyObservers(info, renderingGroupMask);
  17502. }
  17503. // Clear depth/stencil if needed
  17504. if (RenderingManager.AUTOCLEAR) {
  17505. var autoClear = this._autoClearDepthStencil[index];
  17506. if (autoClear && autoClear.autoClear) {
  17507. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  17508. }
  17509. }
  17510. if (observable && info) {
  17511. // Fire PREOPAQUE stage
  17512. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  17513. observable.notifyObservers(info, renderingGroupMask);
  17514. // Fire PRETRANSPARENT stage
  17515. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  17516. observable.notifyObservers(info, renderingGroupMask);
  17517. }
  17518. if (renderingGroup)
  17519. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  17520. // Fire POSTTRANSPARENT stage
  17521. if (observable && info) {
  17522. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  17523. observable.notifyObservers(info, renderingGroupMask);
  17524. }
  17525. }
  17526. };
  17527. RenderingManager.prototype.reset = function () {
  17528. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  17529. var renderingGroup = this._renderingGroups[index];
  17530. if (renderingGroup) {
  17531. renderingGroup.prepare();
  17532. }
  17533. }
  17534. };
  17535. RenderingManager.prototype.dispose = function () {
  17536. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  17537. var renderingGroup = this._renderingGroups[index];
  17538. if (renderingGroup) {
  17539. renderingGroup.dispose();
  17540. }
  17541. }
  17542. this._renderingGroups.length = 0;
  17543. };
  17544. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  17545. if (!this._renderingGroups[renderingGroupId]) {
  17546. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  17547. }
  17548. };
  17549. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  17550. var renderingGroupId = spriteManager.renderingGroupId || 0;
  17551. this._prepareRenderingGroup(renderingGroupId);
  17552. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  17553. };
  17554. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  17555. var renderingGroupId = particleSystem.renderingGroupId || 0;
  17556. this._prepareRenderingGroup(renderingGroupId);
  17557. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  17558. };
  17559. RenderingManager.prototype.dispatch = function (subMesh) {
  17560. var mesh = subMesh.getMesh();
  17561. var renderingGroupId = mesh.renderingGroupId || 0;
  17562. this._prepareRenderingGroup(renderingGroupId);
  17563. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  17564. };
  17565. /**
  17566. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  17567. * This allowed control for front to back rendering or reversly depending of the special needs.
  17568. *
  17569. * @param renderingGroupId The rendering group id corresponding to its index
  17570. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  17571. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  17572. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  17573. */
  17574. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17575. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17576. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17577. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17578. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  17579. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  17580. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  17581. if (this._renderingGroups[renderingGroupId]) {
  17582. var group = this._renderingGroups[renderingGroupId];
  17583. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  17584. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  17585. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  17586. }
  17587. };
  17588. /**
  17589. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  17590. *
  17591. * @param renderingGroupId The rendering group id corresponding to its index
  17592. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  17593. * @param depth Automatically clears depth between groups if true and autoClear is true.
  17594. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  17595. */
  17596. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  17597. if (depth === void 0) { depth = true; }
  17598. if (stencil === void 0) { stencil = true; }
  17599. this._autoClearDepthStencil[renderingGroupId] = {
  17600. autoClear: autoClearDepthStencil,
  17601. depth: depth,
  17602. stencil: stencil
  17603. };
  17604. };
  17605. /**
  17606. * The max id used for rendering groups (not included)
  17607. */
  17608. RenderingManager.MAX_RENDERINGGROUPS = 4;
  17609. /**
  17610. * The min id used for rendering groups (included)
  17611. */
  17612. RenderingManager.MIN_RENDERINGGROUPS = 0;
  17613. /**
  17614. * Used to globally prevent autoclearing scenes.
  17615. */
  17616. RenderingManager.AUTOCLEAR = true;
  17617. return RenderingManager;
  17618. }());
  17619. BABYLON.RenderingManager = RenderingManager;
  17620. })(BABYLON || (BABYLON = {}));
  17621. //# sourceMappingURL=babylon.renderingManager.js.map
  17622. var BABYLON;
  17623. (function (BABYLON) {
  17624. var RenderingGroup = /** @class */ (function () {
  17625. /**
  17626. * Creates a new rendering group.
  17627. * @param index The rendering group index
  17628. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  17629. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  17630. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  17631. */
  17632. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17633. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17634. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17635. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17636. this.index = index;
  17637. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  17638. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  17639. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  17640. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  17641. this._particleSystems = new BABYLON.SmartArray(256);
  17642. this._spriteManagers = new BABYLON.SmartArray(256);
  17643. this._edgesRenderers = new BABYLON.SmartArray(16);
  17644. this._scene = scene;
  17645. this.opaqueSortCompareFn = opaqueSortCompareFn;
  17646. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  17647. this.transparentSortCompareFn = transparentSortCompareFn;
  17648. }
  17649. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  17650. /**
  17651. * Set the opaque sort comparison function.
  17652. * If null the sub meshes will be render in the order they were created
  17653. */
  17654. set: function (value) {
  17655. this._opaqueSortCompareFn = value;
  17656. if (value) {
  17657. this._renderOpaque = this.renderOpaqueSorted;
  17658. }
  17659. else {
  17660. this._renderOpaque = RenderingGroup.renderUnsorted;
  17661. }
  17662. },
  17663. enumerable: true,
  17664. configurable: true
  17665. });
  17666. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  17667. /**
  17668. * Set the alpha test sort comparison function.
  17669. * If null the sub meshes will be render in the order they were created
  17670. */
  17671. set: function (value) {
  17672. this._alphaTestSortCompareFn = value;
  17673. if (value) {
  17674. this._renderAlphaTest = this.renderAlphaTestSorted;
  17675. }
  17676. else {
  17677. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  17678. }
  17679. },
  17680. enumerable: true,
  17681. configurable: true
  17682. });
  17683. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  17684. /**
  17685. * Set the transparent sort comparison function.
  17686. * If null the sub meshes will be render in the order they were created
  17687. */
  17688. set: function (value) {
  17689. if (value) {
  17690. this._transparentSortCompareFn = value;
  17691. }
  17692. else {
  17693. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  17694. }
  17695. this._renderTransparent = this.renderTransparentSorted;
  17696. },
  17697. enumerable: true,
  17698. configurable: true
  17699. });
  17700. /**
  17701. * Render all the sub meshes contained in the group.
  17702. * @param customRenderFunction Used to override the default render behaviour of the group.
  17703. * @returns true if rendered some submeshes.
  17704. */
  17705. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  17706. if (customRenderFunction) {
  17707. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  17708. return;
  17709. }
  17710. var engine = this._scene.getEngine();
  17711. // Depth only
  17712. if (this._depthOnlySubMeshes.length !== 0) {
  17713. engine.setAlphaTesting(true);
  17714. engine.setColorWrite(false);
  17715. this._renderAlphaTest(this._depthOnlySubMeshes);
  17716. engine.setAlphaTesting(false);
  17717. engine.setColorWrite(true);
  17718. }
  17719. // Opaque
  17720. if (this._opaqueSubMeshes.length !== 0) {
  17721. this._renderOpaque(this._opaqueSubMeshes);
  17722. }
  17723. // Alpha test
  17724. if (this._alphaTestSubMeshes.length !== 0) {
  17725. engine.setAlphaTesting(true);
  17726. this._renderAlphaTest(this._alphaTestSubMeshes);
  17727. engine.setAlphaTesting(false);
  17728. }
  17729. var stencilState = engine.getStencilBuffer();
  17730. engine.setStencilBuffer(false);
  17731. // Sprites
  17732. if (renderSprites) {
  17733. this._renderSprites();
  17734. }
  17735. // Particles
  17736. if (renderParticles) {
  17737. this._renderParticles(activeMeshes);
  17738. }
  17739. if (this.onBeforeTransparentRendering) {
  17740. this.onBeforeTransparentRendering();
  17741. }
  17742. // Transparent
  17743. if (this._transparentSubMeshes.length !== 0) {
  17744. this._renderTransparent(this._transparentSubMeshes);
  17745. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17746. }
  17747. // Set back stencil to false in case it changes before the edge renderer.
  17748. engine.setStencilBuffer(false);
  17749. // Edges
  17750. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  17751. this._edgesRenderers.data[edgesRendererIndex].render();
  17752. }
  17753. // Restore Stencil state.
  17754. engine.setStencilBuffer(stencilState);
  17755. };
  17756. /**
  17757. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  17758. * @param subMeshes The submeshes to render
  17759. */
  17760. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  17761. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  17762. };
  17763. /**
  17764. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  17765. * @param subMeshes The submeshes to render
  17766. */
  17767. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  17768. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  17769. };
  17770. /**
  17771. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  17772. * @param subMeshes The submeshes to render
  17773. */
  17774. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  17775. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  17776. };
  17777. /**
  17778. * Renders the submeshes in a specified order.
  17779. * @param subMeshes The submeshes to sort before render
  17780. * @param sortCompareFn The comparison function use to sort
  17781. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  17782. * @param transparent Specifies to activate blending if true
  17783. */
  17784. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  17785. var subIndex = 0;
  17786. var subMesh;
  17787. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  17788. for (; subIndex < subMeshes.length; subIndex++) {
  17789. subMesh = subMeshes.data[subIndex];
  17790. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  17791. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  17792. }
  17793. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  17794. if (sortCompareFn) {
  17795. sortedArray.sort(sortCompareFn);
  17796. }
  17797. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  17798. subMesh = sortedArray[subIndex];
  17799. if (transparent) {
  17800. var material = subMesh.getMaterial();
  17801. if (material && material.needDepthPrePass) {
  17802. var engine = material.getScene().getEngine();
  17803. engine.setColorWrite(false);
  17804. engine.setAlphaTesting(true);
  17805. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17806. subMesh.render(false);
  17807. engine.setAlphaTesting(false);
  17808. engine.setColorWrite(true);
  17809. }
  17810. }
  17811. subMesh.render(transparent);
  17812. }
  17813. };
  17814. /**
  17815. * Renders the submeshes in the order they were dispatched (no sort applied).
  17816. * @param subMeshes The submeshes to render
  17817. */
  17818. RenderingGroup.renderUnsorted = function (subMeshes) {
  17819. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  17820. var submesh = subMeshes.data[subIndex];
  17821. submesh.render(false);
  17822. }
  17823. };
  17824. /**
  17825. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17826. * are rendered back to front if in the same alpha index.
  17827. *
  17828. * @param a The first submesh
  17829. * @param b The second submesh
  17830. * @returns The result of the comparison
  17831. */
  17832. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  17833. // Alpha index first
  17834. if (a._alphaIndex > b._alphaIndex) {
  17835. return 1;
  17836. }
  17837. if (a._alphaIndex < b._alphaIndex) {
  17838. return -1;
  17839. }
  17840. // Then distance to camera
  17841. return RenderingGroup.backToFrontSortCompare(a, b);
  17842. };
  17843. /**
  17844. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17845. * are rendered back to front.
  17846. *
  17847. * @param a The first submesh
  17848. * @param b The second submesh
  17849. * @returns The result of the comparison
  17850. */
  17851. RenderingGroup.backToFrontSortCompare = function (a, b) {
  17852. // Then distance to camera
  17853. if (a._distanceToCamera < b._distanceToCamera) {
  17854. return 1;
  17855. }
  17856. if (a._distanceToCamera > b._distanceToCamera) {
  17857. return -1;
  17858. }
  17859. return 0;
  17860. };
  17861. /**
  17862. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17863. * are rendered front to back (prevent overdraw).
  17864. *
  17865. * @param a The first submesh
  17866. * @param b The second submesh
  17867. * @returns The result of the comparison
  17868. */
  17869. RenderingGroup.frontToBackSortCompare = function (a, b) {
  17870. // Then distance to camera
  17871. if (a._distanceToCamera < b._distanceToCamera) {
  17872. return -1;
  17873. }
  17874. if (a._distanceToCamera > b._distanceToCamera) {
  17875. return 1;
  17876. }
  17877. return 0;
  17878. };
  17879. /**
  17880. * Resets the different lists of submeshes to prepare a new frame.
  17881. */
  17882. RenderingGroup.prototype.prepare = function () {
  17883. this._opaqueSubMeshes.reset();
  17884. this._transparentSubMeshes.reset();
  17885. this._alphaTestSubMeshes.reset();
  17886. this._depthOnlySubMeshes.reset();
  17887. this._particleSystems.reset();
  17888. this._spriteManagers.reset();
  17889. this._edgesRenderers.reset();
  17890. };
  17891. RenderingGroup.prototype.dispose = function () {
  17892. this._opaqueSubMeshes.dispose();
  17893. this._transparentSubMeshes.dispose();
  17894. this._alphaTestSubMeshes.dispose();
  17895. this._depthOnlySubMeshes.dispose();
  17896. this._particleSystems.dispose();
  17897. this._spriteManagers.dispose();
  17898. this._edgesRenderers.dispose();
  17899. };
  17900. /**
  17901. * Inserts the submesh in its correct queue depending on its material.
  17902. * @param subMesh The submesh to dispatch
  17903. */
  17904. RenderingGroup.prototype.dispatch = function (subMesh) {
  17905. var material = subMesh.getMaterial();
  17906. var mesh = subMesh.getMesh();
  17907. if (!material) {
  17908. return;
  17909. }
  17910. if (material.needAlphaBlendingForMesh(mesh)) {
  17911. this._transparentSubMeshes.push(subMesh);
  17912. }
  17913. else if (material.needAlphaTesting()) {
  17914. if (material.needDepthPrePass) {
  17915. this._depthOnlySubMeshes.push(subMesh);
  17916. }
  17917. this._alphaTestSubMeshes.push(subMesh);
  17918. }
  17919. else {
  17920. if (material.needDepthPrePass) {
  17921. this._depthOnlySubMeshes.push(subMesh);
  17922. }
  17923. this._opaqueSubMeshes.push(subMesh); // Opaque
  17924. }
  17925. if (mesh._edgesRenderer) {
  17926. this._edgesRenderers.push(mesh._edgesRenderer);
  17927. }
  17928. };
  17929. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  17930. this._spriteManagers.push(spriteManager);
  17931. };
  17932. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  17933. this._particleSystems.push(particleSystem);
  17934. };
  17935. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  17936. if (this._particleSystems.length === 0) {
  17937. return;
  17938. }
  17939. // Particles
  17940. var activeCamera = this._scene.activeCamera;
  17941. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  17942. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  17943. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  17944. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  17945. continue;
  17946. }
  17947. var emitter = particleSystem.emitter;
  17948. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  17949. this._scene._activeParticles.addCount(particleSystem.render(), false);
  17950. }
  17951. }
  17952. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  17953. };
  17954. RenderingGroup.prototype._renderSprites = function () {
  17955. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  17956. return;
  17957. }
  17958. // Sprites
  17959. var activeCamera = this._scene.activeCamera;
  17960. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  17961. for (var id = 0; id < this._spriteManagers.length; id++) {
  17962. var spriteManager = this._spriteManagers.data[id];
  17963. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  17964. spriteManager.render();
  17965. }
  17966. }
  17967. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  17968. };
  17969. return RenderingGroup;
  17970. }());
  17971. BABYLON.RenderingGroup = RenderingGroup;
  17972. })(BABYLON || (BABYLON = {}));
  17973. //# sourceMappingURL=babylon.renderingGroup.js.map
  17974. var BABYLON;
  17975. (function (BABYLON) {
  17976. var ClickInfo = /** @class */ (function () {
  17977. function ClickInfo() {
  17978. this._singleClick = false;
  17979. this._doubleClick = false;
  17980. this._hasSwiped = false;
  17981. this._ignore = false;
  17982. }
  17983. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  17984. get: function () {
  17985. return this._singleClick;
  17986. },
  17987. set: function (b) {
  17988. this._singleClick = b;
  17989. },
  17990. enumerable: true,
  17991. configurable: true
  17992. });
  17993. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  17994. get: function () {
  17995. return this._doubleClick;
  17996. },
  17997. set: function (b) {
  17998. this._doubleClick = b;
  17999. },
  18000. enumerable: true,
  18001. configurable: true
  18002. });
  18003. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  18004. get: function () {
  18005. return this._hasSwiped;
  18006. },
  18007. set: function (b) {
  18008. this._hasSwiped = b;
  18009. },
  18010. enumerable: true,
  18011. configurable: true
  18012. });
  18013. Object.defineProperty(ClickInfo.prototype, "ignore", {
  18014. get: function () {
  18015. return this._ignore;
  18016. },
  18017. set: function (b) {
  18018. this._ignore = b;
  18019. },
  18020. enumerable: true,
  18021. configurable: true
  18022. });
  18023. return ClickInfo;
  18024. }());
  18025. /**
  18026. * This class is used by the onRenderingGroupObservable
  18027. */
  18028. var RenderingGroupInfo = /** @class */ (function () {
  18029. function RenderingGroupInfo() {
  18030. }
  18031. /**
  18032. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  18033. * This stage will be fired no matter what
  18034. */
  18035. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  18036. /**
  18037. * Called before opaque object are rendered.
  18038. * This stage will be fired only if there's 3D Opaque content to render
  18039. */
  18040. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  18041. /**
  18042. * Called after the opaque objects are rendered and before the transparent ones
  18043. * This stage will be fired only if there's 3D transparent content to render
  18044. */
  18045. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  18046. /**
  18047. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  18048. * This stage will be fired no matter what
  18049. */
  18050. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  18051. return RenderingGroupInfo;
  18052. }());
  18053. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  18054. /**
  18055. * Represents a scene to be rendered by the engine.
  18056. * @see http://doc.babylonjs.com/page.php?p=21911
  18057. */
  18058. var Scene = /** @class */ (function () {
  18059. /**
  18060. * @constructor
  18061. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  18062. */
  18063. function Scene(engine) {
  18064. // Members
  18065. this.autoClear = true;
  18066. this.autoClearDepthAndStencil = true;
  18067. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  18068. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  18069. this.forceWireframe = false;
  18070. this._forcePointsCloud = false;
  18071. this.forceShowBoundingBoxes = false;
  18072. this.animationsEnabled = true;
  18073. this.useConstantAnimationDeltaTime = false;
  18074. this.constantlyUpdateMeshUnderPointer = false;
  18075. this.hoverCursor = "pointer";
  18076. this.defaultCursor = "";
  18077. /**
  18078. * This is used to call preventDefault() on pointer down
  18079. * in order to block unwanted artifacts like system double clicks
  18080. */
  18081. this.preventDefaultOnPointerDown = true;
  18082. // Metadata
  18083. this.metadata = null;
  18084. /**
  18085. * An event triggered when the scene is disposed.
  18086. * @type {BABYLON.Observable}
  18087. */
  18088. this.onDisposeObservable = new BABYLON.Observable();
  18089. /**
  18090. * An event triggered before rendering the scene (right after animations and physics)
  18091. * @type {BABYLON.Observable}
  18092. */
  18093. this.onBeforeRenderObservable = new BABYLON.Observable();
  18094. /**
  18095. * An event triggered after rendering the scene
  18096. * @type {BABYLON.Observable}
  18097. */
  18098. this.onAfterRenderObservable = new BABYLON.Observable();
  18099. /**
  18100. * An event triggered before animating the scene
  18101. * @type {BABYLON.Observable}
  18102. */
  18103. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  18104. /**
  18105. * An event triggered after animations processing
  18106. * @type {BABYLON.Observable}
  18107. */
  18108. this.onAfterAnimationsObservable = new BABYLON.Observable();
  18109. /**
  18110. * An event triggered before draw calls are ready to be sent
  18111. * @type {BABYLON.Observable}
  18112. */
  18113. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  18114. /**
  18115. * An event triggered after draw calls have been sent
  18116. * @type {BABYLON.Observable}
  18117. */
  18118. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  18119. /**
  18120. * An event triggered when physic simulation is about to be run
  18121. * @type {BABYLON.Observable}
  18122. */
  18123. this.onBeforePhysicsObservable = new BABYLON.Observable();
  18124. /**
  18125. * An event triggered when physic simulation has been done
  18126. * @type {BABYLON.Observable}
  18127. */
  18128. this.onAfterPhysicsObservable = new BABYLON.Observable();
  18129. /**
  18130. * An event triggered when the scene is ready
  18131. * @type {BABYLON.Observable}
  18132. */
  18133. this.onReadyObservable = new BABYLON.Observable();
  18134. /**
  18135. * An event triggered before rendering a camera
  18136. * @type {BABYLON.Observable}
  18137. */
  18138. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  18139. /**
  18140. * An event triggered after rendering a camera
  18141. * @type {BABYLON.Observable}
  18142. */
  18143. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  18144. /**
  18145. * An event triggered when active meshes evaluation is about to start
  18146. * @type {BABYLON.Observable}
  18147. */
  18148. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  18149. /**
  18150. * An event triggered when active meshes evaluation is done
  18151. * @type {BABYLON.Observable}
  18152. */
  18153. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  18154. /**
  18155. * An event triggered when particles rendering is about to start
  18156. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  18157. * @type {BABYLON.Observable}
  18158. */
  18159. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  18160. /**
  18161. * An event triggered when particles rendering is done
  18162. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  18163. * @type {BABYLON.Observable}
  18164. */
  18165. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  18166. /**
  18167. * An event triggered when sprites rendering is about to start
  18168. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  18169. * @type {BABYLON.Observable}
  18170. */
  18171. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  18172. /**
  18173. * An event triggered when sprites rendering is done
  18174. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  18175. * @type {BABYLON.Observable}
  18176. */
  18177. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  18178. /**
  18179. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  18180. * @type {BABYLON.Observable}
  18181. */
  18182. this.onDataLoadedObservable = new BABYLON.Observable();
  18183. /**
  18184. * An event triggered when a camera is created
  18185. * @type {BABYLON.Observable}
  18186. */
  18187. this.onNewCameraAddedObservable = new BABYLON.Observable();
  18188. /**
  18189. * An event triggered when a camera is removed
  18190. * @type {BABYLON.Observable}
  18191. */
  18192. this.onCameraRemovedObservable = new BABYLON.Observable();
  18193. /**
  18194. * An event triggered when a light is created
  18195. * @type {BABYLON.Observable}
  18196. */
  18197. this.onNewLightAddedObservable = new BABYLON.Observable();
  18198. /**
  18199. * An event triggered when a light is removed
  18200. * @type {BABYLON.Observable}
  18201. */
  18202. this.onLightRemovedObservable = new BABYLON.Observable();
  18203. /**
  18204. * An event triggered when a geometry is created
  18205. * @type {BABYLON.Observable}
  18206. */
  18207. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  18208. /**
  18209. * An event triggered when a geometry is removed
  18210. * @type {BABYLON.Observable}
  18211. */
  18212. this.onGeometryRemovedObservable = new BABYLON.Observable();
  18213. /**
  18214. * An event triggered when a transform node is created
  18215. * @type {BABYLON.Observable}
  18216. */
  18217. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  18218. /**
  18219. * An event triggered when a transform node is removed
  18220. * @type {BABYLON.Observable}
  18221. */
  18222. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  18223. /**
  18224. * An event triggered when a mesh is created
  18225. * @type {BABYLON.Observable}
  18226. */
  18227. this.onNewMeshAddedObservable = new BABYLON.Observable();
  18228. /**
  18229. * An event triggered when a mesh is removed
  18230. * @type {BABYLON.Observable}
  18231. */
  18232. this.onMeshRemovedObservable = new BABYLON.Observable();
  18233. /**
  18234. * An event triggered when render targets are about to be rendered
  18235. * Can happen multiple times per frame.
  18236. * @type {BABYLON.Observable}
  18237. */
  18238. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  18239. /**
  18240. * An event triggered when render targets were rendered.
  18241. * Can happen multiple times per frame.
  18242. * @type {BABYLON.Observable}
  18243. */
  18244. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  18245. /**
  18246. * An event triggered before calculating deterministic simulation step
  18247. * @type {BABYLON.Observable}
  18248. */
  18249. this.onBeforeStepObservable = new BABYLON.Observable();
  18250. /**
  18251. * An event triggered after calculating deterministic simulation step
  18252. * @type {BABYLON.Observable}
  18253. */
  18254. this.onAfterStepObservable = new BABYLON.Observable();
  18255. /**
  18256. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  18257. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  18258. * 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)
  18259. */
  18260. this.onRenderingGroupObservable = new BABYLON.Observable();
  18261. // Animations
  18262. this.animations = [];
  18263. /**
  18264. * 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).
  18265. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  18266. */
  18267. this.onPrePointerObservable = new BABYLON.Observable();
  18268. /**
  18269. * Observable event triggered each time an input event is received from the rendering canvas
  18270. */
  18271. this.onPointerObservable = new BABYLON.Observable();
  18272. this._meshPickProceed = false;
  18273. this._currentPickResult = null;
  18274. this._previousPickResult = null;
  18275. this._totalPointersPressed = 0;
  18276. this._doubleClickOccured = false;
  18277. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  18278. this.cameraToUseForPointers = null;
  18279. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  18280. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  18281. this._startingPointerTime = 0;
  18282. this._previousStartingPointerTime = 0;
  18283. // Deterministic lockstep
  18284. this._timeAccumulator = 0;
  18285. this._currentStepId = 0;
  18286. this._currentInternalStep = 0;
  18287. // Keyboard
  18288. /**
  18289. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  18290. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  18291. */
  18292. this.onPreKeyboardObservable = new BABYLON.Observable();
  18293. /**
  18294. * Observable event triggered each time an keyboard event is received from the hosting window
  18295. */
  18296. this.onKeyboardObservable = new BABYLON.Observable();
  18297. // Coordinate system
  18298. /**
  18299. * use right-handed coordinate system on this scene.
  18300. * @type {boolean}
  18301. */
  18302. this._useRightHandedSystem = false;
  18303. // Fog
  18304. this._fogEnabled = true;
  18305. this._fogMode = Scene.FOGMODE_NONE;
  18306. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  18307. this.fogDensity = 0.1;
  18308. this.fogStart = 0;
  18309. this.fogEnd = 1000.0;
  18310. // Lights
  18311. /**
  18312. * is shadow enabled on this scene.
  18313. * @type {boolean}
  18314. */
  18315. this._shadowsEnabled = true;
  18316. /**
  18317. * is light enabled on this scene.
  18318. * @type {boolean}
  18319. */
  18320. this._lightsEnabled = true;
  18321. /**
  18322. * All of the lights added to this scene.
  18323. * @see BABYLON.Light
  18324. * @type {BABYLON.Light[]}
  18325. */
  18326. this.lights = new Array();
  18327. // Cameras
  18328. /** All of the cameras added to this scene. */
  18329. this.cameras = new Array();
  18330. /** All of the active cameras added to this scene. */
  18331. this.activeCameras = new Array();
  18332. // Meshes
  18333. /**
  18334. * All of the tranform nodes added to this scene.
  18335. * @see BABYLON.TransformNode
  18336. * @type {BABYLON.TransformNode[]}
  18337. */
  18338. this.transformNodes = new Array();
  18339. /**
  18340. * All of the (abstract) meshes added to this scene.
  18341. * @see BABYLON.AbstractMesh
  18342. * @type {BABYLON.AbstractMesh[]}
  18343. */
  18344. this.meshes = new Array();
  18345. /**
  18346. * All of the animation groups added to this scene.
  18347. * @see BABYLON.AnimationGroup
  18348. * @type {BABYLON.AnimationGroup[]}
  18349. */
  18350. this.animationGroups = new Array();
  18351. // Geometries
  18352. this._geometries = new Array();
  18353. this.materials = new Array();
  18354. this.multiMaterials = new Array();
  18355. // Textures
  18356. this._texturesEnabled = true;
  18357. this.textures = new Array();
  18358. // Particles
  18359. this.particlesEnabled = true;
  18360. this.particleSystems = new Array();
  18361. // Sprites
  18362. this.spritesEnabled = true;
  18363. this.spriteManagers = new Array();
  18364. // Layers
  18365. this.layers = new Array();
  18366. this.highlightLayers = new Array();
  18367. // Skeletons
  18368. this._skeletonsEnabled = true;
  18369. this.skeletons = new Array();
  18370. // Morph targets
  18371. this.morphTargetManagers = new Array();
  18372. // Lens flares
  18373. this.lensFlaresEnabled = true;
  18374. this.lensFlareSystems = new Array();
  18375. // Collisions
  18376. this.collisionsEnabled = true;
  18377. /** Defines the gravity applied to this scene */
  18378. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  18379. // Postprocesses
  18380. this.postProcesses = new Array();
  18381. this.postProcessesEnabled = true;
  18382. // Customs render targets
  18383. this.renderTargetsEnabled = true;
  18384. this.dumpNextRenderTargets = false;
  18385. this.customRenderTargets = new Array();
  18386. // Imported meshes
  18387. this.importedMeshesFiles = new Array();
  18388. // Probes
  18389. this.probesEnabled = true;
  18390. this.reflectionProbes = new Array();
  18391. this._actionManagers = new Array();
  18392. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  18393. // Procedural textures
  18394. this.proceduralTexturesEnabled = true;
  18395. this._proceduralTextures = new Array();
  18396. this.soundTracks = new Array();
  18397. this._audioEnabled = true;
  18398. this._headphone = false;
  18399. // Performance counters
  18400. this._totalVertices = new BABYLON.PerfCounter();
  18401. this._activeIndices = new BABYLON.PerfCounter();
  18402. this._activeParticles = new BABYLON.PerfCounter();
  18403. this._activeBones = new BABYLON.PerfCounter();
  18404. this._animationTime = 0;
  18405. this.animationTimeScale = 1;
  18406. this._renderId = 0;
  18407. this._executeWhenReadyTimeoutId = -1;
  18408. this._intermediateRendering = false;
  18409. this._viewUpdateFlag = -1;
  18410. this._projectionUpdateFlag = -1;
  18411. this._alternateViewUpdateFlag = -1;
  18412. this._alternateProjectionUpdateFlag = -1;
  18413. this._toBeDisposed = new BABYLON.SmartArray(256);
  18414. this._pendingData = new Array();
  18415. this._isDisposed = false;
  18416. this._activeMeshes = new BABYLON.SmartArray(256);
  18417. this._processedMaterials = new BABYLON.SmartArray(256);
  18418. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  18419. this._activeParticleSystems = new BABYLON.SmartArray(256);
  18420. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  18421. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  18422. this._activeAnimatables = new Array();
  18423. this._transformMatrix = BABYLON.Matrix.Zero();
  18424. this._useAlternateCameraConfiguration = false;
  18425. this._alternateRendering = false;
  18426. this.requireLightSorting = false;
  18427. this._activeMeshesFrozen = false;
  18428. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  18429. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  18430. this._engine.scenes.push(this);
  18431. this._uid = null;
  18432. this._renderingManager = new BABYLON.RenderingManager(this);
  18433. this.postProcessManager = new BABYLON.PostProcessManager(this);
  18434. if (BABYLON.OutlineRenderer) {
  18435. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  18436. }
  18437. if (BABYLON.Tools.IsWindowObjectExist()) {
  18438. this.attachControl();
  18439. }
  18440. //simplification queue
  18441. if (BABYLON.SimplificationQueue) {
  18442. this.simplificationQueue = new BABYLON.SimplificationQueue();
  18443. }
  18444. //collision coordinator initialization. For now legacy per default.
  18445. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  18446. // Uniform Buffer
  18447. this._createUbo();
  18448. // Default Image processing definition.
  18449. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  18450. }
  18451. Object.defineProperty(Scene, "FOGMODE_NONE", {
  18452. /** The fog is deactivated */
  18453. get: function () {
  18454. return Scene._FOGMODE_NONE;
  18455. },
  18456. enumerable: true,
  18457. configurable: true
  18458. });
  18459. Object.defineProperty(Scene, "FOGMODE_EXP", {
  18460. /** The fog density is following an exponential function */
  18461. get: function () {
  18462. return Scene._FOGMODE_EXP;
  18463. },
  18464. enumerable: true,
  18465. configurable: true
  18466. });
  18467. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  18468. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  18469. get: function () {
  18470. return Scene._FOGMODE_EXP2;
  18471. },
  18472. enumerable: true,
  18473. configurable: true
  18474. });
  18475. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  18476. /** The fog density is following a linear function. */
  18477. get: function () {
  18478. return Scene._FOGMODE_LINEAR;
  18479. },
  18480. enumerable: true,
  18481. configurable: true
  18482. });
  18483. Object.defineProperty(Scene.prototype, "environmentTexture", {
  18484. /**
  18485. * Texture used in all pbr material as the reflection texture.
  18486. * As in the majority of the scene they are the same (exception for multi room and so on),
  18487. * this is easier to reference from here than from all the materials.
  18488. */
  18489. get: function () {
  18490. return this._environmentTexture;
  18491. },
  18492. /**
  18493. * Texture used in all pbr material as the reflection texture.
  18494. * As in the majority of the scene they are the same (exception for multi room and so on),
  18495. * this is easier to set here than in all the materials.
  18496. */
  18497. set: function (value) {
  18498. if (this._environmentTexture === value) {
  18499. return;
  18500. }
  18501. this._environmentTexture = value;
  18502. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18503. },
  18504. enumerable: true,
  18505. configurable: true
  18506. });
  18507. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  18508. /**
  18509. * Default image processing configuration used either in the rendering
  18510. * Forward main pass or through the imageProcessingPostProcess if present.
  18511. * As in the majority of the scene they are the same (exception for multi camera),
  18512. * this is easier to reference from here than from all the materials and post process.
  18513. *
  18514. * No setter as we it is a shared configuration, you can set the values instead.
  18515. */
  18516. get: function () {
  18517. return this._imageProcessingConfiguration;
  18518. },
  18519. enumerable: true,
  18520. configurable: true
  18521. });
  18522. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  18523. get: function () {
  18524. return this._forcePointsCloud;
  18525. },
  18526. set: function (value) {
  18527. if (this._forcePointsCloud === value) {
  18528. return;
  18529. }
  18530. this._forcePointsCloud = value;
  18531. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18532. },
  18533. enumerable: true,
  18534. configurable: true
  18535. });
  18536. Object.defineProperty(Scene.prototype, "onDispose", {
  18537. /** A function to be executed when this scene is disposed. */
  18538. set: function (callback) {
  18539. if (this._onDisposeObserver) {
  18540. this.onDisposeObservable.remove(this._onDisposeObserver);
  18541. }
  18542. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18543. },
  18544. enumerable: true,
  18545. configurable: true
  18546. });
  18547. Object.defineProperty(Scene.prototype, "beforeRender", {
  18548. /** A function to be executed before rendering this scene */
  18549. set: function (callback) {
  18550. if (this._onBeforeRenderObserver) {
  18551. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  18552. }
  18553. if (callback) {
  18554. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  18555. }
  18556. },
  18557. enumerable: true,
  18558. configurable: true
  18559. });
  18560. Object.defineProperty(Scene.prototype, "afterRender", {
  18561. /** A function to be executed after rendering this scene */
  18562. set: function (callback) {
  18563. if (this._onAfterRenderObserver) {
  18564. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  18565. }
  18566. if (callback) {
  18567. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  18568. }
  18569. },
  18570. enumerable: true,
  18571. configurable: true
  18572. });
  18573. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  18574. set: function (callback) {
  18575. if (this._onBeforeCameraRenderObserver) {
  18576. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  18577. }
  18578. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  18579. },
  18580. enumerable: true,
  18581. configurable: true
  18582. });
  18583. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  18584. set: function (callback) {
  18585. if (this._onAfterCameraRenderObserver) {
  18586. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  18587. }
  18588. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  18589. },
  18590. enumerable: true,
  18591. configurable: true
  18592. });
  18593. Object.defineProperty(Scene.prototype, "gamepadManager", {
  18594. get: function () {
  18595. if (!this._gamepadManager) {
  18596. this._gamepadManager = new BABYLON.GamepadManager(this);
  18597. }
  18598. return this._gamepadManager;
  18599. },
  18600. enumerable: true,
  18601. configurable: true
  18602. });
  18603. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  18604. get: function () {
  18605. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  18606. },
  18607. enumerable: true,
  18608. configurable: true
  18609. });
  18610. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  18611. get: function () {
  18612. return this._useRightHandedSystem;
  18613. },
  18614. set: function (value) {
  18615. if (this._useRightHandedSystem === value) {
  18616. return;
  18617. }
  18618. this._useRightHandedSystem = value;
  18619. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18620. },
  18621. enumerable: true,
  18622. configurable: true
  18623. });
  18624. Scene.prototype.setStepId = function (newStepId) {
  18625. this._currentStepId = newStepId;
  18626. };
  18627. ;
  18628. Scene.prototype.getStepId = function () {
  18629. return this._currentStepId;
  18630. };
  18631. ;
  18632. Scene.prototype.getInternalStep = function () {
  18633. return this._currentInternalStep;
  18634. };
  18635. ;
  18636. Object.defineProperty(Scene.prototype, "fogEnabled", {
  18637. get: function () {
  18638. return this._fogEnabled;
  18639. },
  18640. /**
  18641. * is fog enabled on this scene.
  18642. */
  18643. set: function (value) {
  18644. if (this._fogEnabled === value) {
  18645. return;
  18646. }
  18647. this._fogEnabled = value;
  18648. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18649. },
  18650. enumerable: true,
  18651. configurable: true
  18652. });
  18653. Object.defineProperty(Scene.prototype, "fogMode", {
  18654. get: function () {
  18655. return this._fogMode;
  18656. },
  18657. set: function (value) {
  18658. if (this._fogMode === value) {
  18659. return;
  18660. }
  18661. this._fogMode = value;
  18662. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18663. },
  18664. enumerable: true,
  18665. configurable: true
  18666. });
  18667. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  18668. get: function () {
  18669. return this._shadowsEnabled;
  18670. },
  18671. set: function (value) {
  18672. if (this._shadowsEnabled === value) {
  18673. return;
  18674. }
  18675. this._shadowsEnabled = value;
  18676. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  18677. },
  18678. enumerable: true,
  18679. configurable: true
  18680. });
  18681. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  18682. get: function () {
  18683. return this._lightsEnabled;
  18684. },
  18685. set: function (value) {
  18686. if (this._lightsEnabled === value) {
  18687. return;
  18688. }
  18689. this._lightsEnabled = value;
  18690. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  18691. },
  18692. enumerable: true,
  18693. configurable: true
  18694. });
  18695. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  18696. /** The default material used on meshes when no material is affected */
  18697. get: function () {
  18698. if (!this._defaultMaterial) {
  18699. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  18700. }
  18701. return this._defaultMaterial;
  18702. },
  18703. /** The default material used on meshes when no material is affected */
  18704. set: function (value) {
  18705. this._defaultMaterial = value;
  18706. },
  18707. enumerable: true,
  18708. configurable: true
  18709. });
  18710. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  18711. get: function () {
  18712. return this._texturesEnabled;
  18713. },
  18714. set: function (value) {
  18715. if (this._texturesEnabled === value) {
  18716. return;
  18717. }
  18718. this._texturesEnabled = value;
  18719. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18720. },
  18721. enumerable: true,
  18722. configurable: true
  18723. });
  18724. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  18725. get: function () {
  18726. return this._skeletonsEnabled;
  18727. },
  18728. set: function (value) {
  18729. if (this._skeletonsEnabled === value) {
  18730. return;
  18731. }
  18732. this._skeletonsEnabled = value;
  18733. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  18734. },
  18735. enumerable: true,
  18736. configurable: true
  18737. });
  18738. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  18739. get: function () {
  18740. if (!this._postProcessRenderPipelineManager) {
  18741. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  18742. }
  18743. return this._postProcessRenderPipelineManager;
  18744. },
  18745. enumerable: true,
  18746. configurable: true
  18747. });
  18748. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  18749. get: function () {
  18750. if (!this._mainSoundTrack) {
  18751. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  18752. }
  18753. return this._mainSoundTrack;
  18754. },
  18755. enumerable: true,
  18756. configurable: true
  18757. });
  18758. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  18759. get: function () {
  18760. return this._alternateRendering;
  18761. },
  18762. enumerable: true,
  18763. configurable: true
  18764. });
  18765. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  18766. get: function () {
  18767. return this._frustumPlanes;
  18768. },
  18769. enumerable: true,
  18770. configurable: true
  18771. });
  18772. Object.defineProperty(Scene.prototype, "debugLayer", {
  18773. // Properties
  18774. get: function () {
  18775. if (!this._debugLayer) {
  18776. this._debugLayer = new BABYLON.DebugLayer(this);
  18777. }
  18778. return this._debugLayer;
  18779. },
  18780. enumerable: true,
  18781. configurable: true
  18782. });
  18783. Object.defineProperty(Scene.prototype, "workerCollisions", {
  18784. get: function () {
  18785. return this._workerCollisions;
  18786. },
  18787. set: function (enabled) {
  18788. if (!BABYLON.CollisionCoordinatorLegacy) {
  18789. return;
  18790. }
  18791. enabled = (enabled && !!Worker);
  18792. this._workerCollisions = enabled;
  18793. if (this.collisionCoordinator) {
  18794. this.collisionCoordinator.destroy();
  18795. }
  18796. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  18797. this.collisionCoordinator.init(this);
  18798. },
  18799. enumerable: true,
  18800. configurable: true
  18801. });
  18802. Object.defineProperty(Scene.prototype, "selectionOctree", {
  18803. get: function () {
  18804. return this._selectionOctree;
  18805. },
  18806. enumerable: true,
  18807. configurable: true
  18808. });
  18809. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  18810. /**
  18811. * The mesh that is currently under the pointer.
  18812. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  18813. */
  18814. get: function () {
  18815. return this._pointerOverMesh;
  18816. },
  18817. enumerable: true,
  18818. configurable: true
  18819. });
  18820. Object.defineProperty(Scene.prototype, "pointerX", {
  18821. /**
  18822. * Current on-screen X position of the pointer
  18823. * @return {number} X position of the pointer
  18824. */
  18825. get: function () {
  18826. return this._pointerX;
  18827. },
  18828. enumerable: true,
  18829. configurable: true
  18830. });
  18831. Object.defineProperty(Scene.prototype, "pointerY", {
  18832. /**
  18833. * Current on-screen Y position of the pointer
  18834. * @return {number} Y position of the pointer
  18835. */
  18836. get: function () {
  18837. return this._pointerY;
  18838. },
  18839. enumerable: true,
  18840. configurable: true
  18841. });
  18842. Scene.prototype.getCachedMaterial = function () {
  18843. return this._cachedMaterial;
  18844. };
  18845. Scene.prototype.getCachedEffect = function () {
  18846. return this._cachedEffect;
  18847. };
  18848. Scene.prototype.getCachedVisibility = function () {
  18849. return this._cachedVisibility;
  18850. };
  18851. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  18852. if (visibility === void 0) { visibility = 1; }
  18853. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  18854. };
  18855. Scene.prototype.getBoundingBoxRenderer = function () {
  18856. if (!this._boundingBoxRenderer) {
  18857. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  18858. }
  18859. return this._boundingBoxRenderer;
  18860. };
  18861. Scene.prototype.getOutlineRenderer = function () {
  18862. return this._outlineRenderer;
  18863. };
  18864. Scene.prototype.getEngine = function () {
  18865. return this._engine;
  18866. };
  18867. Scene.prototype.getTotalVertices = function () {
  18868. return this._totalVertices.current;
  18869. };
  18870. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  18871. get: function () {
  18872. return this._totalVertices;
  18873. },
  18874. enumerable: true,
  18875. configurable: true
  18876. });
  18877. Scene.prototype.getActiveIndices = function () {
  18878. return this._activeIndices.current;
  18879. };
  18880. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  18881. get: function () {
  18882. return this._activeIndices;
  18883. },
  18884. enumerable: true,
  18885. configurable: true
  18886. });
  18887. Scene.prototype.getActiveParticles = function () {
  18888. return this._activeParticles.current;
  18889. };
  18890. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  18891. get: function () {
  18892. return this._activeParticles;
  18893. },
  18894. enumerable: true,
  18895. configurable: true
  18896. });
  18897. Scene.prototype.getActiveBones = function () {
  18898. return this._activeBones.current;
  18899. };
  18900. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  18901. get: function () {
  18902. return this._activeBones;
  18903. },
  18904. enumerable: true,
  18905. configurable: true
  18906. });
  18907. // Stats
  18908. Scene.prototype.getInterFramePerfCounter = function () {
  18909. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18910. return 0;
  18911. };
  18912. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  18913. get: function () {
  18914. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18915. return null;
  18916. },
  18917. enumerable: true,
  18918. configurable: true
  18919. });
  18920. Scene.prototype.getLastFrameDuration = function () {
  18921. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  18922. return 0;
  18923. };
  18924. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  18925. get: function () {
  18926. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18927. return null;
  18928. },
  18929. enumerable: true,
  18930. configurable: true
  18931. });
  18932. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  18933. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  18934. return 0;
  18935. };
  18936. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  18937. get: function () {
  18938. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18939. return null;
  18940. },
  18941. enumerable: true,
  18942. configurable: true
  18943. });
  18944. Scene.prototype.getActiveMeshes = function () {
  18945. return this._activeMeshes;
  18946. };
  18947. Scene.prototype.getRenderTargetsDuration = function () {
  18948. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  18949. return 0;
  18950. };
  18951. Scene.prototype.getRenderDuration = function () {
  18952. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  18953. return 0;
  18954. };
  18955. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  18956. get: function () {
  18957. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18958. return null;
  18959. },
  18960. enumerable: true,
  18961. configurable: true
  18962. });
  18963. Scene.prototype.getParticlesDuration = function () {
  18964. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  18965. return 0;
  18966. };
  18967. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  18968. get: function () {
  18969. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18970. return null;
  18971. },
  18972. enumerable: true,
  18973. configurable: true
  18974. });
  18975. Scene.prototype.getSpritesDuration = function () {
  18976. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  18977. return 0;
  18978. };
  18979. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  18980. get: function () {
  18981. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  18982. return null;
  18983. },
  18984. enumerable: true,
  18985. configurable: true
  18986. });
  18987. Scene.prototype.getAnimationRatio = function () {
  18988. return this._animationRatio;
  18989. };
  18990. Scene.prototype.getRenderId = function () {
  18991. return this._renderId;
  18992. };
  18993. Scene.prototype.incrementRenderId = function () {
  18994. this._renderId++;
  18995. };
  18996. Scene.prototype._updatePointerPosition = function (evt) {
  18997. var canvasRect = this._engine.getRenderingCanvasClientRect();
  18998. if (!canvasRect) {
  18999. return;
  19000. }
  19001. this._pointerX = evt.clientX - canvasRect.left;
  19002. this._pointerY = evt.clientY - canvasRect.top;
  19003. this._unTranslatedPointerX = this._pointerX;
  19004. this._unTranslatedPointerY = this._pointerY;
  19005. };
  19006. Scene.prototype._createUbo = function () {
  19007. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  19008. this._sceneUbo.addUniform("viewProjection", 16);
  19009. this._sceneUbo.addUniform("view", 16);
  19010. };
  19011. Scene.prototype._createAlternateUbo = function () {
  19012. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  19013. this._alternateSceneUbo.addUniform("viewProjection", 16);
  19014. this._alternateSceneUbo.addUniform("view", 16);
  19015. };
  19016. // Pointers handling
  19017. /**
  19018. * Use this method to simulate a pointer move on a mesh
  19019. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  19020. */
  19021. Scene.prototype.simulatePointerMove = function (pickResult) {
  19022. var evt = new PointerEvent("pointermove");
  19023. return this._processPointerMove(pickResult, evt);
  19024. };
  19025. Scene.prototype._processPointerMove = function (pickResult, evt) {
  19026. var canvas = this._engine.getRenderingCanvas();
  19027. if (!canvas) {
  19028. return this;
  19029. }
  19030. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  19031. this.setPointerOverSprite(null);
  19032. this.setPointerOverMesh(pickResult.pickedMesh);
  19033. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  19034. if (this._pointerOverMesh.actionManager.hoverCursor) {
  19035. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  19036. }
  19037. else {
  19038. canvas.style.cursor = this.hoverCursor;
  19039. }
  19040. }
  19041. else {
  19042. canvas.style.cursor = this.defaultCursor;
  19043. }
  19044. }
  19045. else {
  19046. this.setPointerOverMesh(null);
  19047. // Sprites
  19048. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  19049. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  19050. this.setPointerOverSprite(pickResult.pickedSprite);
  19051. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  19052. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  19053. }
  19054. else {
  19055. canvas.style.cursor = this.hoverCursor;
  19056. }
  19057. }
  19058. else {
  19059. this.setPointerOverSprite(null);
  19060. // Restore pointer
  19061. canvas.style.cursor = this.defaultCursor;
  19062. }
  19063. }
  19064. if (pickResult) {
  19065. if (this.onPointerMove) {
  19066. this.onPointerMove(evt, pickResult);
  19067. }
  19068. if (this.onPointerObservable.hasObservers()) {
  19069. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  19070. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  19071. this.onPointerObservable.notifyObservers(pi, type);
  19072. }
  19073. }
  19074. return this;
  19075. };
  19076. /**
  19077. * Use this method to simulate a pointer down on a mesh
  19078. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  19079. */
  19080. Scene.prototype.simulatePointerDown = function (pickResult) {
  19081. var evt = new PointerEvent("pointerdown");
  19082. return this._processPointerDown(pickResult, evt);
  19083. };
  19084. Scene.prototype._processPointerDown = function (pickResult, evt) {
  19085. var _this = this;
  19086. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  19087. this._pickedDownMesh = pickResult.pickedMesh;
  19088. var actionManager = pickResult.pickedMesh.actionManager;
  19089. if (actionManager) {
  19090. if (actionManager.hasPickTriggers) {
  19091. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19092. switch (evt.button) {
  19093. case 0:
  19094. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19095. break;
  19096. case 1:
  19097. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19098. break;
  19099. case 2:
  19100. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19101. break;
  19102. }
  19103. }
  19104. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  19105. window.setTimeout(function () {
  19106. 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);
  19107. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  19108. if (_this._totalPointersPressed !== 0 &&
  19109. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  19110. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  19111. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  19112. _this._startingPointerTime = 0;
  19113. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19114. }
  19115. }
  19116. }, Scene.LongPressDelay);
  19117. }
  19118. }
  19119. }
  19120. if (pickResult) {
  19121. if (this.onPointerDown) {
  19122. this.onPointerDown(evt, pickResult);
  19123. }
  19124. if (this.onPointerObservable.hasObservers()) {
  19125. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  19126. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  19127. this.onPointerObservable.notifyObservers(pi, type);
  19128. }
  19129. }
  19130. return this;
  19131. };
  19132. /**
  19133. * Use this method to simulate a pointer up on a mesh
  19134. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  19135. */
  19136. Scene.prototype.simulatePointerUp = function (pickResult) {
  19137. var evt = new PointerEvent("pointerup");
  19138. var clickInfo = new ClickInfo();
  19139. clickInfo.singleClick = true;
  19140. clickInfo.ignore = true;
  19141. return this._processPointerUp(pickResult, evt, clickInfo);
  19142. };
  19143. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  19144. if (pickResult && pickResult && pickResult.pickedMesh) {
  19145. this._pickedUpMesh = pickResult.pickedMesh;
  19146. if (this._pickedDownMesh === this._pickedUpMesh) {
  19147. if (this.onPointerPick) {
  19148. this.onPointerPick(evt, pickResult);
  19149. }
  19150. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  19151. var type = BABYLON.PointerEventTypes.POINTERPICK;
  19152. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  19153. this.onPointerObservable.notifyObservers(pi, type);
  19154. }
  19155. }
  19156. if (pickResult.pickedMesh.actionManager) {
  19157. if (clickInfo.ignore) {
  19158. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19159. }
  19160. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  19161. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19162. }
  19163. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  19164. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19165. }
  19166. }
  19167. }
  19168. if (this._pickedDownMesh &&
  19169. this._pickedDownMesh.actionManager &&
  19170. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  19171. this._pickedDownMesh !== this._pickedUpMesh) {
  19172. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  19173. }
  19174. if (this.onPointerUp) {
  19175. this.onPointerUp(evt, pickResult);
  19176. }
  19177. if (this.onPointerObservable.hasObservers()) {
  19178. if (!clickInfo.ignore) {
  19179. if (!clickInfo.hasSwiped) {
  19180. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  19181. var type = BABYLON.PointerEventTypes.POINTERTAP;
  19182. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  19183. this.onPointerObservable.notifyObservers(pi, type);
  19184. }
  19185. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  19186. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  19187. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  19188. this.onPointerObservable.notifyObservers(pi, type);
  19189. }
  19190. }
  19191. }
  19192. else {
  19193. var type = BABYLON.PointerEventTypes.POINTERUP;
  19194. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  19195. this.onPointerObservable.notifyObservers(pi, type);
  19196. }
  19197. }
  19198. return this;
  19199. };
  19200. /**
  19201. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  19202. * @param attachUp defines if you want to attach events to pointerup
  19203. * @param attachDown defines if you want to attach events to pointerdown
  19204. * @param attachMove defines if you want to attach events to pointermove
  19205. */
  19206. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  19207. var _this = this;
  19208. if (attachUp === void 0) { attachUp = true; }
  19209. if (attachDown === void 0) { attachDown = true; }
  19210. if (attachMove === void 0) { attachMove = true; }
  19211. this._initActionManager = function (act, clickInfo) {
  19212. if (!_this._meshPickProceed) {
  19213. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  19214. _this._currentPickResult = pickResult;
  19215. if (pickResult) {
  19216. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  19217. }
  19218. _this._meshPickProceed = true;
  19219. }
  19220. return act;
  19221. };
  19222. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  19223. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  19224. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  19225. btn !== _this._previousButtonPressed) {
  19226. _this._doubleClickOccured = false;
  19227. clickInfo.singleClick = true;
  19228. clickInfo.ignore = false;
  19229. cb(clickInfo, _this._currentPickResult);
  19230. }
  19231. };
  19232. this._initClickEvent = function (obs1, obs2, evt, cb) {
  19233. var clickInfo = new ClickInfo();
  19234. _this._currentPickResult = null;
  19235. var act = null;
  19236. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  19237. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  19238. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  19239. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  19240. act = _this._initActionManager(act, clickInfo);
  19241. if (act)
  19242. checkPicking = act.hasPickTriggers;
  19243. }
  19244. if (checkPicking) {
  19245. var btn = evt.button;
  19246. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  19247. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  19248. if (!clickInfo.hasSwiped) {
  19249. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  19250. if (!checkSingleClickImmediately) {
  19251. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  19252. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  19253. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  19254. act = _this._initActionManager(act, clickInfo);
  19255. if (act)
  19256. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  19257. }
  19258. }
  19259. if (checkSingleClickImmediately) {
  19260. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  19261. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  19262. btn !== _this._previousButtonPressed) {
  19263. clickInfo.singleClick = true;
  19264. cb(clickInfo, _this._currentPickResult);
  19265. }
  19266. }
  19267. else {
  19268. // wait that no double click has been raised during the double click delay
  19269. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  19270. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  19271. }
  19272. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  19273. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  19274. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  19275. act = _this._initActionManager(act, clickInfo);
  19276. if (act)
  19277. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  19278. }
  19279. if (checkDoubleClick) {
  19280. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  19281. if (btn === _this._previousButtonPressed &&
  19282. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  19283. !_this._doubleClickOccured) {
  19284. // pointer has not moved for 2 clicks, it's a double click
  19285. if (!clickInfo.hasSwiped &&
  19286. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  19287. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  19288. _this._previousStartingPointerTime = 0;
  19289. _this._doubleClickOccured = true;
  19290. clickInfo.doubleClick = true;
  19291. clickInfo.ignore = false;
  19292. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  19293. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  19294. }
  19295. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  19296. cb(clickInfo, _this._currentPickResult);
  19297. }
  19298. else {
  19299. _this._doubleClickOccured = false;
  19300. _this._previousStartingPointerTime = _this._startingPointerTime;
  19301. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  19302. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  19303. _this._previousButtonPressed = btn;
  19304. if (Scene.ExclusiveDoubleClickMode) {
  19305. if (_this._previousDelayedSimpleClickTimeout) {
  19306. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  19307. }
  19308. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  19309. cb(clickInfo, _this._previousPickResult);
  19310. }
  19311. else {
  19312. cb(clickInfo, _this._currentPickResult);
  19313. }
  19314. }
  19315. }
  19316. else {
  19317. _this._doubleClickOccured = false;
  19318. _this._previousStartingPointerTime = _this._startingPointerTime;
  19319. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  19320. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  19321. _this._previousButtonPressed = btn;
  19322. }
  19323. }
  19324. }
  19325. }
  19326. clickInfo.ignore = true;
  19327. cb(clickInfo, _this._currentPickResult);
  19328. };
  19329. this._spritePredicate = function (sprite) {
  19330. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  19331. };
  19332. this._onPointerMove = function (evt) {
  19333. _this._updatePointerPosition(evt);
  19334. // PreObservable support
  19335. if (_this.onPrePointerObservable.hasObservers()) {
  19336. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  19337. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19338. _this.onPrePointerObservable.notifyObservers(pi, type);
  19339. if (pi.skipOnPointerObservable) {
  19340. return;
  19341. }
  19342. }
  19343. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19344. return;
  19345. }
  19346. if (!_this.pointerMovePredicate) {
  19347. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  19348. }
  19349. // Meshes
  19350. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  19351. _this._processPointerMove(pickResult, evt);
  19352. };
  19353. this._onPointerDown = function (evt) {
  19354. _this._totalPointersPressed++;
  19355. _this._pickedDownMesh = null;
  19356. _this._meshPickProceed = false;
  19357. _this._updatePointerPosition(evt);
  19358. if (_this.preventDefaultOnPointerDown && canvas) {
  19359. evt.preventDefault();
  19360. canvas.focus();
  19361. }
  19362. // PreObservable support
  19363. if (_this.onPrePointerObservable.hasObservers()) {
  19364. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  19365. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19366. _this.onPrePointerObservable.notifyObservers(pi, type);
  19367. if (pi.skipOnPointerObservable) {
  19368. return;
  19369. }
  19370. }
  19371. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19372. return;
  19373. }
  19374. _this._startingPointerPosition.x = _this._pointerX;
  19375. _this._startingPointerPosition.y = _this._pointerY;
  19376. _this._startingPointerTime = new Date().getTime();
  19377. if (!_this.pointerDownPredicate) {
  19378. _this.pointerDownPredicate = function (mesh) {
  19379. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  19380. };
  19381. }
  19382. // Meshes
  19383. _this._pickedDownMesh = null;
  19384. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  19385. _this._processPointerDown(pickResult, evt);
  19386. // Sprites
  19387. _this._pickedDownSprite = null;
  19388. if (_this.spriteManagers.length > 0) {
  19389. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  19390. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  19391. if (pickResult.pickedSprite.actionManager) {
  19392. _this._pickedDownSprite = pickResult.pickedSprite;
  19393. switch (evt.button) {
  19394. case 0:
  19395. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19396. break;
  19397. case 1:
  19398. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19399. break;
  19400. case 2:
  19401. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19402. break;
  19403. }
  19404. if (pickResult.pickedSprite.actionManager) {
  19405. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19406. }
  19407. }
  19408. }
  19409. }
  19410. };
  19411. this._onPointerUp = function (evt) {
  19412. if (_this._totalPointersPressed === 0) {
  19413. return; // So we need to test it the pointer down was pressed before.
  19414. }
  19415. _this._totalPointersPressed--;
  19416. _this._pickedUpMesh = null;
  19417. _this._meshPickProceed = false;
  19418. _this._updatePointerPosition(evt);
  19419. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  19420. // PreObservable support
  19421. if (_this.onPrePointerObservable.hasObservers()) {
  19422. if (!clickInfo.ignore) {
  19423. if (!clickInfo.hasSwiped) {
  19424. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  19425. var type = BABYLON.PointerEventTypes.POINTERTAP;
  19426. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19427. _this.onPrePointerObservable.notifyObservers(pi, type);
  19428. if (pi.skipOnPointerObservable) {
  19429. return;
  19430. }
  19431. }
  19432. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  19433. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  19434. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19435. _this.onPrePointerObservable.notifyObservers(pi, type);
  19436. if (pi.skipOnPointerObservable) {
  19437. return;
  19438. }
  19439. }
  19440. }
  19441. }
  19442. else {
  19443. var type = BABYLON.PointerEventTypes.POINTERUP;
  19444. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19445. _this.onPrePointerObservable.notifyObservers(pi, type);
  19446. if (pi.skipOnPointerObservable) {
  19447. return;
  19448. }
  19449. }
  19450. }
  19451. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19452. return;
  19453. }
  19454. if (!_this.pointerUpPredicate) {
  19455. _this.pointerUpPredicate = function (mesh) {
  19456. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  19457. };
  19458. }
  19459. // Meshes
  19460. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  19461. _this._initActionManager(null, clickInfo);
  19462. }
  19463. if (!pickResult) {
  19464. pickResult = _this._currentPickResult;
  19465. }
  19466. _this._processPointerUp(pickResult, evt, clickInfo);
  19467. // Sprites
  19468. if (_this.spriteManagers.length > 0) {
  19469. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  19470. if (spritePickResult) {
  19471. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  19472. if (spritePickResult.pickedSprite.actionManager) {
  19473. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  19474. if (spritePickResult.pickedSprite.actionManager) {
  19475. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  19476. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  19477. }
  19478. }
  19479. }
  19480. }
  19481. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  19482. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  19483. }
  19484. }
  19485. }
  19486. _this._previousPickResult = _this._currentPickResult;
  19487. });
  19488. };
  19489. this._onKeyDown = function (evt) {
  19490. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  19491. if (_this.onPreKeyboardObservable.hasObservers()) {
  19492. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  19493. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  19494. if (pi.skipOnPointerObservable) {
  19495. return;
  19496. }
  19497. }
  19498. if (_this.onKeyboardObservable.hasObservers()) {
  19499. var pi = new BABYLON.KeyboardInfo(type, evt);
  19500. _this.onKeyboardObservable.notifyObservers(pi, type);
  19501. }
  19502. if (_this.actionManager) {
  19503. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  19504. }
  19505. };
  19506. this._onKeyUp = function (evt) {
  19507. var type = BABYLON.KeyboardEventTypes.KEYUP;
  19508. if (_this.onPreKeyboardObservable.hasObservers()) {
  19509. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  19510. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  19511. if (pi.skipOnPointerObservable) {
  19512. return;
  19513. }
  19514. }
  19515. if (_this.onKeyboardObservable.hasObservers()) {
  19516. var pi = new BABYLON.KeyboardInfo(type, evt);
  19517. _this.onKeyboardObservable.notifyObservers(pi, type);
  19518. }
  19519. if (_this.actionManager) {
  19520. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  19521. }
  19522. };
  19523. var engine = this.getEngine();
  19524. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  19525. if (!canvas) {
  19526. return;
  19527. }
  19528. canvas.addEventListener("keydown", _this._onKeyDown, false);
  19529. canvas.addEventListener("keyup", _this._onKeyUp, false);
  19530. });
  19531. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  19532. if (!canvas) {
  19533. return;
  19534. }
  19535. canvas.removeEventListener("keydown", _this._onKeyDown);
  19536. canvas.removeEventListener("keyup", _this._onKeyUp);
  19537. });
  19538. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  19539. var canvas = this._engine.getRenderingCanvas();
  19540. if (!canvas) {
  19541. return;
  19542. }
  19543. if (attachMove) {
  19544. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  19545. // Wheel
  19546. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  19547. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  19548. }
  19549. if (attachDown) {
  19550. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  19551. }
  19552. if (attachUp) {
  19553. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  19554. }
  19555. canvas.tabIndex = 1;
  19556. };
  19557. Scene.prototype.detachControl = function () {
  19558. var engine = this.getEngine();
  19559. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  19560. var canvas = engine.getRenderingCanvas();
  19561. if (!canvas) {
  19562. return;
  19563. }
  19564. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  19565. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  19566. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  19567. if (this._onCanvasBlurObserver) {
  19568. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  19569. }
  19570. if (this._onCanvasFocusObserver) {
  19571. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  19572. }
  19573. // Wheel
  19574. canvas.removeEventListener('mousewheel', this._onPointerMove);
  19575. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  19576. // Keyboard
  19577. canvas.removeEventListener("keydown", this._onKeyDown);
  19578. canvas.removeEventListener("keyup", this._onKeyUp);
  19579. // Observables
  19580. this.onKeyboardObservable.clear();
  19581. this.onPreKeyboardObservable.clear();
  19582. this.onPointerObservable.clear();
  19583. this.onPrePointerObservable.clear();
  19584. };
  19585. // Ready
  19586. Scene.prototype.isReady = function () {
  19587. if (this._isDisposed) {
  19588. return false;
  19589. }
  19590. if (this._pendingData.length > 0) {
  19591. return false;
  19592. }
  19593. var index;
  19594. // Geometries
  19595. for (index = 0; index < this._geometries.length; index++) {
  19596. var geometry = this._geometries[index];
  19597. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19598. return false;
  19599. }
  19600. }
  19601. // Meshes
  19602. for (index = 0; index < this.meshes.length; index++) {
  19603. var mesh = this.meshes[index];
  19604. if (!mesh.isEnabled()) {
  19605. continue;
  19606. }
  19607. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  19608. continue;
  19609. }
  19610. if (!mesh.isReady()) {
  19611. return false;
  19612. }
  19613. var mat = mesh.material;
  19614. if (mat) {
  19615. if (!mat.isReady(mesh)) {
  19616. return false;
  19617. }
  19618. }
  19619. }
  19620. return true;
  19621. };
  19622. Scene.prototype.resetCachedMaterial = function () {
  19623. this._cachedMaterial = null;
  19624. this._cachedEffect = null;
  19625. this._cachedVisibility = null;
  19626. };
  19627. Scene.prototype.registerBeforeRender = function (func) {
  19628. this.onBeforeRenderObservable.add(func);
  19629. };
  19630. Scene.prototype.unregisterBeforeRender = function (func) {
  19631. this.onBeforeRenderObservable.removeCallback(func);
  19632. };
  19633. Scene.prototype.registerAfterRender = function (func) {
  19634. this.onAfterRenderObservable.add(func);
  19635. };
  19636. Scene.prototype.unregisterAfterRender = function (func) {
  19637. this.onAfterRenderObservable.removeCallback(func);
  19638. };
  19639. Scene.prototype._addPendingData = function (data) {
  19640. this._pendingData.push(data);
  19641. };
  19642. Scene.prototype._removePendingData = function (data) {
  19643. var wasLoading = this.isLoading;
  19644. var index = this._pendingData.indexOf(data);
  19645. if (index !== -1) {
  19646. this._pendingData.splice(index, 1);
  19647. }
  19648. if (wasLoading && !this.isLoading) {
  19649. this.onDataLoadedObservable.notifyObservers(this);
  19650. }
  19651. };
  19652. Scene.prototype.getWaitingItemsCount = function () {
  19653. return this._pendingData.length;
  19654. };
  19655. Object.defineProperty(Scene.prototype, "isLoading", {
  19656. get: function () {
  19657. return this._pendingData.length > 0;
  19658. },
  19659. enumerable: true,
  19660. configurable: true
  19661. });
  19662. /**
  19663. * Registers a function to be executed when the scene is ready.
  19664. * @param {Function} func - the function to be executed.
  19665. */
  19666. Scene.prototype.executeWhenReady = function (func) {
  19667. var _this = this;
  19668. this.onReadyObservable.add(func);
  19669. if (this._executeWhenReadyTimeoutId !== -1) {
  19670. return;
  19671. }
  19672. this._executeWhenReadyTimeoutId = setTimeout(function () {
  19673. _this._checkIsReady();
  19674. }, 150);
  19675. };
  19676. Scene.prototype._checkIsReady = function () {
  19677. var _this = this;
  19678. if (this.isReady()) {
  19679. this.onReadyObservable.notifyObservers(this);
  19680. this.onReadyObservable.clear();
  19681. this._executeWhenReadyTimeoutId = -1;
  19682. return;
  19683. }
  19684. this._executeWhenReadyTimeoutId = setTimeout(function () {
  19685. _this._checkIsReady();
  19686. }, 150);
  19687. };
  19688. // Animations
  19689. /**
  19690. * Will start the animation sequence of a given target
  19691. * @param target - the target
  19692. * @param {number} from - from which frame should animation start
  19693. * @param {number} to - till which frame should animation run.
  19694. * @param {boolean} [loop] - should the animation loop
  19695. * @param {number} [speedRatio] - the speed in which to run the animation
  19696. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  19697. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  19698. * Returns {BABYLON.Animatable} the animatable object created for this animation
  19699. * See BABYLON.Animatable
  19700. */
  19701. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  19702. if (speedRatio === void 0) { speedRatio = 1.0; }
  19703. if (from > to && speedRatio > 0) {
  19704. speedRatio *= -1;
  19705. }
  19706. this.stopAnimation(target);
  19707. if (!animatable) {
  19708. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  19709. }
  19710. // Local animations
  19711. if (target.animations) {
  19712. animatable.appendAnimations(target, target.animations);
  19713. }
  19714. // Children animations
  19715. if (target.getAnimatables) {
  19716. var animatables = target.getAnimatables();
  19717. for (var index = 0; index < animatables.length; index++) {
  19718. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  19719. }
  19720. }
  19721. animatable.reset();
  19722. return animatable;
  19723. };
  19724. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  19725. if (speedRatio === undefined) {
  19726. speedRatio = 1.0;
  19727. }
  19728. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  19729. return animatable;
  19730. };
  19731. Scene.prototype.getAnimatableByTarget = function (target) {
  19732. for (var index = 0; index < this._activeAnimatables.length; index++) {
  19733. if (this._activeAnimatables[index].target === target) {
  19734. return this._activeAnimatables[index];
  19735. }
  19736. }
  19737. return null;
  19738. };
  19739. Object.defineProperty(Scene.prototype, "Animatables", {
  19740. get: function () {
  19741. return this._activeAnimatables;
  19742. },
  19743. enumerable: true,
  19744. configurable: true
  19745. });
  19746. /**
  19747. * Will stop the animation of the given target
  19748. * @param target - the target
  19749. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  19750. * @see beginAnimation
  19751. */
  19752. Scene.prototype.stopAnimation = function (target, animationName) {
  19753. var animatable = this.getAnimatableByTarget(target);
  19754. if (animatable) {
  19755. animatable.stop(animationName);
  19756. }
  19757. };
  19758. /**
  19759. * Stops and removes all animations that have been applied to the scene
  19760. */
  19761. Scene.prototype.stopAllAnimations = function () {
  19762. if (this._activeAnimatables) {
  19763. for (var i = 0; i < this._activeAnimatables.length; i++) {
  19764. this._activeAnimatables[i].stop();
  19765. }
  19766. this._activeAnimatables = [];
  19767. }
  19768. };
  19769. Scene.prototype._animate = function () {
  19770. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  19771. return;
  19772. }
  19773. // Getting time
  19774. var now = BABYLON.Tools.Now;
  19775. if (!this._animationTimeLast) {
  19776. if (this._pendingData.length > 0) {
  19777. return;
  19778. }
  19779. this._animationTimeLast = now;
  19780. }
  19781. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  19782. this._animationTime += deltaTime;
  19783. this._animationTimeLast = now;
  19784. for (var index = 0; index < this._activeAnimatables.length; index++) {
  19785. this._activeAnimatables[index]._animate(this._animationTime);
  19786. }
  19787. };
  19788. // Matrix
  19789. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  19790. this._useAlternateCameraConfiguration = active;
  19791. };
  19792. Scene.prototype.getViewMatrix = function () {
  19793. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  19794. };
  19795. Scene.prototype.getProjectionMatrix = function () {
  19796. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  19797. };
  19798. Scene.prototype.getTransformMatrix = function () {
  19799. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  19800. };
  19801. Scene.prototype.setTransformMatrix = function (view, projection) {
  19802. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  19803. return;
  19804. }
  19805. this._viewUpdateFlag = view.updateFlag;
  19806. this._projectionUpdateFlag = projection.updateFlag;
  19807. this._viewMatrix = view;
  19808. this._projectionMatrix = projection;
  19809. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  19810. // Update frustum
  19811. if (!this._frustumPlanes) {
  19812. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  19813. }
  19814. else {
  19815. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  19816. }
  19817. if (this.activeCamera && this.activeCamera._alternateCamera) {
  19818. var otherCamera = this.activeCamera._alternateCamera;
  19819. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  19820. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  19821. }
  19822. if (this._sceneUbo.useUbo) {
  19823. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  19824. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  19825. this._sceneUbo.update();
  19826. }
  19827. };
  19828. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  19829. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  19830. return;
  19831. }
  19832. this._alternateViewUpdateFlag = view.updateFlag;
  19833. this._alternateProjectionUpdateFlag = projection.updateFlag;
  19834. this._alternateViewMatrix = view;
  19835. this._alternateProjectionMatrix = projection;
  19836. if (!this._alternateTransformMatrix) {
  19837. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  19838. }
  19839. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  19840. if (!this._alternateSceneUbo) {
  19841. this._createAlternateUbo();
  19842. }
  19843. if (this._alternateSceneUbo.useUbo) {
  19844. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  19845. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  19846. this._alternateSceneUbo.update();
  19847. }
  19848. };
  19849. Scene.prototype.getSceneUniformBuffer = function () {
  19850. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  19851. };
  19852. // Methods
  19853. Scene.prototype.getUniqueId = function () {
  19854. var result = Scene._uniqueIdCounter;
  19855. Scene._uniqueIdCounter++;
  19856. return result;
  19857. };
  19858. Scene.prototype.addMesh = function (newMesh) {
  19859. this.meshes.push(newMesh);
  19860. //notify the collision coordinator
  19861. if (this.collisionCoordinator) {
  19862. this.collisionCoordinator.onMeshAdded(newMesh);
  19863. }
  19864. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  19865. };
  19866. Scene.prototype.removeMesh = function (toRemove) {
  19867. var index = this.meshes.indexOf(toRemove);
  19868. if (index !== -1) {
  19869. // Remove from the scene if mesh found
  19870. this.meshes.splice(index, 1);
  19871. }
  19872. this.onMeshRemovedObservable.notifyObservers(toRemove);
  19873. return index;
  19874. };
  19875. Scene.prototype.addTransformNode = function (newTransformNode) {
  19876. this.transformNodes.push(newTransformNode);
  19877. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  19878. };
  19879. Scene.prototype.removeTransformNode = function (toRemove) {
  19880. var index = this.transformNodes.indexOf(toRemove);
  19881. if (index !== -1) {
  19882. // Remove from the scene if found
  19883. this.transformNodes.splice(index, 1);
  19884. }
  19885. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  19886. return index;
  19887. };
  19888. Scene.prototype.removeSkeleton = function (toRemove) {
  19889. var index = this.skeletons.indexOf(toRemove);
  19890. if (index !== -1) {
  19891. // Remove from the scene if found
  19892. this.skeletons.splice(index, 1);
  19893. }
  19894. return index;
  19895. };
  19896. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  19897. var index = this.morphTargetManagers.indexOf(toRemove);
  19898. if (index !== -1) {
  19899. // Remove from the scene if found
  19900. this.morphTargetManagers.splice(index, 1);
  19901. }
  19902. return index;
  19903. };
  19904. Scene.prototype.removeLight = function (toRemove) {
  19905. var index = this.lights.indexOf(toRemove);
  19906. if (index !== -1) {
  19907. // Remove from the scene if mesh found
  19908. this.lights.splice(index, 1);
  19909. this.sortLightsByPriority();
  19910. }
  19911. this.onLightRemovedObservable.notifyObservers(toRemove);
  19912. return index;
  19913. };
  19914. Scene.prototype.removeCamera = function (toRemove) {
  19915. var index = this.cameras.indexOf(toRemove);
  19916. if (index !== -1) {
  19917. // Remove from the scene if mesh found
  19918. this.cameras.splice(index, 1);
  19919. }
  19920. // Remove from activeCameras
  19921. var index2 = this.activeCameras.indexOf(toRemove);
  19922. if (index2 !== -1) {
  19923. // Remove from the scene if mesh found
  19924. this.activeCameras.splice(index2, 1);
  19925. }
  19926. // Reset the activeCamera
  19927. if (this.activeCamera === toRemove) {
  19928. if (this.cameras.length > 0) {
  19929. this.activeCamera = this.cameras[0];
  19930. }
  19931. else {
  19932. this.activeCamera = null;
  19933. }
  19934. }
  19935. this.onCameraRemovedObservable.notifyObservers(toRemove);
  19936. return index;
  19937. };
  19938. Scene.prototype.addLight = function (newLight) {
  19939. this.lights.push(newLight);
  19940. this.sortLightsByPriority();
  19941. this.onNewLightAddedObservable.notifyObservers(newLight);
  19942. };
  19943. Scene.prototype.sortLightsByPriority = function () {
  19944. if (this.requireLightSorting) {
  19945. this.lights.sort(BABYLON.Light.compareLightsPriority);
  19946. }
  19947. };
  19948. Scene.prototype.addCamera = function (newCamera) {
  19949. this.cameras.push(newCamera);
  19950. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  19951. };
  19952. /**
  19953. * Switch active camera
  19954. * @param {Camera} newCamera - new active camera
  19955. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  19956. */
  19957. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  19958. if (attachControl === void 0) { attachControl = true; }
  19959. var canvas = this._engine.getRenderingCanvas();
  19960. if (!canvas) {
  19961. return;
  19962. }
  19963. if (this.activeCamera) {
  19964. this.activeCamera.detachControl(canvas);
  19965. }
  19966. this.activeCamera = newCamera;
  19967. if (attachControl) {
  19968. newCamera.attachControl(canvas);
  19969. }
  19970. };
  19971. /**
  19972. * sets the active camera of the scene using its ID
  19973. * @param {string} id - the camera's ID
  19974. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19975. * @see activeCamera
  19976. */
  19977. Scene.prototype.setActiveCameraByID = function (id) {
  19978. var camera = this.getCameraByID(id);
  19979. if (camera) {
  19980. this.activeCamera = camera;
  19981. return camera;
  19982. }
  19983. return null;
  19984. };
  19985. /**
  19986. * sets the active camera of the scene using its name
  19987. * @param {string} name - the camera's name
  19988. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19989. * @see activeCamera
  19990. */
  19991. Scene.prototype.setActiveCameraByName = function (name) {
  19992. var camera = this.getCameraByName(name);
  19993. if (camera) {
  19994. this.activeCamera = camera;
  19995. return camera;
  19996. }
  19997. return null;
  19998. };
  19999. /**
  20000. * get an animation group using its name
  20001. * @param {string} the material's name
  20002. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  20003. */
  20004. Scene.prototype.getAnimationGroupByName = function (name) {
  20005. for (var index = 0; index < this.animationGroups.length; index++) {
  20006. if (this.animationGroups[index].name === name) {
  20007. return this.animationGroups[index];
  20008. }
  20009. }
  20010. return null;
  20011. };
  20012. /**
  20013. * get a material using its id
  20014. * @param {string} the material's ID
  20015. * @return {BABYLON.Material|null} the material or null if none found.
  20016. */
  20017. Scene.prototype.getMaterialByID = function (id) {
  20018. for (var index = 0; index < this.materials.length; index++) {
  20019. if (this.materials[index].id === id) {
  20020. return this.materials[index];
  20021. }
  20022. }
  20023. return null;
  20024. };
  20025. /**
  20026. * get a material using its name
  20027. * @param {string} the material's name
  20028. * @return {BABYLON.Material|null} the material or null if none found.
  20029. */
  20030. Scene.prototype.getMaterialByName = function (name) {
  20031. for (var index = 0; index < this.materials.length; index++) {
  20032. if (this.materials[index].name === name) {
  20033. return this.materials[index];
  20034. }
  20035. }
  20036. return null;
  20037. };
  20038. Scene.prototype.getLensFlareSystemByName = function (name) {
  20039. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  20040. if (this.lensFlareSystems[index].name === name) {
  20041. return this.lensFlareSystems[index];
  20042. }
  20043. }
  20044. return null;
  20045. };
  20046. Scene.prototype.getLensFlareSystemByID = function (id) {
  20047. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  20048. if (this.lensFlareSystems[index].id === id) {
  20049. return this.lensFlareSystems[index];
  20050. }
  20051. }
  20052. return null;
  20053. };
  20054. Scene.prototype.getCameraByID = function (id) {
  20055. for (var index = 0; index < this.cameras.length; index++) {
  20056. if (this.cameras[index].id === id) {
  20057. return this.cameras[index];
  20058. }
  20059. }
  20060. return null;
  20061. };
  20062. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  20063. for (var index = 0; index < this.cameras.length; index++) {
  20064. if (this.cameras[index].uniqueId === uniqueId) {
  20065. return this.cameras[index];
  20066. }
  20067. }
  20068. return null;
  20069. };
  20070. /**
  20071. * get a camera using its name
  20072. * @param {string} the camera's name
  20073. * @return {BABYLON.Camera|null} the camera or null if none found.
  20074. */
  20075. Scene.prototype.getCameraByName = function (name) {
  20076. for (var index = 0; index < this.cameras.length; index++) {
  20077. if (this.cameras[index].name === name) {
  20078. return this.cameras[index];
  20079. }
  20080. }
  20081. return null;
  20082. };
  20083. /**
  20084. * get a bone using its id
  20085. * @param {string} the bone's id
  20086. * @return {BABYLON.Bone|null} the bone or null if not found
  20087. */
  20088. Scene.prototype.getBoneByID = function (id) {
  20089. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  20090. var skeleton = this.skeletons[skeletonIndex];
  20091. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  20092. if (skeleton.bones[boneIndex].id === id) {
  20093. return skeleton.bones[boneIndex];
  20094. }
  20095. }
  20096. }
  20097. return null;
  20098. };
  20099. /**
  20100. * get a bone using its id
  20101. * @param {string} the bone's name
  20102. * @return {BABYLON.Bone|null} the bone or null if not found
  20103. */
  20104. Scene.prototype.getBoneByName = function (name) {
  20105. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  20106. var skeleton = this.skeletons[skeletonIndex];
  20107. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  20108. if (skeleton.bones[boneIndex].name === name) {
  20109. return skeleton.bones[boneIndex];
  20110. }
  20111. }
  20112. }
  20113. return null;
  20114. };
  20115. /**
  20116. * get a light node using its name
  20117. * @param {string} the light's name
  20118. * @return {BABYLON.Light|null} the light or null if none found.
  20119. */
  20120. Scene.prototype.getLightByName = function (name) {
  20121. for (var index = 0; index < this.lights.length; index++) {
  20122. if (this.lights[index].name === name) {
  20123. return this.lights[index];
  20124. }
  20125. }
  20126. return null;
  20127. };
  20128. /**
  20129. * get a light node using its ID
  20130. * @param {string} the light's id
  20131. * @return {BABYLON.Light|null} the light or null if none found.
  20132. */
  20133. Scene.prototype.getLightByID = function (id) {
  20134. for (var index = 0; index < this.lights.length; index++) {
  20135. if (this.lights[index].id === id) {
  20136. return this.lights[index];
  20137. }
  20138. }
  20139. return null;
  20140. };
  20141. /**
  20142. * get a light node using its scene-generated unique ID
  20143. * @param {number} the light's unique id
  20144. * @return {BABYLON.Light|null} the light or null if none found.
  20145. */
  20146. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  20147. for (var index = 0; index < this.lights.length; index++) {
  20148. if (this.lights[index].uniqueId === uniqueId) {
  20149. return this.lights[index];
  20150. }
  20151. }
  20152. return null;
  20153. };
  20154. /**
  20155. * get a particle system by id
  20156. * @param id {number} the particle system id
  20157. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  20158. */
  20159. Scene.prototype.getParticleSystemByID = function (id) {
  20160. for (var index = 0; index < this.particleSystems.length; index++) {
  20161. if (this.particleSystems[index].id === id) {
  20162. return this.particleSystems[index];
  20163. }
  20164. }
  20165. return null;
  20166. };
  20167. /**
  20168. * get a geometry using its ID
  20169. * @param {string} the geometry's id
  20170. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  20171. */
  20172. Scene.prototype.getGeometryByID = function (id) {
  20173. for (var index = 0; index < this._geometries.length; index++) {
  20174. if (this._geometries[index].id === id) {
  20175. return this._geometries[index];
  20176. }
  20177. }
  20178. return null;
  20179. };
  20180. /**
  20181. * add a new geometry to this scene.
  20182. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  20183. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  20184. * @return {boolean} was the geometry added or not
  20185. */
  20186. Scene.prototype.pushGeometry = function (geometry, force) {
  20187. if (!force && this.getGeometryByID(geometry.id)) {
  20188. return false;
  20189. }
  20190. this._geometries.push(geometry);
  20191. //notify the collision coordinator
  20192. if (this.collisionCoordinator) {
  20193. this.collisionCoordinator.onGeometryAdded(geometry);
  20194. }
  20195. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  20196. return true;
  20197. };
  20198. /**
  20199. * Removes an existing geometry
  20200. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  20201. * @return {boolean} was the geometry removed or not
  20202. */
  20203. Scene.prototype.removeGeometry = function (geometry) {
  20204. var index = this._geometries.indexOf(geometry);
  20205. if (index > -1) {
  20206. this._geometries.splice(index, 1);
  20207. //notify the collision coordinator
  20208. if (this.collisionCoordinator) {
  20209. this.collisionCoordinator.onGeometryDeleted(geometry);
  20210. }
  20211. this.onGeometryRemovedObservable.notifyObservers(geometry);
  20212. return true;
  20213. }
  20214. return false;
  20215. };
  20216. Scene.prototype.getGeometries = function () {
  20217. return this._geometries;
  20218. };
  20219. /**
  20220. * Get the first added mesh found of a given ID
  20221. * @param {string} id - the id to search for
  20222. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20223. */
  20224. Scene.prototype.getMeshByID = function (id) {
  20225. for (var index = 0; index < this.meshes.length; index++) {
  20226. if (this.meshes[index].id === id) {
  20227. return this.meshes[index];
  20228. }
  20229. }
  20230. return null;
  20231. };
  20232. Scene.prototype.getMeshesByID = function (id) {
  20233. return this.meshes.filter(function (m) {
  20234. return m.id === id;
  20235. });
  20236. };
  20237. /**
  20238. * Get the first added transform node found of a given ID
  20239. * @param {string} id - the id to search for
  20240. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  20241. */
  20242. Scene.prototype.getTransformNodeByID = function (id) {
  20243. for (var index = 0; index < this.transformNodes.length; index++) {
  20244. if (this.transformNodes[index].id === id) {
  20245. return this.transformNodes[index];
  20246. }
  20247. }
  20248. return null;
  20249. };
  20250. Scene.prototype.getTransformNodesByID = function (id) {
  20251. return this.transformNodes.filter(function (m) {
  20252. return m.id === id;
  20253. });
  20254. };
  20255. /**
  20256. * Get a mesh with its auto-generated unique id
  20257. * @param {number} uniqueId - the unique id to search for
  20258. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20259. */
  20260. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  20261. for (var index = 0; index < this.meshes.length; index++) {
  20262. if (this.meshes[index].uniqueId === uniqueId) {
  20263. return this.meshes[index];
  20264. }
  20265. }
  20266. return null;
  20267. };
  20268. /**
  20269. * Get a the last added mesh found of a given ID
  20270. * @param {string} id - the id to search for
  20271. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20272. */
  20273. Scene.prototype.getLastMeshByID = function (id) {
  20274. for (var index = this.meshes.length - 1; index >= 0; index--) {
  20275. if (this.meshes[index].id === id) {
  20276. return this.meshes[index];
  20277. }
  20278. }
  20279. return null;
  20280. };
  20281. /**
  20282. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  20283. * @param {string} id - the id to search for
  20284. * @return {BABYLON.Node|null} the node found or null if not found at all.
  20285. */
  20286. Scene.prototype.getLastEntryByID = function (id) {
  20287. var index;
  20288. for (index = this.meshes.length - 1; index >= 0; index--) {
  20289. if (this.meshes[index].id === id) {
  20290. return this.meshes[index];
  20291. }
  20292. }
  20293. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  20294. if (this.transformNodes[index].id === id) {
  20295. return this.transformNodes[index];
  20296. }
  20297. }
  20298. for (index = this.cameras.length - 1; index >= 0; index--) {
  20299. if (this.cameras[index].id === id) {
  20300. return this.cameras[index];
  20301. }
  20302. }
  20303. for (index = this.lights.length - 1; index >= 0; index--) {
  20304. if (this.lights[index].id === id) {
  20305. return this.lights[index];
  20306. }
  20307. }
  20308. return null;
  20309. };
  20310. Scene.prototype.getNodeByID = function (id) {
  20311. var mesh = this.getMeshByID(id);
  20312. if (mesh) {
  20313. return mesh;
  20314. }
  20315. var light = this.getLightByID(id);
  20316. if (light) {
  20317. return light;
  20318. }
  20319. var camera = this.getCameraByID(id);
  20320. if (camera) {
  20321. return camera;
  20322. }
  20323. var bone = this.getBoneByID(id);
  20324. return bone;
  20325. };
  20326. Scene.prototype.getNodeByName = function (name) {
  20327. var mesh = this.getMeshByName(name);
  20328. if (mesh) {
  20329. return mesh;
  20330. }
  20331. var light = this.getLightByName(name);
  20332. if (light) {
  20333. return light;
  20334. }
  20335. var camera = this.getCameraByName(name);
  20336. if (camera) {
  20337. return camera;
  20338. }
  20339. var bone = this.getBoneByName(name);
  20340. return bone;
  20341. };
  20342. Scene.prototype.getMeshByName = function (name) {
  20343. for (var index = 0; index < this.meshes.length; index++) {
  20344. if (this.meshes[index].name === name) {
  20345. return this.meshes[index];
  20346. }
  20347. }
  20348. return null;
  20349. };
  20350. Scene.prototype.getTransformNodeByName = function (name) {
  20351. for (var index = 0; index < this.transformNodes.length; index++) {
  20352. if (this.transformNodes[index].name === name) {
  20353. return this.transformNodes[index];
  20354. }
  20355. }
  20356. return null;
  20357. };
  20358. Scene.prototype.getSoundByName = function (name) {
  20359. var index;
  20360. if (BABYLON.AudioEngine) {
  20361. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  20362. if (this.mainSoundTrack.soundCollection[index].name === name) {
  20363. return this.mainSoundTrack.soundCollection[index];
  20364. }
  20365. }
  20366. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  20367. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  20368. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  20369. return this.soundTracks[sdIndex].soundCollection[index];
  20370. }
  20371. }
  20372. }
  20373. }
  20374. return null;
  20375. };
  20376. Scene.prototype.getLastSkeletonByID = function (id) {
  20377. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  20378. if (this.skeletons[index].id === id) {
  20379. return this.skeletons[index];
  20380. }
  20381. }
  20382. return null;
  20383. };
  20384. Scene.prototype.getSkeletonById = function (id) {
  20385. for (var index = 0; index < this.skeletons.length; index++) {
  20386. if (this.skeletons[index].id === id) {
  20387. return this.skeletons[index];
  20388. }
  20389. }
  20390. return null;
  20391. };
  20392. Scene.prototype.getSkeletonByName = function (name) {
  20393. for (var index = 0; index < this.skeletons.length; index++) {
  20394. if (this.skeletons[index].name === name) {
  20395. return this.skeletons[index];
  20396. }
  20397. }
  20398. return null;
  20399. };
  20400. Scene.prototype.getMorphTargetManagerById = function (id) {
  20401. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  20402. if (this.morphTargetManagers[index].uniqueId === id) {
  20403. return this.morphTargetManagers[index];
  20404. }
  20405. }
  20406. return null;
  20407. };
  20408. Scene.prototype.isActiveMesh = function (mesh) {
  20409. return (this._activeMeshes.indexOf(mesh) !== -1);
  20410. };
  20411. /**
  20412. * Return a the first highlight layer of the scene with a given name.
  20413. * @param name The name of the highlight layer to look for.
  20414. * @return The highlight layer if found otherwise null.
  20415. */
  20416. Scene.prototype.getHighlightLayerByName = function (name) {
  20417. for (var index = 0; index < this.highlightLayers.length; index++) {
  20418. if (this.highlightLayers[index].name === name) {
  20419. return this.highlightLayers[index];
  20420. }
  20421. }
  20422. return null;
  20423. };
  20424. Object.defineProperty(Scene.prototype, "uid", {
  20425. /**
  20426. * Return a unique id as a string which can serve as an identifier for the scene
  20427. */
  20428. get: function () {
  20429. if (!this._uid) {
  20430. this._uid = BABYLON.Tools.RandomId();
  20431. }
  20432. return this._uid;
  20433. },
  20434. enumerable: true,
  20435. configurable: true
  20436. });
  20437. /**
  20438. * Add an externaly attached data from its key.
  20439. * This method call will fail and return false, if such key already exists.
  20440. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  20441. * @param key the unique key that identifies the data
  20442. * @param data the data object to associate to the key for this Engine instance
  20443. * @return true if no such key were already present and the data was added successfully, false otherwise
  20444. */
  20445. Scene.prototype.addExternalData = function (key, data) {
  20446. if (!this._externalData) {
  20447. this._externalData = new BABYLON.StringDictionary();
  20448. }
  20449. return this._externalData.add(key, data);
  20450. };
  20451. /**
  20452. * Get an externaly attached data from its key
  20453. * @param key the unique key that identifies the data
  20454. * @return the associated data, if present (can be null), or undefined if not present
  20455. */
  20456. Scene.prototype.getExternalData = function (key) {
  20457. if (!this._externalData) {
  20458. return null;
  20459. }
  20460. return this._externalData.get(key);
  20461. };
  20462. /**
  20463. * Get an externaly attached data from its key, create it using a factory if it's not already present
  20464. * @param key the unique key that identifies the data
  20465. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  20466. * @return the associated data, can be null if the factory returned null.
  20467. */
  20468. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  20469. if (!this._externalData) {
  20470. this._externalData = new BABYLON.StringDictionary();
  20471. }
  20472. return this._externalData.getOrAddWithFactory(key, factory);
  20473. };
  20474. /**
  20475. * Remove an externaly attached data from the Engine instance
  20476. * @param key the unique key that identifies the data
  20477. * @return true if the data was successfully removed, false if it doesn't exist
  20478. */
  20479. Scene.prototype.removeExternalData = function (key) {
  20480. return this._externalData.remove(key);
  20481. };
  20482. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  20483. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  20484. var material = subMesh.getMaterial();
  20485. if (mesh.showSubMeshesBoundingBox) {
  20486. var boundingInfo = subMesh.getBoundingInfo();
  20487. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  20488. }
  20489. if (material) {
  20490. // Render targets
  20491. if (material.getRenderTargetTextures) {
  20492. if (this._processedMaterials.indexOf(material) === -1) {
  20493. this._processedMaterials.push(material);
  20494. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  20495. }
  20496. }
  20497. // Dispatch
  20498. this._activeIndices.addCount(subMesh.indexCount, false);
  20499. this._renderingManager.dispatch(subMesh);
  20500. }
  20501. }
  20502. };
  20503. Scene.prototype._isInIntermediateRendering = function () {
  20504. return this._intermediateRendering;
  20505. };
  20506. /**
  20507. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  20508. */
  20509. Scene.prototype.freezeActiveMeshes = function () {
  20510. this._evaluateActiveMeshes();
  20511. this._activeMeshesFrozen = true;
  20512. return this;
  20513. };
  20514. /**
  20515. * Use this function to restart evaluating active meshes on every frame
  20516. */
  20517. Scene.prototype.unfreezeActiveMeshes = function () {
  20518. this._activeMeshesFrozen = false;
  20519. return this;
  20520. };
  20521. Scene.prototype._evaluateActiveMeshes = function () {
  20522. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  20523. return;
  20524. }
  20525. if (!this.activeCamera) {
  20526. return;
  20527. }
  20528. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  20529. this.activeCamera._activeMeshes.reset();
  20530. this._activeMeshes.reset();
  20531. this._renderingManager.reset();
  20532. this._processedMaterials.reset();
  20533. this._activeParticleSystems.reset();
  20534. this._activeSkeletons.reset();
  20535. this._softwareSkinnedMeshes.reset();
  20536. if (this._boundingBoxRenderer) {
  20537. this._boundingBoxRenderer.reset();
  20538. }
  20539. // Meshes
  20540. var meshes;
  20541. var len;
  20542. if (this._selectionOctree) {
  20543. var selection = this._selectionOctree.select(this._frustumPlanes);
  20544. meshes = selection.data;
  20545. len = selection.length;
  20546. }
  20547. else {
  20548. len = this.meshes.length;
  20549. meshes = this.meshes;
  20550. }
  20551. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  20552. var mesh = meshes[meshIndex];
  20553. if (mesh.isBlocked) {
  20554. continue;
  20555. }
  20556. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  20557. if (!mesh.isReady() || !mesh.isEnabled()) {
  20558. continue;
  20559. }
  20560. mesh.computeWorldMatrix();
  20561. // Intersections
  20562. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  20563. this._meshesForIntersections.pushNoDuplicate(mesh);
  20564. }
  20565. // Switch to current LOD
  20566. var meshLOD = mesh.getLOD(this.activeCamera);
  20567. if (!meshLOD) {
  20568. continue;
  20569. }
  20570. mesh._preActivate();
  20571. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  20572. this._activeMeshes.push(mesh);
  20573. this.activeCamera._activeMeshes.push(mesh);
  20574. mesh._activate(this._renderId);
  20575. if (meshLOD !== mesh) {
  20576. meshLOD._activate(this._renderId);
  20577. }
  20578. this._activeMesh(mesh, meshLOD);
  20579. }
  20580. }
  20581. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  20582. // Particle systems
  20583. if (this.particlesEnabled) {
  20584. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  20585. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  20586. var particleSystem = this.particleSystems[particleIndex];
  20587. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  20588. continue;
  20589. }
  20590. var emitter = particleSystem.emitter;
  20591. if (!emitter.position || emitter.isEnabled()) {
  20592. this._activeParticleSystems.push(particleSystem);
  20593. particleSystem.animate();
  20594. this._renderingManager.dispatchParticles(particleSystem);
  20595. }
  20596. }
  20597. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  20598. }
  20599. };
  20600. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  20601. if (mesh.skeleton && this.skeletonsEnabled) {
  20602. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  20603. mesh.skeleton.prepare();
  20604. }
  20605. if (!mesh.computeBonesUsingShaders) {
  20606. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  20607. }
  20608. }
  20609. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  20610. var boundingInfo = sourceMesh.getBoundingInfo();
  20611. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  20612. }
  20613. if (mesh && mesh.subMeshes) {
  20614. // Submeshes Octrees
  20615. var len;
  20616. var subMeshes;
  20617. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  20618. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  20619. len = intersections.length;
  20620. subMeshes = intersections.data;
  20621. }
  20622. else {
  20623. subMeshes = mesh.subMeshes;
  20624. len = subMeshes.length;
  20625. }
  20626. for (var subIndex = 0; subIndex < len; subIndex++) {
  20627. var subMesh = subMeshes[subIndex];
  20628. this._evaluateSubMesh(subMesh, mesh);
  20629. }
  20630. }
  20631. };
  20632. Scene.prototype.updateTransformMatrix = function (force) {
  20633. if (!this.activeCamera) {
  20634. return;
  20635. }
  20636. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  20637. };
  20638. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  20639. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  20640. };
  20641. Scene.prototype._renderForCamera = function (camera) {
  20642. if (camera && camera._skipRendering) {
  20643. return;
  20644. }
  20645. var engine = this._engine;
  20646. this.activeCamera = camera;
  20647. if (!this.activeCamera)
  20648. throw new Error("Active camera not set");
  20649. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  20650. // Viewport
  20651. engine.setViewport(this.activeCamera.viewport);
  20652. // Camera
  20653. this.resetCachedMaterial();
  20654. this._renderId++;
  20655. this.activeCamera.update();
  20656. this.updateTransformMatrix();
  20657. if (camera._alternateCamera) {
  20658. this.updateAlternateTransformMatrix(camera._alternateCamera);
  20659. this._alternateRendering = true;
  20660. }
  20661. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  20662. // Meshes
  20663. this._evaluateActiveMeshes();
  20664. // Software skinning
  20665. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  20666. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  20667. mesh.applySkeleton(mesh.skeleton);
  20668. }
  20669. // Render targets
  20670. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  20671. var needsRestoreFrameBuffer = false;
  20672. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  20673. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  20674. }
  20675. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  20676. this._intermediateRendering = true;
  20677. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  20678. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  20679. var renderTarget = this._renderTargets.data[renderIndex];
  20680. if (renderTarget._shouldRender()) {
  20681. this._renderId++;
  20682. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  20683. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  20684. }
  20685. }
  20686. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  20687. this._intermediateRendering = false;
  20688. this._renderId++;
  20689. needsRestoreFrameBuffer = true; // Restore back buffer
  20690. }
  20691. // Render HighlightLayer Texture
  20692. var stencilState = this._engine.getStencilBuffer();
  20693. var renderhighlights = false;
  20694. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  20695. this._intermediateRendering = true;
  20696. for (var i = 0; i < this.highlightLayers.length; i++) {
  20697. var highlightLayer = this.highlightLayers[i];
  20698. if (highlightLayer.shouldRender() &&
  20699. (!highlightLayer.camera ||
  20700. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  20701. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  20702. renderhighlights = true;
  20703. var renderTarget = highlightLayer._mainTexture;
  20704. if (renderTarget._shouldRender()) {
  20705. this._renderId++;
  20706. renderTarget.render(false, false);
  20707. needsRestoreFrameBuffer = true;
  20708. }
  20709. }
  20710. }
  20711. this._intermediateRendering = false;
  20712. this._renderId++;
  20713. }
  20714. if (needsRestoreFrameBuffer) {
  20715. engine.restoreDefaultFramebuffer(); // Restore back buffer
  20716. }
  20717. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  20718. // Prepare Frame
  20719. this.postProcessManager._prepareFrame();
  20720. // Backgrounds
  20721. var layerIndex;
  20722. var layer;
  20723. if (this.layers.length) {
  20724. engine.setDepthBuffer(false);
  20725. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  20726. layer = this.layers[layerIndex];
  20727. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  20728. layer.render();
  20729. }
  20730. }
  20731. engine.setDepthBuffer(true);
  20732. }
  20733. // Activate HighlightLayer stencil
  20734. if (renderhighlights) {
  20735. this._engine.setStencilBuffer(true);
  20736. }
  20737. // Render
  20738. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  20739. this._renderingManager.render(null, null, true, true);
  20740. this.onAfterDrawPhaseObservable.notifyObservers(this);
  20741. // Restore HighlightLayer stencil
  20742. if (renderhighlights) {
  20743. this._engine.setStencilBuffer(stencilState);
  20744. }
  20745. // Bounding boxes
  20746. if (this._boundingBoxRenderer) {
  20747. this._boundingBoxRenderer.render();
  20748. }
  20749. // Lens flares
  20750. if (this.lensFlaresEnabled) {
  20751. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  20752. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  20753. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  20754. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  20755. lensFlareSystem.render();
  20756. }
  20757. }
  20758. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  20759. }
  20760. // Foregrounds
  20761. if (this.layers.length) {
  20762. engine.setDepthBuffer(false);
  20763. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  20764. layer = this.layers[layerIndex];
  20765. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  20766. layer.render();
  20767. }
  20768. }
  20769. engine.setDepthBuffer(true);
  20770. }
  20771. // Highlight Layer
  20772. if (renderhighlights) {
  20773. engine.setDepthBuffer(false);
  20774. for (var i = 0; i < this.highlightLayers.length; i++) {
  20775. if (this.highlightLayers[i].shouldRender()) {
  20776. this.highlightLayers[i].render();
  20777. }
  20778. }
  20779. engine.setDepthBuffer(true);
  20780. }
  20781. // Finalize frame
  20782. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  20783. // Reset some special arrays
  20784. this._renderTargets.reset();
  20785. this._alternateRendering = false;
  20786. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  20787. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  20788. };
  20789. Scene.prototype._processSubCameras = function (camera) {
  20790. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  20791. this._renderForCamera(camera);
  20792. return;
  20793. }
  20794. // Update camera
  20795. if (this.activeCamera) {
  20796. this.activeCamera.update();
  20797. }
  20798. // rig cameras
  20799. for (var index = 0; index < camera._rigCameras.length; index++) {
  20800. this._renderForCamera(camera._rigCameras[index]);
  20801. }
  20802. this.activeCamera = camera;
  20803. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  20804. };
  20805. Scene.prototype._checkIntersections = function () {
  20806. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  20807. var sourceMesh = this._meshesForIntersections.data[index];
  20808. if (!sourceMesh.actionManager) {
  20809. continue;
  20810. }
  20811. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  20812. var action = sourceMesh.actionManager.actions[actionIndex];
  20813. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20814. var parameters = action.getTriggerParameter();
  20815. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  20816. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  20817. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  20818. if (areIntersecting && currentIntersectionInProgress === -1) {
  20819. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  20820. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  20821. sourceMesh._intersectionsInProgress.push(otherMesh);
  20822. }
  20823. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20824. sourceMesh._intersectionsInProgress.push(otherMesh);
  20825. }
  20826. }
  20827. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  20828. //They intersected, and now they don't.
  20829. //is this trigger an exit trigger? execute an event.
  20830. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20831. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  20832. }
  20833. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  20834. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20835. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  20836. }
  20837. }
  20838. }
  20839. }
  20840. }
  20841. };
  20842. Scene.prototype.render = function () {
  20843. if (this.isDisposed) {
  20844. return;
  20845. }
  20846. this._activeParticles.fetchNewFrame();
  20847. this._totalVertices.fetchNewFrame();
  20848. this._activeIndices.fetchNewFrame();
  20849. this._activeBones.fetchNewFrame();
  20850. this._meshesForIntersections.reset();
  20851. this.resetCachedMaterial();
  20852. this.onBeforeAnimationsObservable.notifyObservers(this);
  20853. // Actions
  20854. if (this.actionManager) {
  20855. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  20856. }
  20857. //Simplification Queue
  20858. if (this.simplificationQueue && !this.simplificationQueue.running) {
  20859. this.simplificationQueue.executeNext();
  20860. }
  20861. if (this._engine.isDeterministicLockStep()) {
  20862. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  20863. var defaultFPS = (60.0 / 1000.0);
  20864. var defaultFrameTime = 1000 / 60; // frame time in MS
  20865. if (this._physicsEngine) {
  20866. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  20867. }
  20868. var stepsTaken = 0;
  20869. var maxSubSteps = this._engine.getLockstepMaxSteps();
  20870. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  20871. internalSteps = Math.min(internalSteps, maxSubSteps);
  20872. do {
  20873. this.onBeforeStepObservable.notifyObservers(this);
  20874. // Animations
  20875. this._animationRatio = defaultFrameTime * defaultFPS;
  20876. this._animate();
  20877. this.onAfterAnimationsObservable.notifyObservers(this);
  20878. // Physics
  20879. if (this._physicsEngine) {
  20880. this.onBeforePhysicsObservable.notifyObservers(this);
  20881. this._physicsEngine._step(defaultFrameTime / 1000);
  20882. this.onAfterPhysicsObservable.notifyObservers(this);
  20883. }
  20884. this.onAfterStepObservable.notifyObservers(this);
  20885. this._currentStepId++;
  20886. stepsTaken++;
  20887. deltaTime -= defaultFrameTime;
  20888. } while (deltaTime > 0 && stepsTaken < internalSteps);
  20889. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  20890. }
  20891. else {
  20892. // Animations
  20893. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  20894. this._animationRatio = deltaTime * (60.0 / 1000.0);
  20895. this._animate();
  20896. this.onAfterAnimationsObservable.notifyObservers(this);
  20897. // Physics
  20898. if (this._physicsEngine) {
  20899. this.onBeforePhysicsObservable.notifyObservers(this);
  20900. this._physicsEngine._step(deltaTime / 1000.0);
  20901. this.onAfterPhysicsObservable.notifyObservers(this);
  20902. }
  20903. }
  20904. // update gamepad manager
  20905. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  20906. this._gamepadManager._checkGamepadsStatus();
  20907. }
  20908. // Before render
  20909. this.onBeforeRenderObservable.notifyObservers(this);
  20910. // Customs render targets
  20911. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  20912. var engine = this.getEngine();
  20913. var currentActiveCamera = this.activeCamera;
  20914. if (this.renderTargetsEnabled) {
  20915. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20916. this._intermediateRendering = true;
  20917. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  20918. var renderTarget = this.customRenderTargets[customIndex];
  20919. if (renderTarget._shouldRender()) {
  20920. this._renderId++;
  20921. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  20922. if (!this.activeCamera)
  20923. throw new Error("Active camera not set");
  20924. // Viewport
  20925. engine.setViewport(this.activeCamera.viewport);
  20926. // Camera
  20927. this.updateTransformMatrix();
  20928. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  20929. }
  20930. }
  20931. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20932. this._intermediateRendering = false;
  20933. this._renderId++;
  20934. }
  20935. // Restore back buffer
  20936. if (this.customRenderTargets.length > 0) {
  20937. engine.restoreDefaultFramebuffer();
  20938. }
  20939. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  20940. this.activeCamera = currentActiveCamera;
  20941. // Procedural textures
  20942. if (this.proceduralTexturesEnabled) {
  20943. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20944. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  20945. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  20946. if (proceduralTexture._shouldRender()) {
  20947. proceduralTexture.render();
  20948. }
  20949. }
  20950. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20951. }
  20952. // Clear
  20953. if (this.autoClearDepthAndStencil || this.autoClear) {
  20954. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  20955. }
  20956. // Shadows
  20957. if (this.shadowsEnabled) {
  20958. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  20959. var light = this.lights[lightIndex];
  20960. var shadowGenerator = light.getShadowGenerator();
  20961. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  20962. var shadowMap = (shadowGenerator.getShadowMap());
  20963. if (this.textures.indexOf(shadowMap) !== -1) {
  20964. this._renderTargets.push(shadowMap);
  20965. }
  20966. }
  20967. }
  20968. }
  20969. // Depth renderer
  20970. if (this._depthRenderer) {
  20971. this._renderTargets.push(this._depthRenderer.getDepthMap());
  20972. }
  20973. // Geometry renderer
  20974. if (this._geometryBufferRenderer) {
  20975. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  20976. }
  20977. // RenderPipeline
  20978. if (this._postProcessRenderPipelineManager) {
  20979. this._postProcessRenderPipelineManager.update();
  20980. }
  20981. // Multi-cameras?
  20982. if (this.activeCameras.length > 0) {
  20983. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  20984. if (cameraIndex > 0) {
  20985. this._engine.clear(null, false, true, true);
  20986. }
  20987. this._processSubCameras(this.activeCameras[cameraIndex]);
  20988. }
  20989. }
  20990. else {
  20991. if (!this.activeCamera) {
  20992. throw new Error("No camera defined");
  20993. }
  20994. this._processSubCameras(this.activeCamera);
  20995. }
  20996. // Intersection checks
  20997. this._checkIntersections();
  20998. // Update the audio listener attached to the camera
  20999. if (BABYLON.AudioEngine) {
  21000. this._updateAudioParameters();
  21001. }
  21002. // After render
  21003. if (this.afterRender) {
  21004. this.afterRender();
  21005. }
  21006. this.onAfterRenderObservable.notifyObservers(this);
  21007. // Cleaning
  21008. for (var index = 0; index < this._toBeDisposed.length; index++) {
  21009. var data = this._toBeDisposed.data[index];
  21010. if (data) {
  21011. data.dispose();
  21012. }
  21013. this._toBeDisposed[index] = null;
  21014. }
  21015. this._toBeDisposed.reset();
  21016. if (this.dumpNextRenderTargets) {
  21017. this.dumpNextRenderTargets = false;
  21018. }
  21019. this._activeBones.addCount(0, true);
  21020. this._activeIndices.addCount(0, true);
  21021. this._activeParticles.addCount(0, true);
  21022. };
  21023. Scene.prototype._updateAudioParameters = function () {
  21024. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  21025. return;
  21026. }
  21027. var listeningCamera;
  21028. var audioEngine = BABYLON.Engine.audioEngine;
  21029. if (this.activeCameras.length > 0) {
  21030. listeningCamera = this.activeCameras[0];
  21031. }
  21032. else {
  21033. listeningCamera = this.activeCamera;
  21034. }
  21035. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  21036. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  21037. // for VR cameras
  21038. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  21039. listeningCamera = listeningCamera.rigCameras[0];
  21040. }
  21041. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  21042. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  21043. cameraDirection.normalize();
  21044. // To avoid some errors on GearVR
  21045. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  21046. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  21047. }
  21048. var i;
  21049. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21050. var sound = this.mainSoundTrack.soundCollection[i];
  21051. if (sound.useCustomAttenuation) {
  21052. sound.updateDistanceFromListener();
  21053. }
  21054. }
  21055. for (i = 0; i < this.soundTracks.length; i++) {
  21056. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21057. sound = this.soundTracks[i].soundCollection[j];
  21058. if (sound.useCustomAttenuation) {
  21059. sound.updateDistanceFromListener();
  21060. }
  21061. }
  21062. }
  21063. }
  21064. };
  21065. Object.defineProperty(Scene.prototype, "audioEnabled", {
  21066. // Audio
  21067. get: function () {
  21068. return this._audioEnabled;
  21069. },
  21070. set: function (value) {
  21071. this._audioEnabled = value;
  21072. if (BABYLON.AudioEngine) {
  21073. if (this._audioEnabled) {
  21074. this._enableAudio();
  21075. }
  21076. else {
  21077. this._disableAudio();
  21078. }
  21079. }
  21080. },
  21081. enumerable: true,
  21082. configurable: true
  21083. });
  21084. Scene.prototype._disableAudio = function () {
  21085. var i;
  21086. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21087. this.mainSoundTrack.soundCollection[i].pause();
  21088. }
  21089. for (i = 0; i < this.soundTracks.length; i++) {
  21090. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21091. this.soundTracks[i].soundCollection[j].pause();
  21092. }
  21093. }
  21094. };
  21095. Scene.prototype._enableAudio = function () {
  21096. var i;
  21097. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21098. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  21099. this.mainSoundTrack.soundCollection[i].play();
  21100. }
  21101. }
  21102. for (i = 0; i < this.soundTracks.length; i++) {
  21103. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21104. if (this.soundTracks[i].soundCollection[j].isPaused) {
  21105. this.soundTracks[i].soundCollection[j].play();
  21106. }
  21107. }
  21108. }
  21109. };
  21110. Object.defineProperty(Scene.prototype, "headphone", {
  21111. get: function () {
  21112. return this._headphone;
  21113. },
  21114. set: function (value) {
  21115. this._headphone = value;
  21116. if (BABYLON.AudioEngine) {
  21117. if (this._headphone) {
  21118. this._switchAudioModeForHeadphones();
  21119. }
  21120. else {
  21121. this._switchAudioModeForNormalSpeakers();
  21122. }
  21123. }
  21124. },
  21125. enumerable: true,
  21126. configurable: true
  21127. });
  21128. Scene.prototype._switchAudioModeForHeadphones = function () {
  21129. this.mainSoundTrack.switchPanningModelToHRTF();
  21130. for (var i = 0; i < this.soundTracks.length; i++) {
  21131. this.soundTracks[i].switchPanningModelToHRTF();
  21132. }
  21133. };
  21134. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  21135. this.mainSoundTrack.switchPanningModelToEqualPower();
  21136. for (var i = 0; i < this.soundTracks.length; i++) {
  21137. this.soundTracks[i].switchPanningModelToEqualPower();
  21138. }
  21139. };
  21140. Scene.prototype.enableDepthRenderer = function () {
  21141. if (this._depthRenderer) {
  21142. return this._depthRenderer;
  21143. }
  21144. this._depthRenderer = new BABYLON.DepthRenderer(this);
  21145. return this._depthRenderer;
  21146. };
  21147. Scene.prototype.disableDepthRenderer = function () {
  21148. if (!this._depthRenderer) {
  21149. return;
  21150. }
  21151. this._depthRenderer.dispose();
  21152. this._depthRenderer = null;
  21153. };
  21154. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  21155. if (ratio === void 0) { ratio = 1; }
  21156. if (this._geometryBufferRenderer) {
  21157. return this._geometryBufferRenderer;
  21158. }
  21159. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  21160. if (!this._geometryBufferRenderer.isSupported) {
  21161. this._geometryBufferRenderer = null;
  21162. }
  21163. return this._geometryBufferRenderer;
  21164. };
  21165. Scene.prototype.disableGeometryBufferRenderer = function () {
  21166. if (!this._geometryBufferRenderer) {
  21167. return;
  21168. }
  21169. this._geometryBufferRenderer.dispose();
  21170. this._geometryBufferRenderer = null;
  21171. };
  21172. Scene.prototype.freezeMaterials = function () {
  21173. for (var i = 0; i < this.materials.length; i++) {
  21174. this.materials[i].freeze();
  21175. }
  21176. };
  21177. Scene.prototype.unfreezeMaterials = function () {
  21178. for (var i = 0; i < this.materials.length; i++) {
  21179. this.materials[i].unfreeze();
  21180. }
  21181. };
  21182. Scene.prototype.dispose = function () {
  21183. this.beforeRender = null;
  21184. this.afterRender = null;
  21185. this.skeletons = [];
  21186. this.morphTargetManagers = [];
  21187. this.importedMeshesFiles = new Array();
  21188. this.stopAllAnimations();
  21189. this.resetCachedMaterial();
  21190. if (this._depthRenderer) {
  21191. this._depthRenderer.dispose();
  21192. }
  21193. if (this._gamepadManager) {
  21194. this._gamepadManager.dispose();
  21195. this._gamepadManager = null;
  21196. }
  21197. // Smart arrays
  21198. if (this.activeCamera) {
  21199. this.activeCamera._activeMeshes.dispose();
  21200. this.activeCamera = null;
  21201. }
  21202. this._activeMeshes.dispose();
  21203. this._renderingManager.dispose();
  21204. this._processedMaterials.dispose();
  21205. this._activeParticleSystems.dispose();
  21206. this._activeSkeletons.dispose();
  21207. this._softwareSkinnedMeshes.dispose();
  21208. this._renderTargets.dispose();
  21209. if (this._boundingBoxRenderer) {
  21210. this._boundingBoxRenderer.dispose();
  21211. }
  21212. this._meshesForIntersections.dispose();
  21213. this._toBeDisposed.dispose();
  21214. // Debug layer
  21215. if (this._debugLayer) {
  21216. this._debugLayer.hide();
  21217. }
  21218. // Events
  21219. this.onDisposeObservable.notifyObservers(this);
  21220. this.onDisposeObservable.clear();
  21221. this.onBeforeRenderObservable.clear();
  21222. this.onAfterRenderObservable.clear();
  21223. this.OnBeforeRenderTargetsRenderObservable.clear();
  21224. this.OnAfterRenderTargetsRenderObservable.clear();
  21225. this.onAfterStepObservable.clear();
  21226. this.onBeforeStepObservable.clear();
  21227. this.onBeforeActiveMeshesEvaluationObservable.clear();
  21228. this.onAfterActiveMeshesEvaluationObservable.clear();
  21229. this.onBeforeParticlesRenderingObservable.clear();
  21230. this.onAfterParticlesRenderingObservable.clear();
  21231. this.onBeforeSpritesRenderingObservable.clear();
  21232. this.onAfterSpritesRenderingObservable.clear();
  21233. this.onBeforeDrawPhaseObservable.clear();
  21234. this.onAfterDrawPhaseObservable.clear();
  21235. this.onBeforePhysicsObservable.clear();
  21236. this.onAfterPhysicsObservable.clear();
  21237. this.onBeforeAnimationsObservable.clear();
  21238. this.onAfterAnimationsObservable.clear();
  21239. this.onDataLoadedObservable.clear();
  21240. this.detachControl();
  21241. // Release sounds & sounds tracks
  21242. if (BABYLON.AudioEngine) {
  21243. this.disposeSounds();
  21244. }
  21245. // VR Helper
  21246. if (this.VRHelper) {
  21247. this.VRHelper.dispose();
  21248. }
  21249. // Detach cameras
  21250. var canvas = this._engine.getRenderingCanvas();
  21251. if (canvas) {
  21252. var index;
  21253. for (index = 0; index < this.cameras.length; index++) {
  21254. this.cameras[index].detachControl(canvas);
  21255. }
  21256. }
  21257. // Release animation groups
  21258. while (this.animationGroups.length) {
  21259. this.animationGroups[0].dispose();
  21260. }
  21261. // Release lights
  21262. while (this.lights.length) {
  21263. this.lights[0].dispose();
  21264. }
  21265. // Release meshes
  21266. while (this.meshes.length) {
  21267. this.meshes[0].dispose(true);
  21268. }
  21269. while (this.transformNodes.length) {
  21270. this.removeTransformNode(this.transformNodes[0]);
  21271. }
  21272. // Release cameras
  21273. while (this.cameras.length) {
  21274. this.cameras[0].dispose();
  21275. }
  21276. // Release materials
  21277. if (this.defaultMaterial) {
  21278. this.defaultMaterial.dispose();
  21279. }
  21280. while (this.multiMaterials.length) {
  21281. this.multiMaterials[0].dispose();
  21282. }
  21283. while (this.materials.length) {
  21284. this.materials[0].dispose();
  21285. }
  21286. // Release particles
  21287. while (this.particleSystems.length) {
  21288. this.particleSystems[0].dispose();
  21289. }
  21290. // Release sprites
  21291. while (this.spriteManagers.length) {
  21292. this.spriteManagers[0].dispose();
  21293. }
  21294. // Release postProcesses
  21295. while (this.postProcesses.length) {
  21296. this.postProcesses[0].dispose();
  21297. }
  21298. // Release layers
  21299. while (this.layers.length) {
  21300. this.layers[0].dispose();
  21301. }
  21302. while (this.highlightLayers.length) {
  21303. this.highlightLayers[0].dispose();
  21304. }
  21305. // Release textures
  21306. while (this.textures.length) {
  21307. this.textures[0].dispose();
  21308. }
  21309. // Release UBO
  21310. this._sceneUbo.dispose();
  21311. if (this._alternateSceneUbo) {
  21312. this._alternateSceneUbo.dispose();
  21313. }
  21314. // Post-processes
  21315. this.postProcessManager.dispose();
  21316. if (this._postProcessRenderPipelineManager) {
  21317. this._postProcessRenderPipelineManager.dispose();
  21318. }
  21319. // Physics
  21320. if (this._physicsEngine) {
  21321. this.disablePhysicsEngine();
  21322. }
  21323. // Remove from engine
  21324. index = this._engine.scenes.indexOf(this);
  21325. if (index > -1) {
  21326. this._engine.scenes.splice(index, 1);
  21327. }
  21328. this._engine.wipeCaches(true);
  21329. this._isDisposed = true;
  21330. };
  21331. Object.defineProperty(Scene.prototype, "isDisposed", {
  21332. get: function () {
  21333. return this._isDisposed;
  21334. },
  21335. enumerable: true,
  21336. configurable: true
  21337. });
  21338. // Release sounds & sounds tracks
  21339. Scene.prototype.disposeSounds = function () {
  21340. if (!this._mainSoundTrack) {
  21341. return;
  21342. }
  21343. this.mainSoundTrack.dispose();
  21344. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  21345. this.soundTracks[scIndex].dispose();
  21346. }
  21347. };
  21348. // Octrees
  21349. Scene.prototype.getWorldExtends = function () {
  21350. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21351. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21352. for (var index = 0; index < this.meshes.length; index++) {
  21353. var mesh = this.meshes[index];
  21354. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  21355. continue;
  21356. }
  21357. mesh.computeWorldMatrix(true);
  21358. var boundingInfo = mesh.getBoundingInfo();
  21359. var minBox = boundingInfo.boundingBox.minimumWorld;
  21360. var maxBox = boundingInfo.boundingBox.maximumWorld;
  21361. BABYLON.Tools.CheckExtends(minBox, min, max);
  21362. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21363. }
  21364. return {
  21365. min: min,
  21366. max: max
  21367. };
  21368. };
  21369. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  21370. if (maxCapacity === void 0) { maxCapacity = 64; }
  21371. if (maxDepth === void 0) { maxDepth = 2; }
  21372. if (!this._selectionOctree) {
  21373. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  21374. }
  21375. var worldExtends = this.getWorldExtends();
  21376. // Update octree
  21377. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  21378. return this._selectionOctree;
  21379. };
  21380. // Picking
  21381. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  21382. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  21383. var result = BABYLON.Ray.Zero();
  21384. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  21385. return result;
  21386. };
  21387. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  21388. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  21389. var engine = this._engine;
  21390. if (!camera) {
  21391. if (!this.activeCamera)
  21392. throw new Error("Active camera not set");
  21393. camera = this.activeCamera;
  21394. }
  21395. var cameraViewport = camera.viewport;
  21396. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21397. // Moving coordinates to local viewport world
  21398. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21399. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21400. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  21401. return this;
  21402. };
  21403. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  21404. var result = BABYLON.Ray.Zero();
  21405. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  21406. return result;
  21407. };
  21408. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  21409. if (!BABYLON.PickingInfo) {
  21410. return this;
  21411. }
  21412. var engine = this._engine;
  21413. if (!camera) {
  21414. if (!this.activeCamera)
  21415. throw new Error("Active camera not set");
  21416. camera = this.activeCamera;
  21417. }
  21418. var cameraViewport = camera.viewport;
  21419. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21420. var identity = BABYLON.Matrix.Identity();
  21421. // Moving coordinates to local viewport world
  21422. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21423. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21424. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  21425. return this;
  21426. };
  21427. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  21428. if (!BABYLON.PickingInfo) {
  21429. return null;
  21430. }
  21431. var pickingInfo = null;
  21432. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21433. var mesh = this.meshes[meshIndex];
  21434. if (predicate) {
  21435. if (!predicate(mesh)) {
  21436. continue;
  21437. }
  21438. }
  21439. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21440. continue;
  21441. }
  21442. var world = mesh.getWorldMatrix();
  21443. var ray = rayFunction(world);
  21444. var result = mesh.intersects(ray, fastCheck);
  21445. if (!result || !result.hit)
  21446. continue;
  21447. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21448. continue;
  21449. pickingInfo = result;
  21450. if (fastCheck) {
  21451. break;
  21452. }
  21453. }
  21454. return pickingInfo || new BABYLON.PickingInfo();
  21455. };
  21456. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  21457. if (!BABYLON.PickingInfo) {
  21458. return null;
  21459. }
  21460. var pickingInfos = new Array();
  21461. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21462. var mesh = this.meshes[meshIndex];
  21463. if (predicate) {
  21464. if (!predicate(mesh)) {
  21465. continue;
  21466. }
  21467. }
  21468. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21469. continue;
  21470. }
  21471. var world = mesh.getWorldMatrix();
  21472. var ray = rayFunction(world);
  21473. var result = mesh.intersects(ray, false);
  21474. if (!result || !result.hit)
  21475. continue;
  21476. pickingInfos.push(result);
  21477. }
  21478. return pickingInfos;
  21479. };
  21480. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  21481. if (!BABYLON.PickingInfo) {
  21482. return null;
  21483. }
  21484. var pickingInfo = null;
  21485. if (!camera) {
  21486. if (!this.activeCamera) {
  21487. return null;
  21488. }
  21489. camera = this.activeCamera;
  21490. }
  21491. if (this.spriteManagers.length > 0) {
  21492. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  21493. var spriteManager = this.spriteManagers[spriteIndex];
  21494. if (!spriteManager.isPickable) {
  21495. continue;
  21496. }
  21497. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  21498. if (!result || !result.hit)
  21499. continue;
  21500. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21501. continue;
  21502. pickingInfo = result;
  21503. if (fastCheck) {
  21504. break;
  21505. }
  21506. }
  21507. }
  21508. return pickingInfo || new BABYLON.PickingInfo();
  21509. };
  21510. /** Launch a ray to try to pick a mesh in the scene
  21511. * @param x position on screen
  21512. * @param y position on screen
  21513. * @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
  21514. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  21515. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  21516. */
  21517. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  21518. var _this = this;
  21519. if (!BABYLON.PickingInfo) {
  21520. return null;
  21521. }
  21522. return this._internalPick(function (world) {
  21523. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  21524. return _this._tempPickingRay;
  21525. }, predicate, fastCheck);
  21526. };
  21527. /** Launch a ray to try to pick a sprite in the scene
  21528. * @param x position on screen
  21529. * @param y position on screen
  21530. * @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
  21531. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  21532. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  21533. */
  21534. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  21535. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  21536. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  21537. };
  21538. /** Use the given ray to pick a mesh in the scene
  21539. * @param ray The ray to use to pick meshes
  21540. * @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
  21541. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  21542. */
  21543. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  21544. var _this = this;
  21545. return this._internalPick(function (world) {
  21546. if (!_this._pickWithRayInverseMatrix) {
  21547. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  21548. }
  21549. world.invertToRef(_this._pickWithRayInverseMatrix);
  21550. if (!_this._cachedRayForTransform) {
  21551. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  21552. }
  21553. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  21554. return _this._cachedRayForTransform;
  21555. }, predicate, fastCheck);
  21556. };
  21557. /**
  21558. * Launch a ray to try to pick a mesh in the scene
  21559. * @param x X position on screen
  21560. * @param y Y position on screen
  21561. * @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
  21562. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  21563. */
  21564. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  21565. var _this = this;
  21566. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  21567. };
  21568. /**
  21569. * Launch a ray to try to pick a mesh in the scene
  21570. * @param ray Ray to use
  21571. * @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
  21572. */
  21573. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  21574. var _this = this;
  21575. return this._internalMultiPick(function (world) {
  21576. if (!_this._pickWithRayInverseMatrix) {
  21577. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  21578. }
  21579. world.invertToRef(_this._pickWithRayInverseMatrix);
  21580. if (!_this._cachedRayForTransform) {
  21581. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  21582. }
  21583. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  21584. return _this._cachedRayForTransform;
  21585. }, predicate);
  21586. };
  21587. Scene.prototype.setPointerOverMesh = function (mesh) {
  21588. if (this._pointerOverMesh === mesh) {
  21589. return;
  21590. }
  21591. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  21592. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  21593. }
  21594. this._pointerOverMesh = mesh;
  21595. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  21596. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  21597. }
  21598. };
  21599. Scene.prototype.getPointerOverMesh = function () {
  21600. return this._pointerOverMesh;
  21601. };
  21602. Scene.prototype.setPointerOverSprite = function (sprite) {
  21603. if (this._pointerOverSprite === sprite) {
  21604. return;
  21605. }
  21606. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  21607. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  21608. }
  21609. this._pointerOverSprite = sprite;
  21610. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  21611. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  21612. }
  21613. };
  21614. Scene.prototype.getPointerOverSprite = function () {
  21615. return this._pointerOverSprite;
  21616. };
  21617. // Physics
  21618. Scene.prototype.getPhysicsEngine = function () {
  21619. return this._physicsEngine;
  21620. };
  21621. /**
  21622. * Enables physics to the current scene
  21623. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  21624. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  21625. * @return {boolean} was the physics engine initialized
  21626. */
  21627. Scene.prototype.enablePhysics = function (gravity, plugin) {
  21628. if (gravity === void 0) { gravity = null; }
  21629. if (this._physicsEngine) {
  21630. return true;
  21631. }
  21632. try {
  21633. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  21634. return true;
  21635. }
  21636. catch (e) {
  21637. BABYLON.Tools.Error(e.message);
  21638. return false;
  21639. }
  21640. };
  21641. Scene.prototype.disablePhysicsEngine = function () {
  21642. if (!this._physicsEngine) {
  21643. return;
  21644. }
  21645. this._physicsEngine.dispose();
  21646. this._physicsEngine = null;
  21647. };
  21648. Scene.prototype.isPhysicsEnabled = function () {
  21649. return this._physicsEngine !== undefined;
  21650. };
  21651. Scene.prototype.deleteCompoundImpostor = function (compound) {
  21652. var mesh = compound.parts[0].mesh;
  21653. if (mesh.physicsImpostor) {
  21654. mesh.physicsImpostor.dispose();
  21655. mesh.physicsImpostor = null;
  21656. }
  21657. };
  21658. // Misc.
  21659. Scene.prototype._rebuildGeometries = function () {
  21660. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  21661. var geometry = _a[_i];
  21662. geometry._rebuild();
  21663. }
  21664. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  21665. var mesh = _c[_b];
  21666. mesh._rebuild();
  21667. }
  21668. if (this.postProcessManager) {
  21669. this.postProcessManager._rebuild();
  21670. }
  21671. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  21672. var layer = _e[_d];
  21673. layer._rebuild();
  21674. }
  21675. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  21676. var highlightLayer = _g[_f];
  21677. highlightLayer._rebuild();
  21678. }
  21679. if (this._boundingBoxRenderer) {
  21680. this._boundingBoxRenderer._rebuild();
  21681. }
  21682. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  21683. var system = _j[_h];
  21684. system.rebuild();
  21685. }
  21686. if (this._postProcessRenderPipelineManager) {
  21687. this._postProcessRenderPipelineManager._rebuild();
  21688. }
  21689. };
  21690. Scene.prototype._rebuildTextures = function () {
  21691. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  21692. var texture = _a[_i];
  21693. texture._rebuild();
  21694. }
  21695. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21696. };
  21697. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  21698. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  21699. if (replace === void 0) { replace = false; }
  21700. if (attachCameraControls === void 0) { attachCameraControls = false; }
  21701. // Dispose existing camera or light in replace mode.
  21702. if (replace) {
  21703. if (this.activeCamera) {
  21704. this.activeCamera.dispose();
  21705. this.activeCamera = null;
  21706. }
  21707. if (this.lights) {
  21708. for (var i = 0; i < this.lights.length; i++) {
  21709. this.lights[i].dispose();
  21710. }
  21711. }
  21712. }
  21713. // Light
  21714. if (this.lights.length === 0) {
  21715. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  21716. }
  21717. // Camera
  21718. if (!this.activeCamera) {
  21719. var worldExtends = this.getWorldExtends();
  21720. var worldSize = worldExtends.max.subtract(worldExtends.min);
  21721. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  21722. var camera;
  21723. var radius = worldSize.length() * 1.5;
  21724. if (createArcRotateCamera) {
  21725. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  21726. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  21727. arcRotateCamera.wheelPrecision = 100 / radius;
  21728. camera = arcRotateCamera;
  21729. }
  21730. else {
  21731. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  21732. freeCamera.setTarget(worldCenter);
  21733. camera = freeCamera;
  21734. }
  21735. camera.minZ = radius * 0.01;
  21736. camera.maxZ = radius * 100;
  21737. camera.speed = radius * 0.2;
  21738. this.activeCamera = camera;
  21739. var canvas = this.getEngine().getRenderingCanvas();
  21740. if (attachCameraControls && canvas) {
  21741. camera.attachControl(canvas);
  21742. }
  21743. }
  21744. };
  21745. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  21746. if (pbr === void 0) { pbr = false; }
  21747. if (scale === void 0) { scale = 1000; }
  21748. if (blur === void 0) { blur = 0; }
  21749. if (environmentTexture) {
  21750. this.environmentTexture = environmentTexture;
  21751. }
  21752. if (!this.environmentTexture) {
  21753. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  21754. return null;
  21755. }
  21756. // Skybox
  21757. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  21758. if (pbr) {
  21759. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  21760. hdrSkyboxMaterial.backFaceCulling = false;
  21761. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  21762. if (hdrSkyboxMaterial.reflectionTexture) {
  21763. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  21764. }
  21765. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  21766. hdrSkyboxMaterial.disableLighting = true;
  21767. hdrSkyboxMaterial.twoSidedLighting = true;
  21768. hdrSkybox.infiniteDistance = true;
  21769. hdrSkybox.material = hdrSkyboxMaterial;
  21770. }
  21771. else {
  21772. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  21773. skyboxMaterial.backFaceCulling = false;
  21774. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  21775. if (skyboxMaterial.reflectionTexture) {
  21776. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  21777. }
  21778. skyboxMaterial.disableLighting = true;
  21779. hdrSkybox.infiniteDistance = true;
  21780. hdrSkybox.material = skyboxMaterial;
  21781. }
  21782. return hdrSkybox;
  21783. };
  21784. Scene.prototype.createDefaultEnvironment = function (options) {
  21785. if (BABYLON.EnvironmentHelper) {
  21786. return new BABYLON.EnvironmentHelper(options, this);
  21787. }
  21788. return null;
  21789. };
  21790. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  21791. if (webVROptions === void 0) { webVROptions = {}; }
  21792. return new BABYLON.VRExperienceHelper(this, webVROptions);
  21793. };
  21794. // Tags
  21795. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  21796. if (tagsQuery === undefined) {
  21797. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  21798. return list;
  21799. }
  21800. var listByTags = [];
  21801. forEach = forEach || (function (item) { return; });
  21802. for (var i in list) {
  21803. var item = list[i];
  21804. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  21805. listByTags.push(item);
  21806. forEach(item);
  21807. }
  21808. }
  21809. return listByTags;
  21810. };
  21811. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  21812. return this._getByTags(this.meshes, tagsQuery, forEach);
  21813. };
  21814. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  21815. return this._getByTags(this.cameras, tagsQuery, forEach);
  21816. };
  21817. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  21818. return this._getByTags(this.lights, tagsQuery, forEach);
  21819. };
  21820. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  21821. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  21822. };
  21823. /**
  21824. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  21825. * This allowed control for front to back rendering or reversly depending of the special needs.
  21826. *
  21827. * @param renderingGroupId The rendering group id corresponding to its index
  21828. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21829. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21830. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21831. */
  21832. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21833. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21834. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21835. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21836. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  21837. };
  21838. /**
  21839. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21840. *
  21841. * @param renderingGroupId The rendering group id corresponding to its index
  21842. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21843. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21844. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21845. */
  21846. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21847. if (depth === void 0) { depth = true; }
  21848. if (stencil === void 0) { stencil = true; }
  21849. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  21850. };
  21851. /**
  21852. * Will flag all materials as dirty to trigger new shader compilation
  21853. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  21854. */
  21855. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  21856. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  21857. var material = _a[_i];
  21858. if (predicate && !predicate(material)) {
  21859. continue;
  21860. }
  21861. material.markAsDirty(flag);
  21862. }
  21863. };
  21864. // Statics
  21865. Scene._FOGMODE_NONE = 0;
  21866. Scene._FOGMODE_EXP = 1;
  21867. Scene._FOGMODE_EXP2 = 2;
  21868. Scene._FOGMODE_LINEAR = 3;
  21869. Scene._uniqueIdCounter = 0;
  21870. Scene.MinDeltaTime = 1.0;
  21871. Scene.MaxDeltaTime = 1000.0;
  21872. /** The distance in pixel that you have to move to prevent some events */
  21873. Scene.DragMovementThreshold = 10; // in pixels
  21874. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  21875. Scene.LongPressDelay = 500; // in milliseconds
  21876. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  21877. Scene.DoubleClickDelay = 300; // in milliseconds
  21878. /** If you need to check double click without raising a single click at first click, enable this flag */
  21879. Scene.ExclusiveDoubleClickMode = false;
  21880. return Scene;
  21881. }());
  21882. BABYLON.Scene = Scene;
  21883. })(BABYLON || (BABYLON = {}));
  21884. //# sourceMappingURL=babylon.scene.js.map
  21885. var BABYLON;
  21886. (function (BABYLON) {
  21887. var Buffer = /** @class */ (function () {
  21888. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  21889. if (instanced === void 0) { instanced = false; }
  21890. if (engine instanceof BABYLON.Mesh) {
  21891. this._engine = engine.getScene().getEngine();
  21892. }
  21893. else {
  21894. this._engine = engine;
  21895. }
  21896. this._updatable = updatable;
  21897. this._data = data;
  21898. this._strideSize = stride;
  21899. if (!postponeInternalCreation) {
  21900. this.create();
  21901. }
  21902. this._instanced = instanced;
  21903. this._instanceDivisor = instanced ? 1 : 0;
  21904. }
  21905. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  21906. // a lot of these parameters are ignored as they are overriden by the buffer
  21907. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  21908. };
  21909. // Properties
  21910. Buffer.prototype.isUpdatable = function () {
  21911. return this._updatable;
  21912. };
  21913. Buffer.prototype.getData = function () {
  21914. return this._data;
  21915. };
  21916. Buffer.prototype.getBuffer = function () {
  21917. return this._buffer;
  21918. };
  21919. Buffer.prototype.getStrideSize = function () {
  21920. return this._strideSize;
  21921. };
  21922. Buffer.prototype.getIsInstanced = function () {
  21923. return this._instanced;
  21924. };
  21925. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  21926. get: function () {
  21927. return this._instanceDivisor;
  21928. },
  21929. set: function (value) {
  21930. this._instanceDivisor = value;
  21931. if (value == 0) {
  21932. this._instanced = false;
  21933. }
  21934. else {
  21935. this._instanced = true;
  21936. }
  21937. },
  21938. enumerable: true,
  21939. configurable: true
  21940. });
  21941. // Methods
  21942. Buffer.prototype.create = function (data) {
  21943. if (data === void 0) { data = null; }
  21944. if (!data && this._buffer) {
  21945. return; // nothing to do
  21946. }
  21947. data = data || this._data;
  21948. if (!data) {
  21949. return;
  21950. }
  21951. if (!this._buffer) {
  21952. if (this._updatable) {
  21953. this._buffer = this._engine.createDynamicVertexBuffer(data);
  21954. this._data = data;
  21955. }
  21956. else {
  21957. this._buffer = this._engine.createVertexBuffer(data);
  21958. }
  21959. }
  21960. else if (this._updatable) {
  21961. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  21962. this._data = data;
  21963. }
  21964. };
  21965. Buffer.prototype._rebuild = function () {
  21966. this._buffer = null;
  21967. this.create(this._data);
  21968. };
  21969. Buffer.prototype.update = function (data) {
  21970. this.create(data);
  21971. };
  21972. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  21973. if (!this._buffer) {
  21974. return;
  21975. }
  21976. if (this._updatable) {
  21977. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  21978. this._data = null;
  21979. }
  21980. };
  21981. Buffer.prototype.dispose = function () {
  21982. if (!this._buffer) {
  21983. return;
  21984. }
  21985. if (this._engine._releaseBuffer(this._buffer)) {
  21986. this._buffer = null;
  21987. }
  21988. };
  21989. return Buffer;
  21990. }());
  21991. BABYLON.Buffer = Buffer;
  21992. })(BABYLON || (BABYLON = {}));
  21993. //# sourceMappingURL=babylon.buffer.js.map
  21994. var BABYLON;
  21995. (function (BABYLON) {
  21996. var VertexBuffer = /** @class */ (function () {
  21997. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  21998. if (!stride) {
  21999. // Deduce stride from kind
  22000. switch (kind) {
  22001. case VertexBuffer.PositionKind:
  22002. stride = 3;
  22003. break;
  22004. case VertexBuffer.NormalKind:
  22005. stride = 3;
  22006. break;
  22007. case VertexBuffer.UVKind:
  22008. case VertexBuffer.UV2Kind:
  22009. case VertexBuffer.UV3Kind:
  22010. case VertexBuffer.UV4Kind:
  22011. case VertexBuffer.UV5Kind:
  22012. case VertexBuffer.UV6Kind:
  22013. stride = 2;
  22014. break;
  22015. case VertexBuffer.TangentKind:
  22016. case VertexBuffer.ColorKind:
  22017. stride = 4;
  22018. break;
  22019. case VertexBuffer.MatricesIndicesKind:
  22020. case VertexBuffer.MatricesIndicesExtraKind:
  22021. stride = 4;
  22022. break;
  22023. case VertexBuffer.MatricesWeightsKind:
  22024. case VertexBuffer.MatricesWeightsExtraKind:
  22025. default:
  22026. stride = 4;
  22027. break;
  22028. }
  22029. }
  22030. if (data instanceof BABYLON.Buffer) {
  22031. if (!stride) {
  22032. stride = data.getStrideSize();
  22033. }
  22034. this._buffer = data;
  22035. this._ownsBuffer = false;
  22036. }
  22037. else {
  22038. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  22039. this._ownsBuffer = true;
  22040. }
  22041. this._stride = stride;
  22042. this._offset = offset ? offset : 0;
  22043. this._size = size ? size : stride;
  22044. this._kind = kind;
  22045. }
  22046. VertexBuffer.prototype._rebuild = function () {
  22047. if (!this._buffer) {
  22048. return;
  22049. }
  22050. this._buffer._rebuild();
  22051. };
  22052. /**
  22053. * Returns the kind of the VertexBuffer (string).
  22054. */
  22055. VertexBuffer.prototype.getKind = function () {
  22056. return this._kind;
  22057. };
  22058. // Properties
  22059. /**
  22060. * Boolean : is the VertexBuffer updatable ?
  22061. */
  22062. VertexBuffer.prototype.isUpdatable = function () {
  22063. return this._buffer.isUpdatable();
  22064. };
  22065. /**
  22066. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  22067. */
  22068. VertexBuffer.prototype.getData = function () {
  22069. return this._buffer.getData();
  22070. };
  22071. /**
  22072. * Returns the WebGLBuffer associated to the VertexBuffer.
  22073. */
  22074. VertexBuffer.prototype.getBuffer = function () {
  22075. return this._buffer.getBuffer();
  22076. };
  22077. /**
  22078. * Returns the stride of the VertexBuffer (integer).
  22079. */
  22080. VertexBuffer.prototype.getStrideSize = function () {
  22081. return this._stride;
  22082. };
  22083. /**
  22084. * Returns the offset (integer).
  22085. */
  22086. VertexBuffer.prototype.getOffset = function () {
  22087. return this._offset;
  22088. };
  22089. /**
  22090. * Returns the VertexBuffer total size (integer).
  22091. */
  22092. VertexBuffer.prototype.getSize = function () {
  22093. return this._size;
  22094. };
  22095. /**
  22096. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  22097. */
  22098. VertexBuffer.prototype.getIsInstanced = function () {
  22099. return this._buffer.getIsInstanced();
  22100. };
  22101. /**
  22102. * Returns the instancing divisor, zero for non-instanced (integer).
  22103. */
  22104. VertexBuffer.prototype.getInstanceDivisor = function () {
  22105. return this._buffer.instanceDivisor;
  22106. };
  22107. // Methods
  22108. /**
  22109. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  22110. * Returns the created WebGLBuffer.
  22111. */
  22112. VertexBuffer.prototype.create = function (data) {
  22113. return this._buffer.create(data);
  22114. };
  22115. /**
  22116. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  22117. * Returns the updated WebGLBuffer.
  22118. */
  22119. VertexBuffer.prototype.update = function (data) {
  22120. return this._buffer.update(data);
  22121. };
  22122. /**
  22123. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  22124. * Returns the directly updated WebGLBuffer.
  22125. */
  22126. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  22127. return this._buffer.updateDirectly(data, offset);
  22128. };
  22129. /**
  22130. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  22131. */
  22132. VertexBuffer.prototype.dispose = function () {
  22133. if (this._ownsBuffer) {
  22134. this._buffer.dispose();
  22135. }
  22136. };
  22137. Object.defineProperty(VertexBuffer, "PositionKind", {
  22138. get: function () {
  22139. return VertexBuffer._PositionKind;
  22140. },
  22141. enumerable: true,
  22142. configurable: true
  22143. });
  22144. Object.defineProperty(VertexBuffer, "NormalKind", {
  22145. get: function () {
  22146. return VertexBuffer._NormalKind;
  22147. },
  22148. enumerable: true,
  22149. configurable: true
  22150. });
  22151. Object.defineProperty(VertexBuffer, "TangentKind", {
  22152. get: function () {
  22153. return VertexBuffer._TangentKind;
  22154. },
  22155. enumerable: true,
  22156. configurable: true
  22157. });
  22158. Object.defineProperty(VertexBuffer, "UVKind", {
  22159. get: function () {
  22160. return VertexBuffer._UVKind;
  22161. },
  22162. enumerable: true,
  22163. configurable: true
  22164. });
  22165. Object.defineProperty(VertexBuffer, "UV2Kind", {
  22166. get: function () {
  22167. return VertexBuffer._UV2Kind;
  22168. },
  22169. enumerable: true,
  22170. configurable: true
  22171. });
  22172. Object.defineProperty(VertexBuffer, "UV3Kind", {
  22173. get: function () {
  22174. return VertexBuffer._UV3Kind;
  22175. },
  22176. enumerable: true,
  22177. configurable: true
  22178. });
  22179. Object.defineProperty(VertexBuffer, "UV4Kind", {
  22180. get: function () {
  22181. return VertexBuffer._UV4Kind;
  22182. },
  22183. enumerable: true,
  22184. configurable: true
  22185. });
  22186. Object.defineProperty(VertexBuffer, "UV5Kind", {
  22187. get: function () {
  22188. return VertexBuffer._UV5Kind;
  22189. },
  22190. enumerable: true,
  22191. configurable: true
  22192. });
  22193. Object.defineProperty(VertexBuffer, "UV6Kind", {
  22194. get: function () {
  22195. return VertexBuffer._UV6Kind;
  22196. },
  22197. enumerable: true,
  22198. configurable: true
  22199. });
  22200. Object.defineProperty(VertexBuffer, "ColorKind", {
  22201. get: function () {
  22202. return VertexBuffer._ColorKind;
  22203. },
  22204. enumerable: true,
  22205. configurable: true
  22206. });
  22207. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  22208. get: function () {
  22209. return VertexBuffer._MatricesIndicesKind;
  22210. },
  22211. enumerable: true,
  22212. configurable: true
  22213. });
  22214. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  22215. get: function () {
  22216. return VertexBuffer._MatricesWeightsKind;
  22217. },
  22218. enumerable: true,
  22219. configurable: true
  22220. });
  22221. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  22222. get: function () {
  22223. return VertexBuffer._MatricesIndicesExtraKind;
  22224. },
  22225. enumerable: true,
  22226. configurable: true
  22227. });
  22228. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  22229. get: function () {
  22230. return VertexBuffer._MatricesWeightsExtraKind;
  22231. },
  22232. enumerable: true,
  22233. configurable: true
  22234. });
  22235. // Enums
  22236. VertexBuffer._PositionKind = "position";
  22237. VertexBuffer._NormalKind = "normal";
  22238. VertexBuffer._TangentKind = "tangent";
  22239. VertexBuffer._UVKind = "uv";
  22240. VertexBuffer._UV2Kind = "uv2";
  22241. VertexBuffer._UV3Kind = "uv3";
  22242. VertexBuffer._UV4Kind = "uv4";
  22243. VertexBuffer._UV5Kind = "uv5";
  22244. VertexBuffer._UV6Kind = "uv6";
  22245. VertexBuffer._ColorKind = "color";
  22246. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  22247. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  22248. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  22249. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  22250. return VertexBuffer;
  22251. }());
  22252. BABYLON.VertexBuffer = VertexBuffer;
  22253. })(BABYLON || (BABYLON = {}));
  22254. //# sourceMappingURL=babylon.vertexBuffer.js.map
  22255. var BABYLON;
  22256. (function (BABYLON) {
  22257. var InternalTexture = /** @class */ (function () {
  22258. function InternalTexture(engine, dataSource) {
  22259. this.onLoadedObservable = new BABYLON.Observable();
  22260. // Private
  22261. this._initialSlot = -1;
  22262. this._designatedSlot = -1;
  22263. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  22264. this._references = 1;
  22265. this._engine = engine;
  22266. this._dataSource = dataSource;
  22267. this._webGLTexture = engine._createTexture();
  22268. }
  22269. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  22270. get: function () {
  22271. return this._dataSource;
  22272. },
  22273. enumerable: true,
  22274. configurable: true
  22275. });
  22276. InternalTexture.prototype.incrementReferences = function () {
  22277. this._references++;
  22278. };
  22279. InternalTexture.prototype.updateSize = function (width, height, depth) {
  22280. if (depth === void 0) { depth = 1; }
  22281. this.width = width;
  22282. this.height = height;
  22283. this.depth = depth;
  22284. this.baseWidth = width;
  22285. this.baseHeight = height;
  22286. this.baseDepth = depth;
  22287. this._size = width * height * depth;
  22288. };
  22289. InternalTexture.prototype._rebuild = function () {
  22290. var _this = this;
  22291. var proxy;
  22292. this.isReady = false;
  22293. this._cachedCoordinatesMode = null;
  22294. this._cachedWrapU = null;
  22295. this._cachedWrapV = null;
  22296. this._cachedAnisotropicFilteringLevel = null;
  22297. switch (this._dataSource) {
  22298. case InternalTexture.DATASOURCE_TEMP:
  22299. return;
  22300. case InternalTexture.DATASOURCE_URL:
  22301. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  22302. _this.isReady = true;
  22303. }, null, this._buffer, undefined, this.format);
  22304. proxy._swapAndDie(this);
  22305. return;
  22306. case InternalTexture.DATASOURCE_RAW:
  22307. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  22308. proxy._swapAndDie(this);
  22309. this.isReady = true;
  22310. return;
  22311. case InternalTexture.DATASOURCE_RAW3D:
  22312. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  22313. proxy._swapAndDie(this);
  22314. this.isReady = true;
  22315. return;
  22316. case InternalTexture.DATASOURCE_DYNAMIC:
  22317. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  22318. proxy._swapAndDie(this);
  22319. // The engine will make sure to update content so no need to flag it as isReady = true
  22320. return;
  22321. case InternalTexture.DATASOURCE_RENDERTARGET:
  22322. var options = new BABYLON.RenderTargetCreationOptions();
  22323. options.generateDepthBuffer = this._generateDepthBuffer;
  22324. options.generateMipMaps = this.generateMipMaps;
  22325. options.generateStencilBuffer = this._generateStencilBuffer;
  22326. options.samplingMode = this.samplingMode;
  22327. options.type = this.type;
  22328. if (this.isCube) {
  22329. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  22330. }
  22331. else {
  22332. var size = {
  22333. width: this.width,
  22334. height: this.height
  22335. };
  22336. proxy = this._engine.createRenderTargetTexture(size, options);
  22337. }
  22338. proxy._swapAndDie(this);
  22339. this.isReady = true;
  22340. return;
  22341. case InternalTexture.DATASOURCE_CUBE:
  22342. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  22343. _this.isReady = true;
  22344. }, null, this.format, this._extension);
  22345. proxy._swapAndDie(this);
  22346. return;
  22347. case InternalTexture.DATASOURCE_CUBERAW:
  22348. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  22349. proxy._swapAndDie(this);
  22350. this.isReady = true;
  22351. return;
  22352. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  22353. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  22354. if (proxy) {
  22355. proxy._swapAndDie(_this);
  22356. }
  22357. _this.isReady = true;
  22358. }, null, this.format, this._extension);
  22359. return;
  22360. }
  22361. };
  22362. InternalTexture.prototype._swapAndDie = function (target) {
  22363. target._webGLTexture = this._webGLTexture;
  22364. if (this._framebuffer) {
  22365. target._framebuffer = this._framebuffer;
  22366. }
  22367. if (this._depthStencilBuffer) {
  22368. target._depthStencilBuffer = this._depthStencilBuffer;
  22369. }
  22370. if (this._lodTextureHigh) {
  22371. if (target._lodTextureHigh) {
  22372. target._lodTextureHigh.dispose();
  22373. }
  22374. target._lodTextureHigh = this._lodTextureHigh;
  22375. }
  22376. if (this._lodTextureMid) {
  22377. if (target._lodTextureMid) {
  22378. target._lodTextureMid.dispose();
  22379. }
  22380. target._lodTextureMid = this._lodTextureMid;
  22381. }
  22382. if (this._lodTextureLow) {
  22383. if (target._lodTextureLow) {
  22384. target._lodTextureLow.dispose();
  22385. }
  22386. target._lodTextureLow = this._lodTextureLow;
  22387. }
  22388. var cache = this._engine.getLoadedTexturesCache();
  22389. var index = cache.indexOf(this);
  22390. if (index !== -1) {
  22391. cache.splice(index, 1);
  22392. }
  22393. };
  22394. InternalTexture.prototype.dispose = function () {
  22395. if (!this._webGLTexture) {
  22396. return;
  22397. }
  22398. this._references--;
  22399. if (this._references === 0) {
  22400. this._engine._releaseTexture(this);
  22401. this._webGLTexture = null;
  22402. }
  22403. };
  22404. InternalTexture.DATASOURCE_UNKNOWN = 0;
  22405. InternalTexture.DATASOURCE_URL = 1;
  22406. InternalTexture.DATASOURCE_TEMP = 2;
  22407. InternalTexture.DATASOURCE_RAW = 3;
  22408. InternalTexture.DATASOURCE_DYNAMIC = 4;
  22409. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  22410. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  22411. InternalTexture.DATASOURCE_CUBE = 7;
  22412. InternalTexture.DATASOURCE_CUBERAW = 8;
  22413. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  22414. InternalTexture.DATASOURCE_RAW3D = 10;
  22415. return InternalTexture;
  22416. }());
  22417. BABYLON.InternalTexture = InternalTexture;
  22418. })(BABYLON || (BABYLON = {}));
  22419. //# sourceMappingURL=babylon.internalTexture.js.map
  22420. var BABYLON;
  22421. (function (BABYLON) {
  22422. var BaseTexture = /** @class */ (function () {
  22423. function BaseTexture(scene) {
  22424. this._hasAlpha = false;
  22425. this.getAlphaFromRGB = false;
  22426. this.level = 1;
  22427. this.coordinatesIndex = 0;
  22428. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  22429. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  22430. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  22431. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  22432. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  22433. this.isCube = false;
  22434. this.is3D = false;
  22435. this.gammaSpace = true;
  22436. this.invertZ = false;
  22437. this.lodLevelInAlpha = false;
  22438. this.lodGenerationOffset = 0.0;
  22439. this.lodGenerationScale = 0.8;
  22440. this.isRenderTarget = false;
  22441. this.animations = new Array();
  22442. /**
  22443. * An event triggered when the texture is disposed.
  22444. * @type {BABYLON.Observable}
  22445. */
  22446. this.onDisposeObservable = new BABYLON.Observable();
  22447. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22448. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  22449. if (this._scene) {
  22450. this._scene.textures.push(this);
  22451. }
  22452. this._uid = null;
  22453. }
  22454. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  22455. get: function () {
  22456. return this._hasAlpha;
  22457. },
  22458. set: function (value) {
  22459. if (this._hasAlpha === value) {
  22460. return;
  22461. }
  22462. this._hasAlpha = value;
  22463. if (this._scene) {
  22464. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22465. }
  22466. },
  22467. enumerable: true,
  22468. configurable: true
  22469. });
  22470. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  22471. get: function () {
  22472. return this._coordinatesMode;
  22473. },
  22474. set: function (value) {
  22475. if (this._coordinatesMode === value) {
  22476. return;
  22477. }
  22478. this._coordinatesMode = value;
  22479. if (this._scene) {
  22480. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22481. }
  22482. },
  22483. enumerable: true,
  22484. configurable: true
  22485. });
  22486. Object.defineProperty(BaseTexture.prototype, "uid", {
  22487. get: function () {
  22488. if (!this._uid) {
  22489. this._uid = BABYLON.Tools.RandomId();
  22490. }
  22491. return this._uid;
  22492. },
  22493. enumerable: true,
  22494. configurable: true
  22495. });
  22496. BaseTexture.prototype.toString = function () {
  22497. return this.name;
  22498. };
  22499. BaseTexture.prototype.getClassName = function () {
  22500. return "BaseTexture";
  22501. };
  22502. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  22503. set: function (callback) {
  22504. if (this._onDisposeObserver) {
  22505. this.onDisposeObservable.remove(this._onDisposeObserver);
  22506. }
  22507. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22508. },
  22509. enumerable: true,
  22510. configurable: true
  22511. });
  22512. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  22513. get: function () {
  22514. return true;
  22515. },
  22516. enumerable: true,
  22517. configurable: true
  22518. });
  22519. BaseTexture.prototype.getScene = function () {
  22520. return this._scene;
  22521. };
  22522. BaseTexture.prototype.getTextureMatrix = function () {
  22523. return BABYLON.Matrix.IdentityReadOnly;
  22524. };
  22525. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  22526. return BABYLON.Matrix.IdentityReadOnly;
  22527. };
  22528. BaseTexture.prototype.getInternalTexture = function () {
  22529. return this._texture;
  22530. };
  22531. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  22532. return !this.isBlocking || this.isReady();
  22533. };
  22534. BaseTexture.prototype.isReady = function () {
  22535. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22536. this.delayLoad();
  22537. return false;
  22538. }
  22539. if (this._texture) {
  22540. return this._texture.isReady;
  22541. }
  22542. return false;
  22543. };
  22544. BaseTexture.prototype.getSize = function () {
  22545. if (this._texture && this._texture.width) {
  22546. return new BABYLON.Size(this._texture.width, this._texture.height);
  22547. }
  22548. if (this._texture && this._texture._size) {
  22549. return new BABYLON.Size(this._texture._size, this._texture._size);
  22550. }
  22551. return BABYLON.Size.Zero();
  22552. };
  22553. BaseTexture.prototype.getBaseSize = function () {
  22554. if (!this.isReady() || !this._texture)
  22555. return BABYLON.Size.Zero();
  22556. if (this._texture._size) {
  22557. return new BABYLON.Size(this._texture._size, this._texture._size);
  22558. }
  22559. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  22560. };
  22561. BaseTexture.prototype.scale = function (ratio) {
  22562. };
  22563. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  22564. get: function () {
  22565. return false;
  22566. },
  22567. enumerable: true,
  22568. configurable: true
  22569. });
  22570. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  22571. if (!this._scene) {
  22572. return null;
  22573. }
  22574. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22575. for (var index = 0; index < texturesCache.length; index++) {
  22576. var texturesCacheEntry = texturesCache[index];
  22577. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  22578. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  22579. texturesCacheEntry.incrementReferences();
  22580. return texturesCacheEntry;
  22581. }
  22582. }
  22583. }
  22584. return null;
  22585. };
  22586. BaseTexture.prototype._rebuild = function () {
  22587. };
  22588. BaseTexture.prototype.delayLoad = function () {
  22589. };
  22590. BaseTexture.prototype.clone = function () {
  22591. return null;
  22592. };
  22593. Object.defineProperty(BaseTexture.prototype, "textureType", {
  22594. get: function () {
  22595. if (!this._texture) {
  22596. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  22597. }
  22598. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  22599. },
  22600. enumerable: true,
  22601. configurable: true
  22602. });
  22603. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  22604. get: function () {
  22605. if (!this._texture) {
  22606. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  22607. }
  22608. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  22609. },
  22610. enumerable: true,
  22611. configurable: true
  22612. });
  22613. BaseTexture.prototype.readPixels = function (faceIndex) {
  22614. if (faceIndex === void 0) { faceIndex = 0; }
  22615. if (!this._texture) {
  22616. return null;
  22617. }
  22618. var size = this.getSize();
  22619. var scene = this.getScene();
  22620. if (!scene) {
  22621. return null;
  22622. }
  22623. var engine = scene.getEngine();
  22624. if (this._texture.isCube) {
  22625. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  22626. }
  22627. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  22628. };
  22629. BaseTexture.prototype.releaseInternalTexture = function () {
  22630. if (this._texture) {
  22631. this._texture.dispose();
  22632. this._texture = null;
  22633. }
  22634. };
  22635. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  22636. get: function () {
  22637. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  22638. return null;
  22639. }
  22640. if (!this._texture._sphericalPolynomial) {
  22641. this._texture._sphericalPolynomial =
  22642. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  22643. }
  22644. return this._texture._sphericalPolynomial;
  22645. },
  22646. set: function (value) {
  22647. if (this._texture) {
  22648. this._texture._sphericalPolynomial = value;
  22649. }
  22650. },
  22651. enumerable: true,
  22652. configurable: true
  22653. });
  22654. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  22655. get: function () {
  22656. if (this._texture) {
  22657. return this._texture._lodTextureHigh;
  22658. }
  22659. return null;
  22660. },
  22661. enumerable: true,
  22662. configurable: true
  22663. });
  22664. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  22665. get: function () {
  22666. if (this._texture) {
  22667. return this._texture._lodTextureMid;
  22668. }
  22669. return null;
  22670. },
  22671. enumerable: true,
  22672. configurable: true
  22673. });
  22674. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  22675. get: function () {
  22676. if (this._texture) {
  22677. return this._texture._lodTextureLow;
  22678. }
  22679. return null;
  22680. },
  22681. enumerable: true,
  22682. configurable: true
  22683. });
  22684. BaseTexture.prototype.dispose = function () {
  22685. if (!this._scene) {
  22686. return;
  22687. }
  22688. // Animations
  22689. this._scene.stopAnimation(this);
  22690. // Remove from scene
  22691. this._scene._removePendingData(this);
  22692. var index = this._scene.textures.indexOf(this);
  22693. if (index >= 0) {
  22694. this._scene.textures.splice(index, 1);
  22695. }
  22696. if (this._texture === undefined) {
  22697. return;
  22698. }
  22699. // Release
  22700. this.releaseInternalTexture();
  22701. // Callback
  22702. this.onDisposeObservable.notifyObservers(this);
  22703. this.onDisposeObservable.clear();
  22704. };
  22705. BaseTexture.prototype.serialize = function () {
  22706. if (!this.name) {
  22707. return null;
  22708. }
  22709. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22710. // Animations
  22711. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22712. return serializationObject;
  22713. };
  22714. BaseTexture.WhenAllReady = function (textures, callback) {
  22715. var numRemaining = textures.length;
  22716. if (numRemaining === 0) {
  22717. callback();
  22718. return;
  22719. }
  22720. var _loop_1 = function () {
  22721. texture = textures[i];
  22722. if (texture.isReady()) {
  22723. if (--numRemaining === 0) {
  22724. callback();
  22725. }
  22726. }
  22727. else {
  22728. onLoadObservable = texture.onLoadObservable;
  22729. var onLoadCallback_1 = function () {
  22730. onLoadObservable.removeCallback(onLoadCallback_1);
  22731. if (--numRemaining === 0) {
  22732. callback();
  22733. }
  22734. };
  22735. onLoadObservable.add(onLoadCallback_1);
  22736. }
  22737. };
  22738. var texture, onLoadObservable;
  22739. for (var i = 0; i < textures.length; i++) {
  22740. _loop_1();
  22741. }
  22742. };
  22743. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  22744. __decorate([
  22745. BABYLON.serialize()
  22746. ], BaseTexture.prototype, "name", void 0);
  22747. __decorate([
  22748. BABYLON.serialize("hasAlpha")
  22749. ], BaseTexture.prototype, "_hasAlpha", void 0);
  22750. __decorate([
  22751. BABYLON.serialize()
  22752. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  22753. __decorate([
  22754. BABYLON.serialize()
  22755. ], BaseTexture.prototype, "level", void 0);
  22756. __decorate([
  22757. BABYLON.serialize()
  22758. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  22759. __decorate([
  22760. BABYLON.serialize("coordinatesMode")
  22761. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  22762. __decorate([
  22763. BABYLON.serialize()
  22764. ], BaseTexture.prototype, "wrapU", void 0);
  22765. __decorate([
  22766. BABYLON.serialize()
  22767. ], BaseTexture.prototype, "wrapV", void 0);
  22768. __decorate([
  22769. BABYLON.serialize()
  22770. ], BaseTexture.prototype, "wrapR", void 0);
  22771. __decorate([
  22772. BABYLON.serialize()
  22773. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  22774. __decorate([
  22775. BABYLON.serialize()
  22776. ], BaseTexture.prototype, "isCube", void 0);
  22777. __decorate([
  22778. BABYLON.serialize()
  22779. ], BaseTexture.prototype, "is3D", void 0);
  22780. __decorate([
  22781. BABYLON.serialize()
  22782. ], BaseTexture.prototype, "gammaSpace", void 0);
  22783. __decorate([
  22784. BABYLON.serialize()
  22785. ], BaseTexture.prototype, "invertZ", void 0);
  22786. __decorate([
  22787. BABYLON.serialize()
  22788. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  22789. __decorate([
  22790. BABYLON.serialize()
  22791. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  22792. __decorate([
  22793. BABYLON.serialize()
  22794. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  22795. __decorate([
  22796. BABYLON.serialize()
  22797. ], BaseTexture.prototype, "isRenderTarget", void 0);
  22798. return BaseTexture;
  22799. }());
  22800. BABYLON.BaseTexture = BaseTexture;
  22801. })(BABYLON || (BABYLON = {}));
  22802. //# sourceMappingURL=babylon.baseTexture.js.map
  22803. var BABYLON;
  22804. (function (BABYLON) {
  22805. var Texture = /** @class */ (function (_super) {
  22806. __extends(Texture, _super);
  22807. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  22808. if (noMipmap === void 0) { noMipmap = false; }
  22809. if (invertY === void 0) { invertY = true; }
  22810. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22811. if (onLoad === void 0) { onLoad = null; }
  22812. if (onError === void 0) { onError = null; }
  22813. if (buffer === void 0) { buffer = null; }
  22814. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22815. var _this = _super.call(this, scene) || this;
  22816. _this.uOffset = 0;
  22817. _this.vOffset = 0;
  22818. _this.uScale = 1.0;
  22819. _this.vScale = 1.0;
  22820. _this.uAng = 0;
  22821. _this.vAng = 0;
  22822. _this.wAng = 0;
  22823. _this._isBlocking = true;
  22824. _this.name = url || "";
  22825. _this.url = url;
  22826. _this._noMipmap = noMipmap;
  22827. _this._invertY = invertY;
  22828. _this._samplingMode = samplingMode;
  22829. _this._buffer = buffer;
  22830. _this._deleteBuffer = deleteBuffer;
  22831. if (format) {
  22832. _this._format = format;
  22833. }
  22834. scene = _this.getScene();
  22835. if (!scene) {
  22836. return _this;
  22837. }
  22838. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  22839. var load = function () {
  22840. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  22841. _this.onLoadObservable.notifyObservers(_this);
  22842. }
  22843. if (onLoad) {
  22844. onLoad();
  22845. }
  22846. if (!_this.isBlocking && scene) {
  22847. scene.resetCachedMaterial();
  22848. }
  22849. };
  22850. if (!_this.url) {
  22851. _this._delayedOnLoad = load;
  22852. _this._delayedOnError = onError;
  22853. return _this;
  22854. }
  22855. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  22856. if (!_this._texture) {
  22857. if (!scene.useDelayedTextureLoading) {
  22858. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  22859. if (deleteBuffer) {
  22860. delete _this._buffer;
  22861. }
  22862. }
  22863. else {
  22864. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22865. _this._delayedOnLoad = load;
  22866. _this._delayedOnError = onError;
  22867. }
  22868. }
  22869. else {
  22870. if (_this._texture.isReady) {
  22871. BABYLON.Tools.SetImmediate(function () { return load(); });
  22872. }
  22873. else {
  22874. _this._texture.onLoadedObservable.add(load);
  22875. }
  22876. }
  22877. return _this;
  22878. }
  22879. Object.defineProperty(Texture.prototype, "noMipmap", {
  22880. get: function () {
  22881. return this._noMipmap;
  22882. },
  22883. enumerable: true,
  22884. configurable: true
  22885. });
  22886. Object.defineProperty(Texture.prototype, "isBlocking", {
  22887. get: function () {
  22888. return this._isBlocking;
  22889. },
  22890. set: function (value) {
  22891. this._isBlocking = value;
  22892. },
  22893. enumerable: true,
  22894. configurable: true
  22895. });
  22896. Object.defineProperty(Texture.prototype, "samplingMode", {
  22897. get: function () {
  22898. return this._samplingMode;
  22899. },
  22900. enumerable: true,
  22901. configurable: true
  22902. });
  22903. Texture.prototype.updateURL = function (url) {
  22904. this.url = url;
  22905. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22906. this.delayLoad();
  22907. };
  22908. Texture.prototype.delayLoad = function () {
  22909. var _this = this;
  22910. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22911. return;
  22912. }
  22913. var scene = this.getScene();
  22914. if (!scene) {
  22915. return;
  22916. }
  22917. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22918. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  22919. if (!this._texture) {
  22920. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  22921. if (this._deleteBuffer) {
  22922. delete this._buffer;
  22923. }
  22924. }
  22925. else {
  22926. if (this._texture.isReady) {
  22927. BABYLON.Tools.SetImmediate(function () {
  22928. if (!_this._delayedOnLoad) {
  22929. return;
  22930. }
  22931. _this._delayedOnLoad();
  22932. });
  22933. }
  22934. else {
  22935. if (this._delayedOnLoad) {
  22936. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  22937. }
  22938. }
  22939. }
  22940. };
  22941. Texture.prototype.updateSamplingMode = function (samplingMode) {
  22942. if (!this._texture) {
  22943. return;
  22944. }
  22945. var scene = this.getScene();
  22946. if (!scene) {
  22947. return;
  22948. }
  22949. this._samplingMode = samplingMode;
  22950. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  22951. };
  22952. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  22953. x *= this.uScale;
  22954. y *= this.vScale;
  22955. x -= 0.5 * this.uScale;
  22956. y -= 0.5 * this.vScale;
  22957. z -= 0.5;
  22958. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  22959. t.x += 0.5 * this.uScale + this.uOffset;
  22960. t.y += 0.5 * this.vScale + this.vOffset;
  22961. t.z += 0.5;
  22962. };
  22963. Texture.prototype.getTextureMatrix = function () {
  22964. var _this = this;
  22965. if (this.uOffset === this._cachedUOffset &&
  22966. this.vOffset === this._cachedVOffset &&
  22967. this.uScale === this._cachedUScale &&
  22968. this.vScale === this._cachedVScale &&
  22969. this.uAng === this._cachedUAng &&
  22970. this.vAng === this._cachedVAng &&
  22971. this.wAng === this._cachedWAng) {
  22972. return this._cachedTextureMatrix;
  22973. }
  22974. this._cachedUOffset = this.uOffset;
  22975. this._cachedVOffset = this.vOffset;
  22976. this._cachedUScale = this.uScale;
  22977. this._cachedVScale = this.vScale;
  22978. this._cachedUAng = this.uAng;
  22979. this._cachedVAng = this.vAng;
  22980. this._cachedWAng = this.wAng;
  22981. if (!this._cachedTextureMatrix) {
  22982. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22983. this._rowGenerationMatrix = new BABYLON.Matrix();
  22984. this._t0 = BABYLON.Vector3.Zero();
  22985. this._t1 = BABYLON.Vector3.Zero();
  22986. this._t2 = BABYLON.Vector3.Zero();
  22987. }
  22988. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  22989. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  22990. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  22991. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  22992. this._t1.subtractInPlace(this._t0);
  22993. this._t2.subtractInPlace(this._t0);
  22994. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22995. this._cachedTextureMatrix.m[0] = this._t1.x;
  22996. this._cachedTextureMatrix.m[1] = this._t1.y;
  22997. this._cachedTextureMatrix.m[2] = this._t1.z;
  22998. this._cachedTextureMatrix.m[4] = this._t2.x;
  22999. this._cachedTextureMatrix.m[5] = this._t2.y;
  23000. this._cachedTextureMatrix.m[6] = this._t2.z;
  23001. this._cachedTextureMatrix.m[8] = this._t0.x;
  23002. this._cachedTextureMatrix.m[9] = this._t0.y;
  23003. this._cachedTextureMatrix.m[10] = this._t0.z;
  23004. var scene = this.getScene();
  23005. if (!scene) {
  23006. return this._cachedTextureMatrix;
  23007. }
  23008. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  23009. return mat.hasTexture(_this);
  23010. });
  23011. return this._cachedTextureMatrix;
  23012. };
  23013. Texture.prototype.getReflectionTextureMatrix = function () {
  23014. var _this = this;
  23015. var scene = this.getScene();
  23016. if (!scene) {
  23017. return this._cachedTextureMatrix;
  23018. }
  23019. if (this.uOffset === this._cachedUOffset &&
  23020. this.vOffset === this._cachedVOffset &&
  23021. this.uScale === this._cachedUScale &&
  23022. this.vScale === this._cachedVScale &&
  23023. this.coordinatesMode === this._cachedCoordinatesMode) {
  23024. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  23025. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  23026. return this._cachedTextureMatrix;
  23027. }
  23028. }
  23029. else {
  23030. return this._cachedTextureMatrix;
  23031. }
  23032. }
  23033. if (!this._cachedTextureMatrix) {
  23034. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  23035. }
  23036. if (!this._projectionModeMatrix) {
  23037. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  23038. }
  23039. this._cachedUOffset = this.uOffset;
  23040. this._cachedVOffset = this.vOffset;
  23041. this._cachedUScale = this.uScale;
  23042. this._cachedVScale = this.vScale;
  23043. this._cachedCoordinatesMode = this.coordinatesMode;
  23044. switch (this.coordinatesMode) {
  23045. case Texture.PLANAR_MODE:
  23046. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23047. this._cachedTextureMatrix[0] = this.uScale;
  23048. this._cachedTextureMatrix[5] = this.vScale;
  23049. this._cachedTextureMatrix[12] = this.uOffset;
  23050. this._cachedTextureMatrix[13] = this.vOffset;
  23051. break;
  23052. case Texture.PROJECTION_MODE:
  23053. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  23054. this._projectionModeMatrix.m[0] = 0.5;
  23055. this._projectionModeMatrix.m[5] = -0.5;
  23056. this._projectionModeMatrix.m[10] = 0.0;
  23057. this._projectionModeMatrix.m[12] = 0.5;
  23058. this._projectionModeMatrix.m[13] = 0.5;
  23059. this._projectionModeMatrix.m[14] = 1.0;
  23060. this._projectionModeMatrix.m[15] = 1.0;
  23061. var projectionMatrix = scene.getProjectionMatrix();
  23062. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  23063. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  23064. break;
  23065. default:
  23066. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23067. break;
  23068. }
  23069. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  23070. return (mat.getActiveTextures().indexOf(_this) !== -1);
  23071. });
  23072. return this._cachedTextureMatrix;
  23073. };
  23074. Texture.prototype.clone = function () {
  23075. var _this = this;
  23076. return BABYLON.SerializationHelper.Clone(function () {
  23077. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  23078. }, this);
  23079. };
  23080. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  23081. get: function () {
  23082. if (!this._onLoadObservable) {
  23083. this._onLoadObservable = new BABYLON.Observable();
  23084. }
  23085. return this._onLoadObservable;
  23086. },
  23087. enumerable: true,
  23088. configurable: true
  23089. });
  23090. Texture.prototype.serialize = function () {
  23091. var serializationObject = _super.prototype.serialize.call(this);
  23092. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  23093. serializationObject.base64String = this._buffer;
  23094. serializationObject.name = serializationObject.name.replace("data:", "");
  23095. }
  23096. return serializationObject;
  23097. };
  23098. Texture.prototype.getClassName = function () {
  23099. return "Texture";
  23100. };
  23101. Texture.prototype.dispose = function () {
  23102. _super.prototype.dispose.call(this);
  23103. if (this.onLoadObservable) {
  23104. this.onLoadObservable.clear();
  23105. this._onLoadObservable = null;
  23106. }
  23107. this._delayedOnLoad = null;
  23108. this._delayedOnError = null;
  23109. };
  23110. // Statics
  23111. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  23112. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23113. if (onLoad === void 0) { onLoad = null; }
  23114. if (onError === void 0) { onError = null; }
  23115. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  23116. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  23117. };
  23118. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  23119. if (parsedTexture.customType) {
  23120. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  23121. // Update Sampling Mode
  23122. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  23123. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  23124. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  23125. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  23126. }
  23127. }
  23128. return parsedCustomTexture;
  23129. }
  23130. if (parsedTexture.isCube) {
  23131. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  23132. }
  23133. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  23134. return null;
  23135. }
  23136. var texture = BABYLON.SerializationHelper.Parse(function () {
  23137. var generateMipMaps = true;
  23138. if (parsedTexture.noMipmap) {
  23139. generateMipMaps = false;
  23140. }
  23141. if (parsedTexture.mirrorPlane) {
  23142. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  23143. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  23144. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  23145. return mirrorTexture;
  23146. }
  23147. else if (parsedTexture.isRenderTarget) {
  23148. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  23149. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  23150. return renderTargetTexture;
  23151. }
  23152. else {
  23153. var texture;
  23154. if (parsedTexture.base64String) {
  23155. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  23156. }
  23157. else {
  23158. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  23159. }
  23160. return texture;
  23161. }
  23162. }, parsedTexture, scene);
  23163. // Update Sampling Mode
  23164. if (parsedTexture.samplingMode) {
  23165. var sampling = parsedTexture.samplingMode;
  23166. if (texture._samplingMode !== sampling) {
  23167. texture.updateSamplingMode(sampling);
  23168. }
  23169. }
  23170. // Animations
  23171. if (parsedTexture.animations) {
  23172. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  23173. var parsedAnimation = parsedTexture.animations[animationIndex];
  23174. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23175. }
  23176. }
  23177. return texture;
  23178. };
  23179. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  23180. if (deleteBuffer === void 0) { deleteBuffer = false; }
  23181. if (noMipmap === void 0) { noMipmap = false; }
  23182. if (invertY === void 0) { invertY = true; }
  23183. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23184. if (onLoad === void 0) { onLoad = null; }
  23185. if (onError === void 0) { onError = null; }
  23186. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  23187. if (name.substr(0, 5) !== "data:") {
  23188. name = "data:" + name;
  23189. }
  23190. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  23191. };
  23192. // Constants
  23193. Texture.NEAREST_SAMPLINGMODE = 1;
  23194. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  23195. Texture.BILINEAR_SAMPLINGMODE = 2;
  23196. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  23197. Texture.TRILINEAR_SAMPLINGMODE = 3;
  23198. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  23199. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  23200. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  23201. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  23202. Texture.NEAREST_LINEAR = 7;
  23203. Texture.NEAREST_NEAREST = 8;
  23204. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  23205. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  23206. Texture.LINEAR_LINEAR = 11;
  23207. Texture.LINEAR_NEAREST = 12;
  23208. Texture.EXPLICIT_MODE = 0;
  23209. Texture.SPHERICAL_MODE = 1;
  23210. Texture.PLANAR_MODE = 2;
  23211. Texture.CUBIC_MODE = 3;
  23212. Texture.PROJECTION_MODE = 4;
  23213. Texture.SKYBOX_MODE = 5;
  23214. Texture.INVCUBIC_MODE = 6;
  23215. Texture.EQUIRECTANGULAR_MODE = 7;
  23216. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  23217. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  23218. Texture.CLAMP_ADDRESSMODE = 0;
  23219. Texture.WRAP_ADDRESSMODE = 1;
  23220. Texture.MIRROR_ADDRESSMODE = 2;
  23221. __decorate([
  23222. BABYLON.serialize()
  23223. ], Texture.prototype, "url", void 0);
  23224. __decorate([
  23225. BABYLON.serialize()
  23226. ], Texture.prototype, "uOffset", void 0);
  23227. __decorate([
  23228. BABYLON.serialize()
  23229. ], Texture.prototype, "vOffset", void 0);
  23230. __decorate([
  23231. BABYLON.serialize()
  23232. ], Texture.prototype, "uScale", void 0);
  23233. __decorate([
  23234. BABYLON.serialize()
  23235. ], Texture.prototype, "vScale", void 0);
  23236. __decorate([
  23237. BABYLON.serialize()
  23238. ], Texture.prototype, "uAng", void 0);
  23239. __decorate([
  23240. BABYLON.serialize()
  23241. ], Texture.prototype, "vAng", void 0);
  23242. __decorate([
  23243. BABYLON.serialize()
  23244. ], Texture.prototype, "wAng", void 0);
  23245. __decorate([
  23246. BABYLON.serialize()
  23247. ], Texture.prototype, "isBlocking", null);
  23248. return Texture;
  23249. }(BABYLON.BaseTexture));
  23250. BABYLON.Texture = Texture;
  23251. })(BABYLON || (BABYLON = {}));
  23252. //# sourceMappingURL=babylon.texture.js.map
  23253. var BABYLON;
  23254. (function (BABYLON) {
  23255. var _InstancesBatch = /** @class */ (function () {
  23256. function _InstancesBatch() {
  23257. this.mustReturn = false;
  23258. this.visibleInstances = new Array();
  23259. this.renderSelf = new Array();
  23260. }
  23261. return _InstancesBatch;
  23262. }());
  23263. BABYLON._InstancesBatch = _InstancesBatch;
  23264. var Mesh = /** @class */ (function (_super) {
  23265. __extends(Mesh, _super);
  23266. /**
  23267. * @constructor
  23268. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  23269. * @param {Scene} scene The scene to add this mesh to.
  23270. * @param {Node} parent The parent of this mesh, if it has one
  23271. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  23272. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  23273. * When false, achieved by calling a clone(), also passing False.
  23274. * This will make creation of children, recursive.
  23275. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  23276. */
  23277. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  23278. if (scene === void 0) { scene = null; }
  23279. if (parent === void 0) { parent = null; }
  23280. if (source === void 0) { source = null; }
  23281. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  23282. var _this = _super.call(this, name, scene) || this;
  23283. // Events
  23284. /**
  23285. * An event triggered before rendering the mesh
  23286. * @type {BABYLON.Observable}
  23287. */
  23288. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23289. /**
  23290. * An event triggered after rendering the mesh
  23291. * @type {BABYLON.Observable}
  23292. */
  23293. _this.onAfterRenderObservable = new BABYLON.Observable();
  23294. /**
  23295. * An event triggered before drawing the mesh
  23296. * @type {BABYLON.Observable}
  23297. */
  23298. _this.onBeforeDrawObservable = new BABYLON.Observable();
  23299. // Members
  23300. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23301. _this.instances = new Array();
  23302. _this._LODLevels = new Array();
  23303. _this._visibleInstances = {};
  23304. _this._renderIdForInstances = new Array();
  23305. _this._batchCache = new _InstancesBatch();
  23306. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  23307. // Use by builder only to know what orientation were the mesh build in.
  23308. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  23309. _this.overrideMaterialSideOrientation = null;
  23310. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  23311. // Will be used to save a source mesh reference, If any
  23312. _this._source = null;
  23313. scene = _this.getScene();
  23314. if (source) {
  23315. // Source mesh
  23316. _this._source = source;
  23317. // Geometry
  23318. if (source._geometry) {
  23319. source._geometry.applyToMesh(_this);
  23320. }
  23321. // Deep copy
  23322. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source"], ["_poseMatrix", "_source"]);
  23323. // Tags
  23324. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  23325. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  23326. }
  23327. _this.metadata = source.metadata;
  23328. // Parent
  23329. _this.parent = source.parent;
  23330. // Pivot
  23331. _this.setPivotMatrix(source.getPivotMatrix());
  23332. _this.id = name + "." + source.id;
  23333. // Material
  23334. _this.material = source.material;
  23335. var index;
  23336. if (!doNotCloneChildren) {
  23337. // Children
  23338. var directDescendants = source.getDescendants(true);
  23339. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  23340. var child = directDescendants[index_1];
  23341. if (child.clone) {
  23342. child.clone(name + "." + child.name, _this);
  23343. }
  23344. }
  23345. }
  23346. // Physics clone
  23347. var physicsEngine = _this.getScene().getPhysicsEngine();
  23348. if (clonePhysicsImpostor && physicsEngine) {
  23349. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  23350. if (impostor) {
  23351. _this.physicsImpostor = impostor.clone(_this);
  23352. }
  23353. }
  23354. // Particles
  23355. for (index = 0; index < scene.particleSystems.length; index++) {
  23356. var system = scene.particleSystems[index];
  23357. if (system.emitter === source) {
  23358. system.clone(system.name, _this);
  23359. }
  23360. }
  23361. _this.computeWorldMatrix(true);
  23362. }
  23363. // Parent
  23364. if (parent !== null) {
  23365. _this.parent = parent;
  23366. }
  23367. return _this;
  23368. }
  23369. Object.defineProperty(Mesh, "FRONTSIDE", {
  23370. /**
  23371. * Mesh side orientation : usually the external or front surface
  23372. */
  23373. get: function () {
  23374. return Mesh._FRONTSIDE;
  23375. },
  23376. enumerable: true,
  23377. configurable: true
  23378. });
  23379. Object.defineProperty(Mesh, "BACKSIDE", {
  23380. /**
  23381. * Mesh side orientation : usually the internal or back surface
  23382. */
  23383. get: function () {
  23384. return Mesh._BACKSIDE;
  23385. },
  23386. enumerable: true,
  23387. configurable: true
  23388. });
  23389. Object.defineProperty(Mesh, "DOUBLESIDE", {
  23390. /**
  23391. * Mesh side orientation : both internal and external or front and back surfaces
  23392. */
  23393. get: function () {
  23394. return Mesh._DOUBLESIDE;
  23395. },
  23396. enumerable: true,
  23397. configurable: true
  23398. });
  23399. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  23400. /**
  23401. * Mesh side orientation : by default, `FRONTSIDE`
  23402. */
  23403. get: function () {
  23404. return Mesh._DEFAULTSIDE;
  23405. },
  23406. enumerable: true,
  23407. configurable: true
  23408. });
  23409. Object.defineProperty(Mesh, "NO_CAP", {
  23410. /**
  23411. * Mesh cap setting : no cap
  23412. */
  23413. get: function () {
  23414. return Mesh._NO_CAP;
  23415. },
  23416. enumerable: true,
  23417. configurable: true
  23418. });
  23419. Object.defineProperty(Mesh, "CAP_START", {
  23420. /**
  23421. * Mesh cap setting : one cap at the beginning of the mesh
  23422. */
  23423. get: function () {
  23424. return Mesh._CAP_START;
  23425. },
  23426. enumerable: true,
  23427. configurable: true
  23428. });
  23429. Object.defineProperty(Mesh, "CAP_END", {
  23430. /**
  23431. * Mesh cap setting : one cap at the end of the mesh
  23432. */
  23433. get: function () {
  23434. return Mesh._CAP_END;
  23435. },
  23436. enumerable: true,
  23437. configurable: true
  23438. });
  23439. Object.defineProperty(Mesh, "CAP_ALL", {
  23440. /**
  23441. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  23442. */
  23443. get: function () {
  23444. return Mesh._CAP_ALL;
  23445. },
  23446. enumerable: true,
  23447. configurable: true
  23448. });
  23449. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  23450. set: function (callback) {
  23451. if (this._onBeforeDrawObserver) {
  23452. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  23453. }
  23454. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  23455. },
  23456. enumerable: true,
  23457. configurable: true
  23458. });
  23459. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  23460. get: function () {
  23461. return this._morphTargetManager;
  23462. },
  23463. set: function (value) {
  23464. if (this._morphTargetManager === value) {
  23465. return;
  23466. }
  23467. this._morphTargetManager = value;
  23468. this._syncGeometryWithMorphTargetManager();
  23469. },
  23470. enumerable: true,
  23471. configurable: true
  23472. });
  23473. Object.defineProperty(Mesh.prototype, "source", {
  23474. get: function () {
  23475. return this._source;
  23476. },
  23477. enumerable: true,
  23478. configurable: true
  23479. });
  23480. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  23481. get: function () {
  23482. return this._unIndexed;
  23483. },
  23484. set: function (value) {
  23485. if (this._unIndexed !== value) {
  23486. this._unIndexed = value;
  23487. this._markSubMeshesAsAttributesDirty();
  23488. }
  23489. },
  23490. enumerable: true,
  23491. configurable: true
  23492. });
  23493. // Methods
  23494. /**
  23495. * Returns the string "Mesh".
  23496. */
  23497. Mesh.prototype.getClassName = function () {
  23498. return "Mesh";
  23499. };
  23500. /**
  23501. * Returns a string.
  23502. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23503. */
  23504. Mesh.prototype.toString = function (fullDetails) {
  23505. var ret = _super.prototype.toString.call(this, fullDetails);
  23506. ret += ", n vertices: " + this.getTotalVertices();
  23507. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  23508. if (this.animations) {
  23509. for (var i = 0; i < this.animations.length; i++) {
  23510. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23511. }
  23512. }
  23513. if (fullDetails) {
  23514. if (this._geometry) {
  23515. var ib = this.getIndices();
  23516. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23517. if (vb && ib) {
  23518. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  23519. }
  23520. }
  23521. else {
  23522. ret += ", flat shading: UNKNOWN";
  23523. }
  23524. }
  23525. return ret;
  23526. };
  23527. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  23528. /**
  23529. * True if the mesh has some Levels Of Details (LOD).
  23530. * Returns a boolean.
  23531. */
  23532. get: function () {
  23533. return this._LODLevels.length > 0;
  23534. },
  23535. enumerable: true,
  23536. configurable: true
  23537. });
  23538. Mesh.prototype._sortLODLevels = function () {
  23539. this._LODLevels.sort(function (a, b) {
  23540. if (a.distance < b.distance) {
  23541. return 1;
  23542. }
  23543. if (a.distance > b.distance) {
  23544. return -1;
  23545. }
  23546. return 0;
  23547. });
  23548. };
  23549. /**
  23550. * Add a mesh as LOD level triggered at the given distance.
  23551. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23552. * @param {number} distance The distance from the center of the object to show this level
  23553. * @param {Mesh} mesh The mesh to be added as LOD level
  23554. * @return {Mesh} This mesh (for chaining)
  23555. */
  23556. Mesh.prototype.addLODLevel = function (distance, mesh) {
  23557. if (mesh && mesh._masterMesh) {
  23558. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  23559. return this;
  23560. }
  23561. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  23562. this._LODLevels.push(level);
  23563. if (mesh) {
  23564. mesh._masterMesh = this;
  23565. }
  23566. this._sortLODLevels();
  23567. return this;
  23568. };
  23569. /**
  23570. * Returns the LOD level mesh at the passed distance or null if not found.
  23571. * It is related to the method `addLODLevel(distance, mesh)`.
  23572. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23573. * Returns an object Mesh or `null`.
  23574. */
  23575. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  23576. for (var index = 0; index < this._LODLevels.length; index++) {
  23577. var level = this._LODLevels[index];
  23578. if (level.distance === distance) {
  23579. return level.mesh;
  23580. }
  23581. }
  23582. return null;
  23583. };
  23584. /**
  23585. * Remove a mesh from the LOD array
  23586. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23587. * @param {Mesh} mesh The mesh to be removed.
  23588. * @return {Mesh} This mesh (for chaining)
  23589. */
  23590. Mesh.prototype.removeLODLevel = function (mesh) {
  23591. for (var index = 0; index < this._LODLevels.length; index++) {
  23592. if (this._LODLevels[index].mesh === mesh) {
  23593. this._LODLevels.splice(index, 1);
  23594. if (mesh) {
  23595. mesh._masterMesh = null;
  23596. }
  23597. }
  23598. }
  23599. this._sortLODLevels();
  23600. return this;
  23601. };
  23602. /**
  23603. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  23604. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23605. */
  23606. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  23607. if (!this._LODLevels || this._LODLevels.length === 0) {
  23608. return this;
  23609. }
  23610. var bSphere;
  23611. if (boundingSphere) {
  23612. bSphere = boundingSphere;
  23613. }
  23614. else {
  23615. var boundingInfo = this.getBoundingInfo();
  23616. bSphere = boundingInfo.boundingSphere;
  23617. }
  23618. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  23619. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  23620. if (this.onLODLevelSelection) {
  23621. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  23622. }
  23623. return this;
  23624. }
  23625. for (var index = 0; index < this._LODLevels.length; index++) {
  23626. var level = this._LODLevels[index];
  23627. if (level.distance < distanceToCamera) {
  23628. if (level.mesh) {
  23629. level.mesh._preActivate();
  23630. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  23631. }
  23632. if (this.onLODLevelSelection) {
  23633. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  23634. }
  23635. return level.mesh;
  23636. }
  23637. }
  23638. if (this.onLODLevelSelection) {
  23639. this.onLODLevelSelection(distanceToCamera, this, this);
  23640. }
  23641. return this;
  23642. };
  23643. Object.defineProperty(Mesh.prototype, "geometry", {
  23644. /**
  23645. * Returns the mesh internal Geometry object.
  23646. */
  23647. get: function () {
  23648. return this._geometry;
  23649. },
  23650. enumerable: true,
  23651. configurable: true
  23652. });
  23653. /**
  23654. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  23655. */
  23656. Mesh.prototype.getTotalVertices = function () {
  23657. if (!this._geometry) {
  23658. return 0;
  23659. }
  23660. return this._geometry.getTotalVertices();
  23661. };
  23662. /**
  23663. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  23664. * 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.
  23665. * You can force the copy with forceCopy === true
  23666. * Returns null if the mesh has no geometry or no vertex buffer.
  23667. * Possible `kind` values :
  23668. * - BABYLON.VertexBuffer.PositionKind
  23669. * - BABYLON.VertexBuffer.UVKind
  23670. * - BABYLON.VertexBuffer.UV2Kind
  23671. * - BABYLON.VertexBuffer.UV3Kind
  23672. * - BABYLON.VertexBuffer.UV4Kind
  23673. * - BABYLON.VertexBuffer.UV5Kind
  23674. * - BABYLON.VertexBuffer.UV6Kind
  23675. * - BABYLON.VertexBuffer.ColorKind
  23676. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23677. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23678. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23679. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23680. */
  23681. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  23682. if (!this._geometry) {
  23683. return null;
  23684. }
  23685. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  23686. };
  23687. /**
  23688. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  23689. * Returns `null` if the mesh has no geometry.
  23690. * Possible `kind` values :
  23691. * - BABYLON.VertexBuffer.PositionKind
  23692. * - BABYLON.VertexBuffer.UVKind
  23693. * - BABYLON.VertexBuffer.UV2Kind
  23694. * - BABYLON.VertexBuffer.UV3Kind
  23695. * - BABYLON.VertexBuffer.UV4Kind
  23696. * - BABYLON.VertexBuffer.UV5Kind
  23697. * - BABYLON.VertexBuffer.UV6Kind
  23698. * - BABYLON.VertexBuffer.ColorKind
  23699. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23700. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23701. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23702. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23703. */
  23704. Mesh.prototype.getVertexBuffer = function (kind) {
  23705. if (!this._geometry) {
  23706. return null;
  23707. }
  23708. return this._geometry.getVertexBuffer(kind);
  23709. };
  23710. /**
  23711. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  23712. * Possible `kind` values :
  23713. * - BABYLON.VertexBuffer.PositionKind
  23714. * - BABYLON.VertexBuffer.UVKind
  23715. * - BABYLON.VertexBuffer.UV2Kind
  23716. * - BABYLON.VertexBuffer.UV3Kind
  23717. * - BABYLON.VertexBuffer.UV4Kind
  23718. * - BABYLON.VertexBuffer.UV5Kind
  23719. * - BABYLON.VertexBuffer.UV6Kind
  23720. * - BABYLON.VertexBuffer.ColorKind
  23721. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23722. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23723. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23724. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23725. */
  23726. Mesh.prototype.isVerticesDataPresent = function (kind) {
  23727. if (!this._geometry) {
  23728. if (this._delayInfo) {
  23729. return this._delayInfo.indexOf(kind) !== -1;
  23730. }
  23731. return false;
  23732. }
  23733. return this._geometry.isVerticesDataPresent(kind);
  23734. };
  23735. /**
  23736. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  23737. * Possible `kind` values :
  23738. * - BABYLON.VertexBuffer.PositionKind
  23739. * - BABYLON.VertexBuffer.UVKind
  23740. * - BABYLON.VertexBuffer.UV2Kind
  23741. * - BABYLON.VertexBuffer.UV3Kind
  23742. * - BABYLON.VertexBuffer.UV4Kind
  23743. * - BABYLON.VertexBuffer.UV5Kind
  23744. * - BABYLON.VertexBuffer.UV6Kind
  23745. * - BABYLON.VertexBuffer.ColorKind
  23746. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23747. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23748. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23749. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23750. */
  23751. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  23752. if (!this._geometry) {
  23753. if (this._delayInfo) {
  23754. return this._delayInfo.indexOf(kind) !== -1;
  23755. }
  23756. return false;
  23757. }
  23758. return this._geometry.isVertexBufferUpdatable(kind);
  23759. };
  23760. /**
  23761. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  23762. * Possible `kind` values :
  23763. * - BABYLON.VertexBuffer.PositionKind
  23764. * - BABYLON.VertexBuffer.UVKind
  23765. * - BABYLON.VertexBuffer.UV2Kind
  23766. * - BABYLON.VertexBuffer.UV3Kind
  23767. * - BABYLON.VertexBuffer.UV4Kind
  23768. * - BABYLON.VertexBuffer.UV5Kind
  23769. * - BABYLON.VertexBuffer.UV6Kind
  23770. * - BABYLON.VertexBuffer.ColorKind
  23771. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23772. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23773. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23774. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23775. */
  23776. Mesh.prototype.getVerticesDataKinds = function () {
  23777. if (!this._geometry) {
  23778. var result = new Array();
  23779. if (this._delayInfo) {
  23780. this._delayInfo.forEach(function (kind, index, array) {
  23781. result.push(kind);
  23782. });
  23783. }
  23784. return result;
  23785. }
  23786. return this._geometry.getVerticesDataKinds();
  23787. };
  23788. /**
  23789. * Returns a positive integer : the total number of indices in this mesh geometry.
  23790. * Returns zero if the mesh has no geometry.
  23791. */
  23792. Mesh.prototype.getTotalIndices = function () {
  23793. if (!this._geometry) {
  23794. return 0;
  23795. }
  23796. return this._geometry.getTotalIndices();
  23797. };
  23798. /**
  23799. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  23800. * 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.
  23801. * Returns an empty array if the mesh has no geometry.
  23802. */
  23803. Mesh.prototype.getIndices = function (copyWhenShared) {
  23804. if (!this._geometry) {
  23805. return [];
  23806. }
  23807. return this._geometry.getIndices(copyWhenShared);
  23808. };
  23809. Object.defineProperty(Mesh.prototype, "isBlocked", {
  23810. get: function () {
  23811. return this._masterMesh !== null && this._masterMesh !== undefined;
  23812. },
  23813. enumerable: true,
  23814. configurable: true
  23815. });
  23816. /**
  23817. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  23818. */
  23819. Mesh.prototype.isReady = function () {
  23820. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23821. return false;
  23822. }
  23823. return _super.prototype.isReady.call(this);
  23824. };
  23825. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  23826. /**
  23827. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  23828. * This property is pertinent only for updatable parametric shapes.
  23829. */
  23830. get: function () {
  23831. return this._areNormalsFrozen;
  23832. },
  23833. enumerable: true,
  23834. configurable: true
  23835. });
  23836. /**
  23837. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23838. * It has no effect at all on other shapes.
  23839. * It prevents the mesh normals from being recomputed on next `positions` array update.
  23840. * Returns the Mesh.
  23841. */
  23842. Mesh.prototype.freezeNormals = function () {
  23843. this._areNormalsFrozen = true;
  23844. return this;
  23845. };
  23846. /**
  23847. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23848. * It has no effect at all on other shapes.
  23849. * It reactivates the mesh normals computation if it was previously frozen.
  23850. * Returns the Mesh.
  23851. */
  23852. Mesh.prototype.unfreezeNormals = function () {
  23853. this._areNormalsFrozen = false;
  23854. return this;
  23855. };
  23856. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  23857. /**
  23858. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  23859. */
  23860. set: function (count) {
  23861. this._overridenInstanceCount = count;
  23862. },
  23863. enumerable: true,
  23864. configurable: true
  23865. });
  23866. // Methods
  23867. Mesh.prototype._preActivate = function () {
  23868. var sceneRenderId = this.getScene().getRenderId();
  23869. if (this._preActivateId === sceneRenderId) {
  23870. return this;
  23871. }
  23872. this._preActivateId = sceneRenderId;
  23873. this._visibleInstances = null;
  23874. return this;
  23875. };
  23876. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  23877. if (this._visibleInstances) {
  23878. this._visibleInstances.intermediateDefaultRenderId = renderId;
  23879. }
  23880. return this;
  23881. };
  23882. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  23883. if (!this._visibleInstances) {
  23884. this._visibleInstances = {};
  23885. this._visibleInstances.defaultRenderId = renderId;
  23886. this._visibleInstances.selfDefaultRenderId = this._renderId;
  23887. }
  23888. if (!this._visibleInstances[renderId]) {
  23889. this._visibleInstances[renderId] = new Array();
  23890. }
  23891. this._visibleInstances[renderId].push(instance);
  23892. return this;
  23893. };
  23894. /**
  23895. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  23896. * This means the mesh underlying bounding box and sphere are recomputed.
  23897. * Returns the Mesh.
  23898. */
  23899. Mesh.prototype.refreshBoundingInfo = function () {
  23900. return this._refreshBoundingInfo(false);
  23901. };
  23902. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  23903. if (this._boundingInfo && this._boundingInfo.isLocked) {
  23904. return this;
  23905. }
  23906. var data = this._getPositionData(applySkeleton);
  23907. if (data) {
  23908. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  23909. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23910. }
  23911. if (this.subMeshes) {
  23912. for (var index = 0; index < this.subMeshes.length; index++) {
  23913. this.subMeshes[index].refreshBoundingInfo();
  23914. }
  23915. }
  23916. this._updateBoundingInfo();
  23917. return this;
  23918. };
  23919. Mesh.prototype._getPositionData = function (applySkeleton) {
  23920. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23921. if (data && applySkeleton && this.skeleton) {
  23922. data = data.slice();
  23923. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  23924. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  23925. if (matricesWeightsData && matricesIndicesData) {
  23926. var needExtras = this.numBoneInfluencers > 4;
  23927. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  23928. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  23929. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  23930. var tempVector = BABYLON.Tmp.Vector3[0];
  23931. var finalMatrix = BABYLON.Tmp.Matrix[0];
  23932. var tempMatrix = BABYLON.Tmp.Matrix[1];
  23933. var matWeightIdx = 0;
  23934. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  23935. finalMatrix.reset();
  23936. var inf;
  23937. var weight;
  23938. for (inf = 0; inf < 4; inf++) {
  23939. weight = matricesWeightsData[matWeightIdx + inf];
  23940. if (weight <= 0)
  23941. break;
  23942. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23943. finalMatrix.addToSelf(tempMatrix);
  23944. }
  23945. if (needExtras) {
  23946. for (inf = 0; inf < 4; inf++) {
  23947. weight = matricesWeightsExtraData[matWeightIdx + inf];
  23948. if (weight <= 0)
  23949. break;
  23950. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23951. finalMatrix.addToSelf(tempMatrix);
  23952. }
  23953. }
  23954. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  23955. tempVector.toArray(data, index);
  23956. }
  23957. }
  23958. }
  23959. return data;
  23960. };
  23961. Mesh.prototype._createGlobalSubMesh = function (force) {
  23962. var totalVertices = this.getTotalVertices();
  23963. if (!totalVertices || !this.getIndices()) {
  23964. return null;
  23965. }
  23966. // Check if we need to recreate the submeshes
  23967. if (this.subMeshes && this.subMeshes.length > 0) {
  23968. var ib = this.getIndices();
  23969. if (!ib) {
  23970. return null;
  23971. }
  23972. var totalIndices = ib.length;
  23973. var needToRecreate = false;
  23974. if (force) {
  23975. needToRecreate = true;
  23976. }
  23977. else {
  23978. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  23979. var submesh = _a[_i];
  23980. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  23981. needToRecreate = true;
  23982. break;
  23983. }
  23984. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  23985. needToRecreate = true;
  23986. break;
  23987. }
  23988. }
  23989. }
  23990. if (!needToRecreate) {
  23991. return this.subMeshes[0];
  23992. }
  23993. }
  23994. this.releaseSubMeshes();
  23995. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  23996. };
  23997. Mesh.prototype.subdivide = function (count) {
  23998. if (count < 1) {
  23999. return;
  24000. }
  24001. var totalIndices = this.getTotalIndices();
  24002. var subdivisionSize = (totalIndices / count) | 0;
  24003. var offset = 0;
  24004. // Ensure that subdivisionSize is a multiple of 3
  24005. while (subdivisionSize % 3 !== 0) {
  24006. subdivisionSize++;
  24007. }
  24008. this.releaseSubMeshes();
  24009. for (var index = 0; index < count; index++) {
  24010. if (offset >= totalIndices) {
  24011. break;
  24012. }
  24013. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  24014. offset += subdivisionSize;
  24015. }
  24016. this.synchronizeInstances();
  24017. };
  24018. /**
  24019. * Sets the vertex data of the mesh geometry for the requested `kind`.
  24020. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  24021. * The `data` are either a numeric array either a Float32Array.
  24022. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  24023. * 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).
  24024. * Note that a new underlying VertexBuffer object is created each call.
  24025. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  24026. *
  24027. * Possible `kind` values :
  24028. * - BABYLON.VertexBuffer.PositionKind
  24029. * - BABYLON.VertexBuffer.UVKind
  24030. * - BABYLON.VertexBuffer.UV2Kind
  24031. * - BABYLON.VertexBuffer.UV3Kind
  24032. * - BABYLON.VertexBuffer.UV4Kind
  24033. * - BABYLON.VertexBuffer.UV5Kind
  24034. * - BABYLON.VertexBuffer.UV6Kind
  24035. * - BABYLON.VertexBuffer.ColorKind
  24036. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24037. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24038. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24039. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24040. *
  24041. * Returns the Mesh.
  24042. */
  24043. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  24044. if (updatable === void 0) { updatable = false; }
  24045. if (!this._geometry) {
  24046. var vertexData = new BABYLON.VertexData();
  24047. vertexData.set(data, kind);
  24048. var scene = this.getScene();
  24049. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  24050. }
  24051. else {
  24052. this._geometry.setVerticesData(kind, data, updatable, stride);
  24053. }
  24054. return this;
  24055. };
  24056. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  24057. if (updatable === void 0) { updatable = true; }
  24058. var vb = this.getVertexBuffer(kind);
  24059. if (!vb || vb.isUpdatable() === updatable) {
  24060. return;
  24061. }
  24062. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  24063. };
  24064. /**
  24065. * Sets the mesh VertexBuffer.
  24066. * Returns the Mesh.
  24067. */
  24068. Mesh.prototype.setVerticesBuffer = function (buffer) {
  24069. if (!this._geometry) {
  24070. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  24071. }
  24072. this._geometry.setVerticesBuffer(buffer);
  24073. return this;
  24074. };
  24075. /**
  24076. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  24077. * If the mesh has no geometry, it is simply returned as it is.
  24078. * The `data` are either a numeric array either a Float32Array.
  24079. * No new underlying VertexBuffer object is created.
  24080. * 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.
  24081. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  24082. *
  24083. * Possible `kind` values :
  24084. * - BABYLON.VertexBuffer.PositionKind
  24085. * - BABYLON.VertexBuffer.UVKind
  24086. * - BABYLON.VertexBuffer.UV2Kind
  24087. * - BABYLON.VertexBuffer.UV3Kind
  24088. * - BABYLON.VertexBuffer.UV4Kind
  24089. * - BABYLON.VertexBuffer.UV5Kind
  24090. * - BABYLON.VertexBuffer.UV6Kind
  24091. * - BABYLON.VertexBuffer.ColorKind
  24092. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24093. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24094. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24095. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24096. *
  24097. * Returns the Mesh.
  24098. */
  24099. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  24100. if (!this._geometry) {
  24101. return this;
  24102. }
  24103. if (!makeItUnique) {
  24104. this._geometry.updateVerticesData(kind, data, updateExtends);
  24105. }
  24106. else {
  24107. this.makeGeometryUnique();
  24108. this.updateVerticesData(kind, data, updateExtends, false);
  24109. }
  24110. return this;
  24111. };
  24112. /**
  24113. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  24114. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  24115. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  24116. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  24117. * Returns the Mesh.
  24118. */
  24119. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  24120. if (computeNormals === void 0) { computeNormals = true; }
  24121. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24122. if (!positions) {
  24123. return this;
  24124. }
  24125. positionFunction(positions);
  24126. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  24127. if (computeNormals) {
  24128. var indices = this.getIndices();
  24129. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24130. if (!normals) {
  24131. return this;
  24132. }
  24133. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  24134. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  24135. }
  24136. return this;
  24137. };
  24138. /**
  24139. * Creates a un-shared specific occurence of the geometry for the mesh.
  24140. * Returns the Mesh.
  24141. */
  24142. Mesh.prototype.makeGeometryUnique = function () {
  24143. if (!this._geometry) {
  24144. return this;
  24145. }
  24146. var oldGeometry = this._geometry;
  24147. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  24148. oldGeometry.releaseForMesh(this, true);
  24149. geometry.applyToMesh(this);
  24150. return this;
  24151. };
  24152. /**
  24153. * Sets the mesh indices.
  24154. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  24155. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  24156. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  24157. * This method creates a new index buffer each call.
  24158. * Returns the Mesh.
  24159. */
  24160. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  24161. if (totalVertices === void 0) { totalVertices = null; }
  24162. if (updatable === void 0) { updatable = false; }
  24163. if (!this._geometry) {
  24164. var vertexData = new BABYLON.VertexData();
  24165. vertexData.indices = indices;
  24166. var scene = this.getScene();
  24167. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  24168. }
  24169. else {
  24170. this._geometry.setIndices(indices, totalVertices, updatable);
  24171. }
  24172. return this;
  24173. };
  24174. /**
  24175. * Update the current index buffer
  24176. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  24177. * Returns the Mesh.
  24178. */
  24179. Mesh.prototype.updateIndices = function (indices, offset) {
  24180. if (!this._geometry) {
  24181. return this;
  24182. }
  24183. this._geometry.updateIndices(indices, offset);
  24184. return this;
  24185. };
  24186. /**
  24187. * Invert the geometry to move from a right handed system to a left handed one.
  24188. * Returns the Mesh.
  24189. */
  24190. Mesh.prototype.toLeftHanded = function () {
  24191. if (!this._geometry) {
  24192. return this;
  24193. }
  24194. this._geometry.toLeftHanded();
  24195. return this;
  24196. };
  24197. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  24198. if (!this._geometry) {
  24199. return this;
  24200. }
  24201. var engine = this.getScene().getEngine();
  24202. // Wireframe
  24203. var indexToBind;
  24204. if (this._unIndexed) {
  24205. indexToBind = null;
  24206. }
  24207. else {
  24208. switch (fillMode) {
  24209. case BABYLON.Material.PointFillMode:
  24210. indexToBind = null;
  24211. break;
  24212. case BABYLON.Material.WireFrameFillMode:
  24213. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  24214. break;
  24215. default:
  24216. case BABYLON.Material.TriangleFillMode:
  24217. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  24218. break;
  24219. }
  24220. }
  24221. // VBOs
  24222. this._geometry._bind(effect, indexToBind);
  24223. return this;
  24224. };
  24225. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  24226. if (alternate === void 0) { alternate = false; }
  24227. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  24228. return this;
  24229. }
  24230. this.onBeforeDrawObservable.notifyObservers(this);
  24231. var scene = this.getScene();
  24232. var engine = scene.getEngine();
  24233. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  24234. // or triangles as points
  24235. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  24236. }
  24237. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  24238. // Triangles as wireframe
  24239. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  24240. }
  24241. else {
  24242. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  24243. }
  24244. if (scene._isAlternateRenderingEnabled && !alternate) {
  24245. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  24246. if (!effect || !scene.activeCamera) {
  24247. return this;
  24248. }
  24249. scene._switchToAlternateCameraConfiguration(true);
  24250. this._effectiveMaterial.bindView(effect);
  24251. this._effectiveMaterial.bindViewProjection(effect);
  24252. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  24253. this._draw(subMesh, fillMode, instancesCount, true);
  24254. engine.setViewport(scene.activeCamera.viewport);
  24255. scene._switchToAlternateCameraConfiguration(false);
  24256. this._effectiveMaterial.bindView(effect);
  24257. this._effectiveMaterial.bindViewProjection(effect);
  24258. }
  24259. return this;
  24260. };
  24261. /**
  24262. * Registers for this mesh a javascript function called just before the rendering process.
  24263. * This function is passed the current mesh.
  24264. * Return the Mesh.
  24265. */
  24266. Mesh.prototype.registerBeforeRender = function (func) {
  24267. this.onBeforeRenderObservable.add(func);
  24268. return this;
  24269. };
  24270. /**
  24271. * Disposes a previously registered javascript function called before the rendering.
  24272. * This function is passed the current mesh.
  24273. * Returns the Mesh.
  24274. */
  24275. Mesh.prototype.unregisterBeforeRender = function (func) {
  24276. this.onBeforeRenderObservable.removeCallback(func);
  24277. return this;
  24278. };
  24279. /**
  24280. * Registers for this mesh a javascript function called just after the rendering is complete.
  24281. * This function is passed the current mesh.
  24282. * Returns the Mesh.
  24283. */
  24284. Mesh.prototype.registerAfterRender = function (func) {
  24285. this.onAfterRenderObservable.add(func);
  24286. return this;
  24287. };
  24288. /**
  24289. * Disposes a previously registered javascript function called after the rendering.
  24290. * This function is passed the current mesh.
  24291. * Return the Mesh.
  24292. */
  24293. Mesh.prototype.unregisterAfterRender = function (func) {
  24294. this.onAfterRenderObservable.removeCallback(func);
  24295. return this;
  24296. };
  24297. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  24298. var scene = this.getScene();
  24299. this._batchCache.mustReturn = false;
  24300. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  24301. this._batchCache.visibleInstances[subMeshId] = null;
  24302. if (this._visibleInstances) {
  24303. var currentRenderId = scene.getRenderId();
  24304. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  24305. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  24306. var selfRenderId = this._renderId;
  24307. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  24308. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  24309. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  24310. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  24311. }
  24312. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  24313. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  24314. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  24315. this._batchCache.mustReturn = true;
  24316. return this._batchCache;
  24317. }
  24318. if (currentRenderId !== selfRenderId) {
  24319. this._batchCache.renderSelf[subMeshId] = false;
  24320. }
  24321. }
  24322. this._renderIdForInstances[subMeshId] = currentRenderId;
  24323. }
  24324. return this._batchCache;
  24325. };
  24326. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  24327. var visibleInstances = batch.visibleInstances[subMesh._id];
  24328. if (!visibleInstances) {
  24329. return this;
  24330. }
  24331. var matricesCount = visibleInstances.length + 1;
  24332. var bufferSize = matricesCount * 16 * 4;
  24333. var currentInstancesBufferSize = this._instancesBufferSize;
  24334. var instancesBuffer = this._instancesBuffer;
  24335. while (this._instancesBufferSize < bufferSize) {
  24336. this._instancesBufferSize *= 2;
  24337. }
  24338. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  24339. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  24340. }
  24341. var offset = 0;
  24342. var instancesCount = 0;
  24343. var world = this.getWorldMatrix();
  24344. if (batch.renderSelf[subMesh._id]) {
  24345. world.copyToArray(this._instancesData, offset);
  24346. offset += 16;
  24347. instancesCount++;
  24348. }
  24349. if (visibleInstances) {
  24350. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  24351. var instance = visibleInstances[instanceIndex];
  24352. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  24353. offset += 16;
  24354. instancesCount++;
  24355. }
  24356. }
  24357. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  24358. if (instancesBuffer) {
  24359. instancesBuffer.dispose();
  24360. }
  24361. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  24362. this._instancesBuffer = instancesBuffer;
  24363. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  24364. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  24365. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  24366. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  24367. }
  24368. else {
  24369. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  24370. }
  24371. this._bind(subMesh, effect, fillMode);
  24372. this._draw(subMesh, fillMode, instancesCount);
  24373. engine.unbindInstanceAttributes();
  24374. return this;
  24375. };
  24376. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  24377. var scene = this.getScene();
  24378. var engine = scene.getEngine();
  24379. if (hardwareInstancedRendering) {
  24380. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  24381. }
  24382. else {
  24383. if (batch.renderSelf[subMesh._id]) {
  24384. // Draw
  24385. if (onBeforeDraw) {
  24386. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  24387. }
  24388. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  24389. }
  24390. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  24391. if (visibleInstancesForSubMesh) {
  24392. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  24393. var instance = visibleInstancesForSubMesh[instanceIndex];
  24394. // World
  24395. var world = instance.getWorldMatrix();
  24396. if (onBeforeDraw) {
  24397. onBeforeDraw(true, world, effectiveMaterial);
  24398. }
  24399. // Draw
  24400. this._draw(subMesh, fillMode);
  24401. }
  24402. }
  24403. }
  24404. return this;
  24405. };
  24406. /**
  24407. * Triggers the draw call for the mesh.
  24408. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  24409. * Returns the Mesh.
  24410. */
  24411. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  24412. this.checkOcclusionQuery();
  24413. if (this._isOccluded) {
  24414. return this;
  24415. }
  24416. var scene = this.getScene();
  24417. // Managing instances
  24418. var batch = this._getInstancesRenderList(subMesh._id);
  24419. if (batch.mustReturn) {
  24420. return this;
  24421. }
  24422. // Checking geometry state
  24423. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  24424. return this;
  24425. }
  24426. this.onBeforeRenderObservable.notifyObservers(this);
  24427. var engine = scene.getEngine();
  24428. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  24429. // Material
  24430. var material = subMesh.getMaterial();
  24431. if (!material) {
  24432. return this;
  24433. }
  24434. this._effectiveMaterial = material;
  24435. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  24436. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  24437. return this;
  24438. }
  24439. }
  24440. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  24441. return this;
  24442. }
  24443. // Alpha mode
  24444. if (enableAlphaMode) {
  24445. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  24446. }
  24447. // Outline - step 1
  24448. var savedDepthWrite = engine.getDepthWrite();
  24449. if (this.renderOutline) {
  24450. engine.setDepthWrite(false);
  24451. scene.getOutlineRenderer().render(subMesh, batch);
  24452. engine.setDepthWrite(savedDepthWrite);
  24453. }
  24454. var effect;
  24455. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  24456. effect = subMesh.effect;
  24457. }
  24458. else {
  24459. effect = this._effectiveMaterial.getEffect();
  24460. }
  24461. if (!effect) {
  24462. return this;
  24463. }
  24464. var sideOrientation = this.overrideMaterialSideOrientation;
  24465. if (sideOrientation == null) {
  24466. sideOrientation = this._effectiveMaterial.sideOrientation;
  24467. if (this._getWorldMatrixDeterminant() < 0) {
  24468. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  24469. }
  24470. }
  24471. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  24472. if (this._effectiveMaterial.forceDepthWrite) {
  24473. engine.setDepthWrite(true);
  24474. }
  24475. // Bind
  24476. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  24477. if (!hardwareInstancedRendering) {
  24478. this._bind(subMesh, effect, fillMode);
  24479. }
  24480. var world = this.getWorldMatrix();
  24481. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  24482. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  24483. }
  24484. else {
  24485. this._effectiveMaterial.bind(world, this);
  24486. }
  24487. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  24488. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  24489. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  24490. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  24491. }
  24492. // Draw
  24493. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  24494. // Unbind
  24495. this._effectiveMaterial.unbind();
  24496. // Outline - step 2
  24497. if (this.renderOutline && savedDepthWrite) {
  24498. engine.setDepthWrite(true);
  24499. engine.setColorWrite(false);
  24500. scene.getOutlineRenderer().render(subMesh, batch);
  24501. engine.setColorWrite(true);
  24502. }
  24503. // Overlay
  24504. if (this.renderOverlay) {
  24505. var currentMode = engine.getAlphaMode();
  24506. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  24507. scene.getOutlineRenderer().render(subMesh, batch, true);
  24508. engine.setAlphaMode(currentMode);
  24509. }
  24510. this.onAfterRenderObservable.notifyObservers(this);
  24511. return this;
  24512. };
  24513. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  24514. if (isInstance && effectiveMaterial) {
  24515. effectiveMaterial.bindOnlyWorldMatrix(world);
  24516. }
  24517. };
  24518. /**
  24519. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  24520. */
  24521. Mesh.prototype.getEmittedParticleSystems = function () {
  24522. var results = new Array();
  24523. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  24524. var particleSystem = this.getScene().particleSystems[index];
  24525. if (particleSystem.emitter === this) {
  24526. results.push(particleSystem);
  24527. }
  24528. }
  24529. return results;
  24530. };
  24531. /**
  24532. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  24533. */
  24534. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  24535. var results = new Array();
  24536. var descendants = this.getDescendants();
  24537. descendants.push(this);
  24538. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  24539. var particleSystem = this.getScene().particleSystems[index];
  24540. var emitter = particleSystem.emitter;
  24541. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  24542. results.push(particleSystem);
  24543. }
  24544. }
  24545. return results;
  24546. };
  24547. Mesh.prototype._checkDelayState = function () {
  24548. var scene = this.getScene();
  24549. if (this._geometry) {
  24550. this._geometry.load(scene);
  24551. }
  24552. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24553. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  24554. this._queueLoad(scene);
  24555. }
  24556. return this;
  24557. };
  24558. Mesh.prototype._queueLoad = function (scene) {
  24559. var _this = this;
  24560. scene._addPendingData(this);
  24561. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  24562. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  24563. if (data instanceof ArrayBuffer) {
  24564. _this._delayLoadingFunction(data, _this);
  24565. }
  24566. else {
  24567. _this._delayLoadingFunction(JSON.parse(data), _this);
  24568. }
  24569. _this.instances.forEach(function (instance) {
  24570. instance._syncSubMeshes();
  24571. });
  24572. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24573. scene._removePendingData(_this);
  24574. }, function () { }, scene.database, getBinaryData);
  24575. return this;
  24576. };
  24577. /**
  24578. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  24579. */
  24580. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  24581. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24582. return false;
  24583. }
  24584. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  24585. return false;
  24586. }
  24587. this._checkDelayState();
  24588. return true;
  24589. };
  24590. /**
  24591. * Sets the mesh material by the material or multiMaterial `id` property.
  24592. * The material `id` is a string identifying the material or the multiMaterial.
  24593. * This method returns the Mesh.
  24594. */
  24595. Mesh.prototype.setMaterialByID = function (id) {
  24596. var materials = this.getScene().materials;
  24597. var index;
  24598. for (index = materials.length - 1; index > -1; index--) {
  24599. if (materials[index].id === id) {
  24600. this.material = materials[index];
  24601. return this;
  24602. }
  24603. }
  24604. // Multi
  24605. var multiMaterials = this.getScene().multiMaterials;
  24606. for (index = multiMaterials.length - 1; index > -1; index--) {
  24607. if (multiMaterials[index].id === id) {
  24608. this.material = multiMaterials[index];
  24609. return this;
  24610. }
  24611. }
  24612. return this;
  24613. };
  24614. /**
  24615. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  24616. */
  24617. Mesh.prototype.getAnimatables = function () {
  24618. var results = new Array();
  24619. if (this.material) {
  24620. results.push(this.material);
  24621. }
  24622. if (this.skeleton) {
  24623. results.push(this.skeleton);
  24624. }
  24625. return results;
  24626. };
  24627. /**
  24628. * Modifies the mesh geometry according to the passed transformation matrix.
  24629. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  24630. * The mesh normals are modified accordingly the same transformation.
  24631. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  24632. * Note that, under the hood, this method sets a new VertexBuffer each call.
  24633. * Returns the Mesh.
  24634. */
  24635. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  24636. // Position
  24637. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24638. return this;
  24639. }
  24640. var submeshes = this.subMeshes.splice(0);
  24641. this._resetPointsArrayCache();
  24642. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24643. var temp = new Array();
  24644. var index;
  24645. for (index = 0; index < data.length; index += 3) {
  24646. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  24647. }
  24648. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  24649. // Normals
  24650. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24651. return this;
  24652. }
  24653. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24654. temp = [];
  24655. for (index = 0; index < data.length; index += 3) {
  24656. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  24657. }
  24658. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  24659. // flip faces?
  24660. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  24661. this.flipFaces();
  24662. }
  24663. // Restore submeshes
  24664. this.releaseSubMeshes();
  24665. this.subMeshes = submeshes;
  24666. return this;
  24667. };
  24668. /**
  24669. * Modifies the mesh geometry according to its own current World Matrix.
  24670. * The mesh World Matrix is then reset.
  24671. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  24672. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  24673. * Note that, under the hood, this method sets a new VertexBuffer each call.
  24674. * Returns the Mesh.
  24675. */
  24676. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  24677. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  24678. this.scaling.copyFromFloats(1, 1, 1);
  24679. this.position.copyFromFloats(0, 0, 0);
  24680. this.rotation.copyFromFloats(0, 0, 0);
  24681. //only if quaternion is already set
  24682. if (this.rotationQuaternion) {
  24683. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  24684. }
  24685. this._worldMatrix = BABYLON.Matrix.Identity();
  24686. return this;
  24687. };
  24688. Object.defineProperty(Mesh.prototype, "_positions", {
  24689. // Cache
  24690. get: function () {
  24691. if (this._geometry) {
  24692. return this._geometry._positions;
  24693. }
  24694. return null;
  24695. },
  24696. enumerable: true,
  24697. configurable: true
  24698. });
  24699. Mesh.prototype._resetPointsArrayCache = function () {
  24700. if (this._geometry) {
  24701. this._geometry._resetPointsArrayCache();
  24702. }
  24703. return this;
  24704. };
  24705. Mesh.prototype._generatePointsArray = function () {
  24706. if (this._geometry) {
  24707. return this._geometry._generatePointsArray();
  24708. }
  24709. return false;
  24710. };
  24711. /**
  24712. * Returns a new Mesh object generated from the current mesh properties.
  24713. * This method must not get confused with createInstance().
  24714. * The parameter `name` is a string, the name given to the new mesh.
  24715. * The optional parameter `newParent` can be any Node object (default `null`).
  24716. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  24717. * 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.
  24718. */
  24719. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  24720. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  24721. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  24722. };
  24723. /**
  24724. * Disposes the Mesh.
  24725. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  24726. * Returns nothing.
  24727. */
  24728. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  24729. var _this = this;
  24730. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  24731. this.morphTargetManager = null;
  24732. if (this._geometry) {
  24733. this._geometry.releaseForMesh(this, true);
  24734. }
  24735. // Sources
  24736. var meshes = this.getScene().meshes;
  24737. meshes.forEach(function (abstractMesh) {
  24738. var mesh = abstractMesh;
  24739. if (mesh._source && mesh._source === _this) {
  24740. mesh._source = null;
  24741. }
  24742. });
  24743. this._source = null;
  24744. // Instances
  24745. if (this._instancesBuffer) {
  24746. this._instancesBuffer.dispose();
  24747. this._instancesBuffer = null;
  24748. }
  24749. while (this.instances.length) {
  24750. this.instances[0].dispose();
  24751. }
  24752. // Highlight layers.
  24753. var highlightLayers = this.getScene().highlightLayers;
  24754. for (var i = 0; i < highlightLayers.length; i++) {
  24755. var highlightLayer = highlightLayers[i];
  24756. if (highlightLayer) {
  24757. highlightLayer.removeMesh(this);
  24758. highlightLayer.removeExcludedMesh(this);
  24759. }
  24760. }
  24761. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  24762. };
  24763. /**
  24764. * Modifies the mesh geometry according to a displacement map.
  24765. * 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.
  24766. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  24767. * This method returns nothing.
  24768. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  24769. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  24770. * 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.
  24771. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  24772. * The parameter `uvScale` is an optional vector2 used to scale UV.
  24773. *
  24774. * Returns the Mesh.
  24775. */
  24776. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  24777. var _this = this;
  24778. var scene = this.getScene();
  24779. var onload = function (img) {
  24780. // Getting height map data
  24781. var canvas = document.createElement("canvas");
  24782. var context = canvas.getContext("2d");
  24783. var heightMapWidth = img.width;
  24784. var heightMapHeight = img.height;
  24785. canvas.width = heightMapWidth;
  24786. canvas.height = heightMapHeight;
  24787. context.drawImage(img, 0, 0);
  24788. // Create VertexData from map data
  24789. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  24790. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  24791. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  24792. //execute success callback, if set
  24793. if (onSuccess) {
  24794. onSuccess(_this);
  24795. }
  24796. };
  24797. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  24798. return this;
  24799. };
  24800. /**
  24801. * Modifies the mesh geometry according to a displacementMap buffer.
  24802. * 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.
  24803. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  24804. * This method returns nothing.
  24805. * 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.
  24806. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  24807. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  24808. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  24809. * The parameter `uvScale` is an optional vector2 used to scale UV.
  24810. *
  24811. * Returns the Mesh.
  24812. */
  24813. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  24814. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  24815. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  24816. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24817. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  24818. return this;
  24819. }
  24820. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24821. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24822. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24823. var position = BABYLON.Vector3.Zero();
  24824. var normal = BABYLON.Vector3.Zero();
  24825. var uv = BABYLON.Vector2.Zero();
  24826. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  24827. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  24828. for (var index = 0; index < positions.length; index += 3) {
  24829. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  24830. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  24831. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  24832. // Compute height
  24833. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  24834. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  24835. var pos = (u + v * heightMapWidth) * 4;
  24836. var r = buffer[pos] / 255.0;
  24837. var g = buffer[pos + 1] / 255.0;
  24838. var b = buffer[pos + 2] / 255.0;
  24839. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  24840. normal.normalize();
  24841. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  24842. position = position.add(normal);
  24843. position.toArray(positions, index);
  24844. }
  24845. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  24846. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  24847. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  24848. return this;
  24849. };
  24850. /**
  24851. * Modify the mesh to get a flat shading rendering.
  24852. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  24853. * This method returns the Mesh.
  24854. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  24855. */
  24856. Mesh.prototype.convertToFlatShadedMesh = function () {
  24857. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  24858. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24859. var kinds = this.getVerticesDataKinds();
  24860. var vbs = {};
  24861. var data = {};
  24862. var newdata = {};
  24863. var updatableNormals = false;
  24864. var kindIndex;
  24865. var kind;
  24866. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24867. kind = kinds[kindIndex];
  24868. var vertexBuffer = this.getVertexBuffer(kind);
  24869. if (kind === BABYLON.VertexBuffer.NormalKind) {
  24870. updatableNormals = vertexBuffer.isUpdatable();
  24871. kinds.splice(kindIndex, 1);
  24872. kindIndex--;
  24873. continue;
  24874. }
  24875. vbs[kind] = vertexBuffer;
  24876. data[kind] = vbs[kind].getData();
  24877. newdata[kind] = [];
  24878. }
  24879. // Save previous submeshes
  24880. var previousSubmeshes = this.subMeshes.slice(0);
  24881. var indices = this.getIndices();
  24882. var totalIndices = this.getTotalIndices();
  24883. // Generating unique vertices per face
  24884. var index;
  24885. for (index = 0; index < totalIndices; index++) {
  24886. var vertexIndex = indices[index];
  24887. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24888. kind = kinds[kindIndex];
  24889. var stride = vbs[kind].getStrideSize();
  24890. for (var offset = 0; offset < stride; offset++) {
  24891. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24892. }
  24893. }
  24894. }
  24895. // Updating faces & normal
  24896. var normals = [];
  24897. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  24898. for (index = 0; index < totalIndices; index += 3) {
  24899. indices[index] = index;
  24900. indices[index + 1] = index + 1;
  24901. indices[index + 2] = index + 2;
  24902. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  24903. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  24904. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  24905. var p1p2 = p1.subtract(p2);
  24906. var p3p2 = p3.subtract(p2);
  24907. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  24908. // Store same normals for every vertex
  24909. for (var localIndex = 0; localIndex < 3; localIndex++) {
  24910. normals.push(normal.x);
  24911. normals.push(normal.y);
  24912. normals.push(normal.z);
  24913. }
  24914. }
  24915. this.setIndices(indices);
  24916. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  24917. // Updating vertex buffers
  24918. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24919. kind = kinds[kindIndex];
  24920. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24921. }
  24922. // Updating submeshes
  24923. this.releaseSubMeshes();
  24924. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24925. var previousOne = previousSubmeshes[submeshIndex];
  24926. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24927. }
  24928. this.synchronizeInstances();
  24929. return this;
  24930. };
  24931. /**
  24932. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  24933. * In other words, more vertices, no more indices and a single bigger VBO.
  24934. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  24935. * Returns the Mesh.
  24936. */
  24937. Mesh.prototype.convertToUnIndexedMesh = function () {
  24938. /// <summary>Remove indices by unfolding faces into buffers</summary>
  24939. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24940. var kinds = this.getVerticesDataKinds();
  24941. var vbs = {};
  24942. var data = {};
  24943. var newdata = {};
  24944. var kindIndex;
  24945. var kind;
  24946. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24947. kind = kinds[kindIndex];
  24948. var vertexBuffer = this.getVertexBuffer(kind);
  24949. vbs[kind] = vertexBuffer;
  24950. data[kind] = vbs[kind].getData();
  24951. newdata[kind] = [];
  24952. }
  24953. // Save previous submeshes
  24954. var previousSubmeshes = this.subMeshes.slice(0);
  24955. var indices = this.getIndices();
  24956. var totalIndices = this.getTotalIndices();
  24957. // Generating unique vertices per face
  24958. var index;
  24959. for (index = 0; index < totalIndices; index++) {
  24960. var vertexIndex = indices[index];
  24961. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24962. kind = kinds[kindIndex];
  24963. var stride = vbs[kind].getStrideSize();
  24964. for (var offset = 0; offset < stride; offset++) {
  24965. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24966. }
  24967. }
  24968. }
  24969. // Updating indices
  24970. for (index = 0; index < totalIndices; index += 3) {
  24971. indices[index] = index;
  24972. indices[index + 1] = index + 1;
  24973. indices[index + 2] = index + 2;
  24974. }
  24975. this.setIndices(indices);
  24976. // Updating vertex buffers
  24977. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24978. kind = kinds[kindIndex];
  24979. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24980. }
  24981. // Updating submeshes
  24982. this.releaseSubMeshes();
  24983. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24984. var previousOne = previousSubmeshes[submeshIndex];
  24985. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24986. }
  24987. this._unIndexed = true;
  24988. this.synchronizeInstances();
  24989. return this;
  24990. };
  24991. /**
  24992. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  24993. * This method returns the Mesh.
  24994. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  24995. */
  24996. Mesh.prototype.flipFaces = function (flipNormals) {
  24997. if (flipNormals === void 0) { flipNormals = false; }
  24998. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  24999. var i;
  25000. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  25001. for (i = 0; i < vertex_data.normals.length; i++) {
  25002. vertex_data.normals[i] *= -1;
  25003. }
  25004. }
  25005. if (vertex_data.indices) {
  25006. var temp;
  25007. for (i = 0; i < vertex_data.indices.length; i += 3) {
  25008. // reassign indices
  25009. temp = vertex_data.indices[i + 1];
  25010. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  25011. vertex_data.indices[i + 2] = temp;
  25012. }
  25013. }
  25014. vertex_data.applyToMesh(this);
  25015. return this;
  25016. };
  25017. // Instances
  25018. /**
  25019. * Creates a new InstancedMesh object from the mesh model.
  25020. * An instance shares the same properties and the same material than its model.
  25021. * Only these properties of each instance can then be set individually :
  25022. * - position
  25023. * - rotation
  25024. * - rotationQuaternion
  25025. * - setPivotMatrix
  25026. * - scaling
  25027. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  25028. * Warning : this method is not supported for Line mesh and LineSystem
  25029. */
  25030. Mesh.prototype.createInstance = function (name) {
  25031. return new BABYLON.InstancedMesh(name, this);
  25032. };
  25033. /**
  25034. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  25035. * After this call, all the mesh instances have the same submeshes than the current mesh.
  25036. * This method returns the Mesh.
  25037. */
  25038. Mesh.prototype.synchronizeInstances = function () {
  25039. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  25040. var instance = this.instances[instanceIndex];
  25041. instance._syncSubMeshes();
  25042. }
  25043. return this;
  25044. };
  25045. /**
  25046. * Simplify the mesh according to the given array of settings.
  25047. * Function will return immediately and will simplify async. It returns the Mesh.
  25048. * @param settings a collection of simplification settings.
  25049. * @param parallelProcessing should all levels calculate parallel or one after the other.
  25050. * @param type the type of simplification to run.
  25051. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  25052. */
  25053. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  25054. if (parallelProcessing === void 0) { parallelProcessing = true; }
  25055. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  25056. this.getScene().simplificationQueue.addTask({
  25057. settings: settings,
  25058. parallelProcessing: parallelProcessing,
  25059. mesh: this,
  25060. simplificationType: simplificationType,
  25061. successCallback: successCallback
  25062. });
  25063. return this;
  25064. };
  25065. /**
  25066. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  25067. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  25068. * This should be used together with the simplification to avoid disappearing triangles.
  25069. * Returns the Mesh.
  25070. * @param successCallback an optional success callback to be called after the optimization finished.
  25071. */
  25072. Mesh.prototype.optimizeIndices = function (successCallback) {
  25073. var _this = this;
  25074. var indices = this.getIndices();
  25075. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25076. if (!positions || !indices) {
  25077. return this;
  25078. }
  25079. var vectorPositions = new Array();
  25080. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  25081. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  25082. }
  25083. var dupes = new Array();
  25084. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  25085. var realPos = vectorPositions.length - 1 - iteration;
  25086. var testedPosition = vectorPositions[realPos];
  25087. for (var j = 0; j < realPos; ++j) {
  25088. var againstPosition = vectorPositions[j];
  25089. if (testedPosition.equals(againstPosition)) {
  25090. dupes[realPos] = j;
  25091. break;
  25092. }
  25093. }
  25094. }, function () {
  25095. for (var i = 0; i < indices.length; ++i) {
  25096. indices[i] = dupes[indices[i]] || indices[i];
  25097. }
  25098. //indices are now reordered
  25099. var originalSubMeshes = _this.subMeshes.slice(0);
  25100. _this.setIndices(indices);
  25101. _this.subMeshes = originalSubMeshes;
  25102. if (successCallback) {
  25103. successCallback(_this);
  25104. }
  25105. });
  25106. return this;
  25107. };
  25108. Mesh.prototype.serialize = function (serializationObject) {
  25109. serializationObject.name = this.name;
  25110. serializationObject.id = this.id;
  25111. serializationObject.type = this.getClassName();
  25112. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  25113. serializationObject.tags = BABYLON.Tags.GetTags(this);
  25114. }
  25115. serializationObject.position = this.position.asArray();
  25116. if (this.rotationQuaternion) {
  25117. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  25118. }
  25119. else if (this.rotation) {
  25120. serializationObject.rotation = this.rotation.asArray();
  25121. }
  25122. serializationObject.scaling = this.scaling.asArray();
  25123. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  25124. serializationObject.isEnabled = this.isEnabled();
  25125. serializationObject.isVisible = this.isVisible;
  25126. serializationObject.infiniteDistance = this.infiniteDistance;
  25127. serializationObject.pickable = this.isPickable;
  25128. serializationObject.receiveShadows = this.receiveShadows;
  25129. serializationObject.billboardMode = this.billboardMode;
  25130. serializationObject.visibility = this.visibility;
  25131. serializationObject.checkCollisions = this.checkCollisions;
  25132. serializationObject.isBlocker = this.isBlocker;
  25133. // Parent
  25134. if (this.parent) {
  25135. serializationObject.parentId = this.parent.id;
  25136. }
  25137. // Geometry
  25138. serializationObject.isUnIndexed = this.isUnIndexed;
  25139. var geometry = this._geometry;
  25140. if (geometry) {
  25141. var geometryId = geometry.id;
  25142. serializationObject.geometryId = geometryId;
  25143. // SubMeshes
  25144. serializationObject.subMeshes = [];
  25145. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  25146. var subMesh = this.subMeshes[subIndex];
  25147. serializationObject.subMeshes.push({
  25148. materialIndex: subMesh.materialIndex,
  25149. verticesStart: subMesh.verticesStart,
  25150. verticesCount: subMesh.verticesCount,
  25151. indexStart: subMesh.indexStart,
  25152. indexCount: subMesh.indexCount
  25153. });
  25154. }
  25155. }
  25156. // Material
  25157. if (this.material) {
  25158. serializationObject.materialId = this.material.id;
  25159. }
  25160. else {
  25161. this.material = null;
  25162. }
  25163. // Morph targets
  25164. if (this.morphTargetManager) {
  25165. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  25166. }
  25167. // Skeleton
  25168. if (this.skeleton) {
  25169. serializationObject.skeletonId = this.skeleton.id;
  25170. }
  25171. // Physics
  25172. //TODO implement correct serialization for physics impostors.
  25173. var impostor = this.getPhysicsImpostor();
  25174. if (impostor) {
  25175. serializationObject.physicsMass = impostor.getParam("mass");
  25176. serializationObject.physicsFriction = impostor.getParam("friction");
  25177. serializationObject.physicsRestitution = impostor.getParam("mass");
  25178. serializationObject.physicsImpostor = impostor.type;
  25179. }
  25180. // Metadata
  25181. if (this.metadata) {
  25182. serializationObject.metadata = this.metadata;
  25183. }
  25184. // Instances
  25185. serializationObject.instances = [];
  25186. for (var index = 0; index < this.instances.length; index++) {
  25187. var instance = this.instances[index];
  25188. var serializationInstance = {
  25189. name: instance.name,
  25190. id: instance.id,
  25191. position: instance.position.asArray(),
  25192. scaling: instance.scaling.asArray()
  25193. };
  25194. if (instance.rotationQuaternion) {
  25195. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  25196. }
  25197. else if (instance.rotation) {
  25198. serializationInstance.rotation = instance.rotation.asArray();
  25199. }
  25200. serializationObject.instances.push(serializationInstance);
  25201. // Animations
  25202. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  25203. serializationInstance.ranges = instance.serializeAnimationRanges();
  25204. }
  25205. //
  25206. // Animations
  25207. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  25208. serializationObject.ranges = this.serializeAnimationRanges();
  25209. // Layer mask
  25210. serializationObject.layerMask = this.layerMask;
  25211. // Alpha
  25212. serializationObject.alphaIndex = this.alphaIndex;
  25213. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  25214. // Overlay
  25215. serializationObject.overlayAlpha = this.overlayAlpha;
  25216. serializationObject.overlayColor = this.overlayColor.asArray();
  25217. serializationObject.renderOverlay = this.renderOverlay;
  25218. // Fog
  25219. serializationObject.applyFog = this.applyFog;
  25220. // Action Manager
  25221. if (this.actionManager) {
  25222. serializationObject.actions = this.actionManager.serialize(this.name);
  25223. }
  25224. };
  25225. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  25226. if (!this.geometry) {
  25227. return;
  25228. }
  25229. this._markSubMeshesAsAttributesDirty();
  25230. var morphTargetManager = this._morphTargetManager;
  25231. if (morphTargetManager && morphTargetManager.vertexCount) {
  25232. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  25233. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  25234. this.morphTargetManager = null;
  25235. return;
  25236. }
  25237. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  25238. var morphTarget = morphTargetManager.getActiveTarget(index);
  25239. var positions = morphTarget.getPositions();
  25240. if (!positions) {
  25241. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  25242. return;
  25243. }
  25244. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  25245. var normals = morphTarget.getNormals();
  25246. if (normals) {
  25247. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  25248. }
  25249. var tangents = morphTarget.getTangents();
  25250. if (tangents) {
  25251. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  25252. }
  25253. }
  25254. }
  25255. else {
  25256. var index = 0;
  25257. // Positions
  25258. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  25259. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  25260. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  25261. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  25262. }
  25263. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  25264. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  25265. }
  25266. index++;
  25267. }
  25268. }
  25269. };
  25270. // Statics
  25271. /**
  25272. * Returns a new Mesh object parsed from the source provided.
  25273. * The parameter `parsedMesh` is the source.
  25274. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  25275. */
  25276. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  25277. var mesh;
  25278. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  25279. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  25280. }
  25281. else {
  25282. mesh = new Mesh(parsedMesh.name, scene);
  25283. }
  25284. mesh.id = parsedMesh.id;
  25285. if (BABYLON.Tags) {
  25286. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  25287. }
  25288. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  25289. if (parsedMesh.metadata !== undefined) {
  25290. mesh.metadata = parsedMesh.metadata;
  25291. }
  25292. if (parsedMesh.rotationQuaternion) {
  25293. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  25294. }
  25295. else if (parsedMesh.rotation) {
  25296. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  25297. }
  25298. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  25299. if (parsedMesh.localMatrix) {
  25300. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  25301. }
  25302. else if (parsedMesh.pivotMatrix) {
  25303. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  25304. }
  25305. mesh.setEnabled(parsedMesh.isEnabled);
  25306. mesh.isVisible = parsedMesh.isVisible;
  25307. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  25308. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  25309. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  25310. if (parsedMesh.applyFog !== undefined) {
  25311. mesh.applyFog = parsedMesh.applyFog;
  25312. }
  25313. if (parsedMesh.pickable !== undefined) {
  25314. mesh.isPickable = parsedMesh.pickable;
  25315. }
  25316. if (parsedMesh.alphaIndex !== undefined) {
  25317. mesh.alphaIndex = parsedMesh.alphaIndex;
  25318. }
  25319. mesh.receiveShadows = parsedMesh.receiveShadows;
  25320. mesh.billboardMode = parsedMesh.billboardMode;
  25321. if (parsedMesh.visibility !== undefined) {
  25322. mesh.visibility = parsedMesh.visibility;
  25323. }
  25324. mesh.checkCollisions = parsedMesh.checkCollisions;
  25325. if (parsedMesh.isBlocker !== undefined) {
  25326. mesh.isBlocker = parsedMesh.isBlocker;
  25327. }
  25328. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  25329. // freezeWorldMatrix
  25330. if (parsedMesh.freezeWorldMatrix) {
  25331. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  25332. }
  25333. // Parent
  25334. if (parsedMesh.parentId) {
  25335. mesh._waitingParentId = parsedMesh.parentId;
  25336. }
  25337. // Actions
  25338. if (parsedMesh.actions !== undefined) {
  25339. mesh._waitingActions = parsedMesh.actions;
  25340. }
  25341. // Overlay
  25342. if (parsedMesh.overlayAlpha !== undefined) {
  25343. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  25344. }
  25345. if (parsedMesh.overlayColor !== undefined) {
  25346. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  25347. }
  25348. if (parsedMesh.renderOverlay !== undefined) {
  25349. mesh.renderOverlay = parsedMesh.renderOverlay;
  25350. }
  25351. // Geometry
  25352. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  25353. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  25354. if (parsedMesh.delayLoadingFile) {
  25355. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  25356. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  25357. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  25358. if (parsedMesh._binaryInfo) {
  25359. mesh._binaryInfo = parsedMesh._binaryInfo;
  25360. }
  25361. mesh._delayInfo = [];
  25362. if (parsedMesh.hasUVs) {
  25363. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  25364. }
  25365. if (parsedMesh.hasUVs2) {
  25366. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  25367. }
  25368. if (parsedMesh.hasUVs3) {
  25369. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  25370. }
  25371. if (parsedMesh.hasUVs4) {
  25372. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  25373. }
  25374. if (parsedMesh.hasUVs5) {
  25375. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  25376. }
  25377. if (parsedMesh.hasUVs6) {
  25378. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  25379. }
  25380. if (parsedMesh.hasColors) {
  25381. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  25382. }
  25383. if (parsedMesh.hasMatricesIndices) {
  25384. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25385. }
  25386. if (parsedMesh.hasMatricesWeights) {
  25387. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25388. }
  25389. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  25390. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  25391. mesh._checkDelayState();
  25392. }
  25393. }
  25394. else {
  25395. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  25396. }
  25397. // Material
  25398. if (parsedMesh.materialId) {
  25399. mesh.setMaterialByID(parsedMesh.materialId);
  25400. }
  25401. else {
  25402. mesh.material = null;
  25403. }
  25404. // Morph targets
  25405. if (parsedMesh.morphTargetManagerId > -1) {
  25406. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  25407. }
  25408. // Skeleton
  25409. if (parsedMesh.skeletonId > -1) {
  25410. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  25411. if (parsedMesh.numBoneInfluencers) {
  25412. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  25413. }
  25414. }
  25415. // Animations
  25416. if (parsedMesh.animations) {
  25417. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  25418. var parsedAnimation = parsedMesh.animations[animationIndex];
  25419. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25420. }
  25421. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  25422. }
  25423. if (parsedMesh.autoAnimate) {
  25424. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  25425. }
  25426. // Layer Mask
  25427. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  25428. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  25429. }
  25430. else {
  25431. mesh.layerMask = 0x0FFFFFFF;
  25432. }
  25433. // Physics
  25434. if (parsedMesh.physicsImpostor) {
  25435. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  25436. mass: parsedMesh.physicsMass,
  25437. friction: parsedMesh.physicsFriction,
  25438. restitution: parsedMesh.physicsRestitution
  25439. }, scene);
  25440. }
  25441. // Instances
  25442. if (parsedMesh.instances) {
  25443. for (var index = 0; index < parsedMesh.instances.length; index++) {
  25444. var parsedInstance = parsedMesh.instances[index];
  25445. var instance = mesh.createInstance(parsedInstance.name);
  25446. if (parsedInstance.id) {
  25447. instance.id = parsedInstance.id;
  25448. }
  25449. if (BABYLON.Tags) {
  25450. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  25451. }
  25452. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  25453. if (parsedInstance.parentId) {
  25454. instance._waitingParentId = parsedInstance.parentId;
  25455. }
  25456. if (parsedInstance.rotationQuaternion) {
  25457. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  25458. }
  25459. else if (parsedInstance.rotation) {
  25460. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  25461. }
  25462. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  25463. instance.checkCollisions = mesh.checkCollisions;
  25464. if (parsedMesh.animations) {
  25465. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  25466. parsedAnimation = parsedMesh.animations[animationIndex];
  25467. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25468. }
  25469. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  25470. }
  25471. }
  25472. }
  25473. return mesh;
  25474. };
  25475. /**
  25476. * Creates a ribbon mesh.
  25477. * Please consider using the same method from the MeshBuilder class instead.
  25478. * 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.
  25479. *
  25480. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  25481. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  25482. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  25483. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  25484. * 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.
  25485. * 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.
  25486. * 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
  25487. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25488. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25489. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25490. */
  25491. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  25492. if (closeArray === void 0) { closeArray = false; }
  25493. if (updatable === void 0) { updatable = false; }
  25494. return BABYLON.MeshBuilder.CreateRibbon(name, {
  25495. pathArray: pathArray,
  25496. closeArray: closeArray,
  25497. closePath: closePath,
  25498. offset: offset,
  25499. updatable: updatable,
  25500. sideOrientation: sideOrientation,
  25501. instance: instance
  25502. }, scene);
  25503. };
  25504. /**
  25505. * Creates a plane polygonal mesh. By default, this is a disc.
  25506. * Please consider using the same method from the MeshBuilder class instead.
  25507. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  25508. * 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.
  25509. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25510. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25511. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25512. */
  25513. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  25514. if (scene === void 0) { scene = null; }
  25515. var options = {
  25516. radius: radius,
  25517. tessellation: tessellation,
  25518. sideOrientation: sideOrientation,
  25519. updatable: updatable
  25520. };
  25521. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  25522. };
  25523. /**
  25524. * Creates a box mesh.
  25525. * Please consider using the same method from the MeshBuilder class instead.
  25526. * The parameter `size` sets the size (float) of each box side (default 1).
  25527. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25528. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25529. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25530. */
  25531. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  25532. if (scene === void 0) { scene = null; }
  25533. var options = {
  25534. size: size,
  25535. sideOrientation: sideOrientation,
  25536. updatable: updatable
  25537. };
  25538. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  25539. };
  25540. /**
  25541. * Creates a sphere mesh.
  25542. * Please consider using the same method from the MeshBuilder class instead.
  25543. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  25544. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  25545. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25546. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25547. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25548. */
  25549. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  25550. var options = {
  25551. segments: segments,
  25552. diameterX: diameter,
  25553. diameterY: diameter,
  25554. diameterZ: diameter,
  25555. sideOrientation: sideOrientation,
  25556. updatable: updatable
  25557. };
  25558. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  25559. };
  25560. /**
  25561. * Creates a cylinder or a cone mesh.
  25562. * Please consider using the same method from the MeshBuilder class instead.
  25563. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  25564. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  25565. * 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.
  25566. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  25567. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  25568. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25569. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25570. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25571. */
  25572. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  25573. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  25574. if (scene !== undefined) {
  25575. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  25576. updatable = scene;
  25577. }
  25578. scene = subdivisions;
  25579. subdivisions = 1;
  25580. }
  25581. var options = {
  25582. height: height,
  25583. diameterTop: diameterTop,
  25584. diameterBottom: diameterBottom,
  25585. tessellation: tessellation,
  25586. subdivisions: subdivisions,
  25587. sideOrientation: sideOrientation,
  25588. updatable: updatable
  25589. };
  25590. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  25591. };
  25592. // Torus (Code from SharpDX.org)
  25593. /**
  25594. * Creates a torus mesh.
  25595. * Please consider using the same method from the MeshBuilder class instead.
  25596. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  25597. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  25598. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  25599. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25600. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25601. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25602. */
  25603. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  25604. var options = {
  25605. diameter: diameter,
  25606. thickness: thickness,
  25607. tessellation: tessellation,
  25608. sideOrientation: sideOrientation,
  25609. updatable: updatable
  25610. };
  25611. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  25612. };
  25613. /**
  25614. * Creates a torus knot mesh.
  25615. * Please consider using the same method from the MeshBuilder class instead.
  25616. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  25617. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  25618. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  25619. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  25620. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25621. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25622. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25623. */
  25624. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  25625. var options = {
  25626. radius: radius,
  25627. tube: tube,
  25628. radialSegments: radialSegments,
  25629. tubularSegments: tubularSegments,
  25630. p: p,
  25631. q: q,
  25632. sideOrientation: sideOrientation,
  25633. updatable: updatable
  25634. };
  25635. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  25636. };
  25637. /**
  25638. * Creates a line mesh.
  25639. * Please consider using the same method from the MeshBuilder class instead.
  25640. * 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.
  25641. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25642. * The parameter `points` is an array successive Vector3.
  25643. * 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
  25644. * When updating an instance, remember that only point positions can change, not the number of points.
  25645. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25646. */
  25647. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  25648. if (scene === void 0) { scene = null; }
  25649. if (updatable === void 0) { updatable = false; }
  25650. if (instance === void 0) { instance = null; }
  25651. var options = {
  25652. points: points,
  25653. updatable: updatable,
  25654. instance: instance
  25655. };
  25656. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  25657. };
  25658. /**
  25659. * Creates a dashed line mesh.
  25660. * Please consider using the same method from the MeshBuilder class instead.
  25661. * 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.
  25662. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25663. * The parameter `points` is an array successive Vector3.
  25664. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  25665. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  25666. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  25667. * 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
  25668. * When updating an instance, remember that only point positions can change, not the number of points.
  25669. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25670. */
  25671. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  25672. if (scene === void 0) { scene = null; }
  25673. var options = {
  25674. points: points,
  25675. dashSize: dashSize,
  25676. gapSize: gapSize,
  25677. dashNb: dashNb,
  25678. updatable: updatable,
  25679. instance: instance
  25680. };
  25681. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  25682. };
  25683. /**
  25684. * Creates a polygon mesh.
  25685. * Please consider using the same method from the MeshBuilder class instead.
  25686. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  25687. * 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.
  25688. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25689. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25690. * Remember you can only change the shape positions, not their number when updating a polygon.
  25691. */
  25692. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  25693. var options = {
  25694. shape: shape,
  25695. holes: holes,
  25696. updatable: updatable,
  25697. sideOrientation: sideOrientation
  25698. };
  25699. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  25700. };
  25701. /**
  25702. * Creates an extruded polygon mesh, with depth in the Y direction.
  25703. * Please consider using the same method from the MeshBuilder class instead.
  25704. */
  25705. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  25706. var options = {
  25707. shape: shape,
  25708. holes: holes,
  25709. depth: depth,
  25710. updatable: updatable,
  25711. sideOrientation: sideOrientation
  25712. };
  25713. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  25714. };
  25715. /**
  25716. * Creates an extruded shape mesh.
  25717. * 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.
  25718. * Please consider using the same method from the MeshBuilder class instead.
  25719. *
  25720. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  25721. * 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
  25722. * extruded along the Z axis.
  25723. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  25724. * 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.
  25725. * The parameter `scale` (float, default 1) is the value to scale the shape.
  25726. * 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
  25727. * 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
  25728. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  25729. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25730. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25731. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25732. */
  25733. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  25734. if (scene === void 0) { scene = null; }
  25735. var options = {
  25736. shape: shape,
  25737. path: path,
  25738. scale: scale,
  25739. rotation: rotation,
  25740. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  25741. sideOrientation: sideOrientation,
  25742. instance: instance,
  25743. updatable: updatable
  25744. };
  25745. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  25746. };
  25747. /**
  25748. * Creates an custom extruded shape mesh.
  25749. * 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.
  25750. * Please consider using the same method from the MeshBuilder class instead.
  25751. *
  25752. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  25753. * 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
  25754. * extruded along the Z axis.
  25755. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  25756. * 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
  25757. * and the distance of this point from the begining of the path :
  25758. * ```javascript
  25759. * var rotationFunction = function(i, distance) {
  25760. * // do things
  25761. * return rotationValue; }
  25762. * ```
  25763. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  25764. * 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
  25765. * and the distance of this point from the begining of the path :
  25766. * ```javascript
  25767. * var scaleFunction = function(i, distance) {
  25768. * // do things
  25769. * return scaleValue;}
  25770. * ```
  25771. * It must returns a float value that will be the scale value applied to the shape on each path point.
  25772. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  25773. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  25774. * 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
  25775. * 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
  25776. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  25777. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25778. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25779. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25780. */
  25781. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  25782. var options = {
  25783. shape: shape,
  25784. path: path,
  25785. scaleFunction: scaleFunction,
  25786. rotationFunction: rotationFunction,
  25787. ribbonCloseArray: ribbonCloseArray,
  25788. ribbonClosePath: ribbonClosePath,
  25789. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  25790. sideOrientation: sideOrientation,
  25791. instance: instance,
  25792. updatable: updatable
  25793. };
  25794. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  25795. };
  25796. /**
  25797. * Creates lathe mesh.
  25798. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  25799. * Please consider using the same method from the MeshBuilder class instead.
  25800. * 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
  25801. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  25802. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  25803. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  25804. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25805. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25806. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25807. */
  25808. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  25809. var options = {
  25810. shape: shape,
  25811. radius: radius,
  25812. tessellation: tessellation,
  25813. sideOrientation: sideOrientation,
  25814. updatable: updatable
  25815. };
  25816. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  25817. };
  25818. /**
  25819. * Creates a plane mesh.
  25820. * Please consider using the same method from the MeshBuilder class instead.
  25821. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  25822. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25823. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25824. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25825. */
  25826. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  25827. var options = {
  25828. size: size,
  25829. width: size,
  25830. height: size,
  25831. sideOrientation: sideOrientation,
  25832. updatable: updatable
  25833. };
  25834. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  25835. };
  25836. /**
  25837. * Creates a ground mesh.
  25838. * Please consider using the same method from the MeshBuilder class instead.
  25839. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  25840. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  25841. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25842. */
  25843. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  25844. var options = {
  25845. width: width,
  25846. height: height,
  25847. subdivisions: subdivisions,
  25848. updatable: updatable
  25849. };
  25850. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  25851. };
  25852. /**
  25853. * Creates a tiled ground mesh.
  25854. * Please consider using the same method from the MeshBuilder class instead.
  25855. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  25856. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  25857. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  25858. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  25859. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  25860. * numbers of subdivisions on the ground width and height of each tile.
  25861. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25862. */
  25863. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  25864. var options = {
  25865. xmin: xmin,
  25866. zmin: zmin,
  25867. xmax: xmax,
  25868. zmax: zmax,
  25869. subdivisions: subdivisions,
  25870. precision: precision,
  25871. updatable: updatable
  25872. };
  25873. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  25874. };
  25875. /**
  25876. * Creates a ground mesh from a height map.
  25877. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  25878. * Please consider using the same method from the MeshBuilder class instead.
  25879. * The parameter `url` sets the URL of the height map image resource.
  25880. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  25881. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  25882. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  25883. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  25884. * 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).
  25885. * This function is passed the newly built mesh :
  25886. * ```javascript
  25887. * function(mesh) { // do things
  25888. * return; }
  25889. * ```
  25890. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25891. */
  25892. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  25893. var options = {
  25894. width: width,
  25895. height: height,
  25896. subdivisions: subdivisions,
  25897. minHeight: minHeight,
  25898. maxHeight: maxHeight,
  25899. updatable: updatable,
  25900. onReady: onReady
  25901. };
  25902. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  25903. };
  25904. /**
  25905. * Creates a tube mesh.
  25906. * 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.
  25907. * Please consider using the same method from the MeshBuilder class instead.
  25908. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  25909. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  25910. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  25911. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  25912. * 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.
  25913. * It must return a radius value (positive float) :
  25914. * ```javascript
  25915. * var radiusFunction = function(i, distance) {
  25916. * // do things
  25917. * return radius; }
  25918. * ```
  25919. * 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
  25920. * 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
  25921. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25922. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25923. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25924. */
  25925. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  25926. var options = {
  25927. path: path,
  25928. radius: radius,
  25929. tessellation: tessellation,
  25930. radiusFunction: radiusFunction,
  25931. arc: 1,
  25932. cap: cap,
  25933. updatable: updatable,
  25934. sideOrientation: sideOrientation,
  25935. instance: instance
  25936. };
  25937. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  25938. };
  25939. /**
  25940. * Creates a polyhedron mesh.
  25941. * Please consider using the same method from the MeshBuilder class instead.
  25942. * 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
  25943. * to choose the wanted type.
  25944. * The parameter `size` (positive float, default 1) sets the polygon size.
  25945. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  25946. * 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`.
  25947. * 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
  25948. * 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)`).
  25949. * 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
  25950. * 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.
  25951. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25952. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25953. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25954. */
  25955. Mesh.CreatePolyhedron = function (name, options, scene) {
  25956. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  25957. };
  25958. /**
  25959. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  25960. * Please consider using the same method from the MeshBuilder class instead.
  25961. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  25962. * 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`).
  25963. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  25964. * 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.
  25965. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25966. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25967. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25968. */
  25969. Mesh.CreateIcoSphere = function (name, options, scene) {
  25970. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  25971. };
  25972. /**
  25973. * Creates a decal mesh.
  25974. * Please consider using the same method from the MeshBuilder class instead.
  25975. * 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.
  25976. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  25977. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  25978. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  25979. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  25980. */
  25981. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  25982. var options = {
  25983. position: position,
  25984. normal: normal,
  25985. size: size,
  25986. angle: angle
  25987. };
  25988. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  25989. };
  25990. // Skeletons
  25991. /**
  25992. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25993. */
  25994. Mesh.prototype.setPositionsForCPUSkinning = function () {
  25995. if (!this._sourcePositions) {
  25996. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25997. if (!source) {
  25998. return this._sourcePositions;
  25999. }
  26000. this._sourcePositions = new Float32Array(source);
  26001. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  26002. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  26003. }
  26004. }
  26005. return this._sourcePositions;
  26006. };
  26007. /**
  26008. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  26009. */
  26010. Mesh.prototype.setNormalsForCPUSkinning = function () {
  26011. if (!this._sourceNormals) {
  26012. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26013. if (!source) {
  26014. return this._sourceNormals;
  26015. }
  26016. this._sourceNormals = new Float32Array(source);
  26017. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  26018. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  26019. }
  26020. }
  26021. return this._sourceNormals;
  26022. };
  26023. /**
  26024. * Updates the vertex buffer by applying transformation from the bones.
  26025. * Returns the Mesh.
  26026. *
  26027. * @param {skeleton} skeleton to apply
  26028. */
  26029. Mesh.prototype.applySkeleton = function (skeleton) {
  26030. if (!this.geometry) {
  26031. return this;
  26032. }
  26033. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  26034. return this;
  26035. }
  26036. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  26037. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26038. return this;
  26039. }
  26040. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26041. return this;
  26042. }
  26043. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26044. return this;
  26045. }
  26046. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26047. return this;
  26048. }
  26049. if (!this._sourcePositions) {
  26050. var submeshes = this.subMeshes.slice();
  26051. this.setPositionsForCPUSkinning();
  26052. this.subMeshes = submeshes;
  26053. }
  26054. if (!this._sourceNormals) {
  26055. this.setNormalsForCPUSkinning();
  26056. }
  26057. // positionsData checks for not being Float32Array will only pass at most once
  26058. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26059. if (!positionsData) {
  26060. return this;
  26061. }
  26062. if (!(positionsData instanceof Float32Array)) {
  26063. positionsData = new Float32Array(positionsData);
  26064. }
  26065. // normalsData checks for not being Float32Array will only pass at most once
  26066. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26067. if (!normalsData) {
  26068. return this;
  26069. }
  26070. if (!(normalsData instanceof Float32Array)) {
  26071. normalsData = new Float32Array(normalsData);
  26072. }
  26073. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  26074. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  26075. if (!matricesWeightsData || !matricesIndicesData) {
  26076. return this;
  26077. }
  26078. var needExtras = this.numBoneInfluencers > 4;
  26079. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  26080. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  26081. var skeletonMatrices = skeleton.getTransformMatrices(this);
  26082. var tempVector3 = BABYLON.Vector3.Zero();
  26083. var finalMatrix = new BABYLON.Matrix();
  26084. var tempMatrix = new BABYLON.Matrix();
  26085. var matWeightIdx = 0;
  26086. var inf;
  26087. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  26088. var weight;
  26089. for (inf = 0; inf < 4; inf++) {
  26090. weight = matricesWeightsData[matWeightIdx + inf];
  26091. if (weight > 0) {
  26092. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  26093. finalMatrix.addToSelf(tempMatrix);
  26094. }
  26095. else
  26096. break;
  26097. }
  26098. if (needExtras) {
  26099. for (inf = 0; inf < 4; inf++) {
  26100. weight = matricesWeightsExtraData[matWeightIdx + inf];
  26101. if (weight > 0) {
  26102. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  26103. finalMatrix.addToSelf(tempMatrix);
  26104. }
  26105. else
  26106. break;
  26107. }
  26108. }
  26109. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  26110. tempVector3.toArray(positionsData, index);
  26111. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  26112. tempVector3.toArray(normalsData, index);
  26113. finalMatrix.reset();
  26114. }
  26115. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  26116. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  26117. return this;
  26118. };
  26119. // Tools
  26120. /**
  26121. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  26122. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  26123. */
  26124. Mesh.MinMax = function (meshes) {
  26125. var minVector = null;
  26126. var maxVector = null;
  26127. meshes.forEach(function (mesh, index, array) {
  26128. var boundingInfo = mesh.getBoundingInfo();
  26129. var boundingBox = boundingInfo.boundingBox;
  26130. if (!minVector || !maxVector) {
  26131. minVector = boundingBox.minimumWorld;
  26132. maxVector = boundingBox.maximumWorld;
  26133. }
  26134. else {
  26135. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  26136. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  26137. }
  26138. });
  26139. if (!minVector || !maxVector) {
  26140. return {
  26141. min: BABYLON.Vector3.Zero(),
  26142. max: BABYLON.Vector3.Zero()
  26143. };
  26144. }
  26145. return {
  26146. min: minVector,
  26147. max: maxVector
  26148. };
  26149. };
  26150. /**
  26151. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  26152. */
  26153. Mesh.Center = function (meshesOrMinMaxVector) {
  26154. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  26155. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  26156. };
  26157. /**
  26158. * Merge the array of meshes into a single mesh for performance reasons.
  26159. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  26160. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  26161. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  26162. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  26163. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  26164. */
  26165. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  26166. if (disposeSource === void 0) { disposeSource = true; }
  26167. var index;
  26168. if (!allow32BitsIndices) {
  26169. var totalVertices = 0;
  26170. // Counting vertices
  26171. for (index = 0; index < meshes.length; index++) {
  26172. if (meshes[index]) {
  26173. totalVertices += meshes[index].getTotalVertices();
  26174. if (totalVertices > 65536) {
  26175. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  26176. return null;
  26177. }
  26178. }
  26179. }
  26180. }
  26181. // Merge
  26182. var vertexData = null;
  26183. var otherVertexData;
  26184. var indiceArray = new Array();
  26185. var source = null;
  26186. for (index = 0; index < meshes.length; index++) {
  26187. if (meshes[index]) {
  26188. meshes[index].computeWorldMatrix(true);
  26189. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  26190. otherVertexData.transform(meshes[index].getWorldMatrix());
  26191. if (vertexData) {
  26192. vertexData.merge(otherVertexData);
  26193. }
  26194. else {
  26195. vertexData = otherVertexData;
  26196. source = meshes[index];
  26197. }
  26198. if (subdivideWithSubMeshes) {
  26199. indiceArray.push(meshes[index].getTotalIndices());
  26200. }
  26201. }
  26202. }
  26203. source = source;
  26204. if (!meshSubclass) {
  26205. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  26206. }
  26207. vertexData.applyToMesh(meshSubclass);
  26208. // Setting properties
  26209. meshSubclass.material = source.material;
  26210. meshSubclass.checkCollisions = source.checkCollisions;
  26211. // Cleaning
  26212. if (disposeSource) {
  26213. for (index = 0; index < meshes.length; index++) {
  26214. if (meshes[index]) {
  26215. meshes[index].dispose();
  26216. }
  26217. }
  26218. }
  26219. // Subdivide
  26220. if (subdivideWithSubMeshes) {
  26221. //-- Suppresions du submesh global
  26222. meshSubclass.releaseSubMeshes();
  26223. index = 0;
  26224. var offset = 0;
  26225. //-- aplique la subdivision en fonction du tableau d'indices
  26226. while (index < indiceArray.length) {
  26227. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  26228. offset += indiceArray[index];
  26229. index++;
  26230. }
  26231. }
  26232. return meshSubclass;
  26233. };
  26234. // Consts
  26235. Mesh._FRONTSIDE = 0;
  26236. Mesh._BACKSIDE = 1;
  26237. Mesh._DOUBLESIDE = 2;
  26238. Mesh._DEFAULTSIDE = 0;
  26239. Mesh._NO_CAP = 0;
  26240. Mesh._CAP_START = 1;
  26241. Mesh._CAP_END = 2;
  26242. Mesh._CAP_ALL = 3;
  26243. return Mesh;
  26244. }(BABYLON.AbstractMesh));
  26245. BABYLON.Mesh = Mesh;
  26246. })(BABYLON || (BABYLON = {}));
  26247. //# sourceMappingURL=babylon.mesh.js.map
  26248. var BABYLON;
  26249. (function (BABYLON) {
  26250. var BaseSubMesh = /** @class */ (function () {
  26251. function BaseSubMesh() {
  26252. }
  26253. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  26254. get: function () {
  26255. return this._materialEffect;
  26256. },
  26257. enumerable: true,
  26258. configurable: true
  26259. });
  26260. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  26261. if (defines === void 0) { defines = null; }
  26262. if (this._materialEffect === effect) {
  26263. if (!effect) {
  26264. this._materialDefines = null;
  26265. }
  26266. return;
  26267. }
  26268. this._materialDefines = defines;
  26269. this._materialEffect = effect;
  26270. };
  26271. return BaseSubMesh;
  26272. }());
  26273. BABYLON.BaseSubMesh = BaseSubMesh;
  26274. var SubMesh = /** @class */ (function (_super) {
  26275. __extends(SubMesh, _super);
  26276. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  26277. if (createBoundingBox === void 0) { createBoundingBox = true; }
  26278. var _this = _super.call(this) || this;
  26279. _this.materialIndex = materialIndex;
  26280. _this.verticesStart = verticesStart;
  26281. _this.verticesCount = verticesCount;
  26282. _this.indexStart = indexStart;
  26283. _this.indexCount = indexCount;
  26284. _this._renderId = 0;
  26285. _this._mesh = mesh;
  26286. _this._renderingMesh = renderingMesh || mesh;
  26287. mesh.subMeshes.push(_this);
  26288. _this._trianglePlanes = [];
  26289. _this._id = mesh.subMeshes.length - 1;
  26290. if (createBoundingBox) {
  26291. _this.refreshBoundingInfo();
  26292. mesh.computeWorldMatrix(true);
  26293. }
  26294. return _this;
  26295. }
  26296. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  26297. if (createBoundingBox === void 0) { createBoundingBox = true; }
  26298. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  26299. };
  26300. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  26301. get: function () {
  26302. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  26303. },
  26304. enumerable: true,
  26305. configurable: true
  26306. });
  26307. /**
  26308. * Returns the submesh BoudingInfo object.
  26309. */
  26310. SubMesh.prototype.getBoundingInfo = function () {
  26311. if (this.IsGlobal) {
  26312. return this._mesh.getBoundingInfo();
  26313. }
  26314. return this._boundingInfo;
  26315. };
  26316. /**
  26317. * Sets the submesh BoundingInfo.
  26318. * Return the SubMesh.
  26319. */
  26320. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  26321. this._boundingInfo = boundingInfo;
  26322. return this;
  26323. };
  26324. /**
  26325. * Returns the mesh of the current submesh.
  26326. */
  26327. SubMesh.prototype.getMesh = function () {
  26328. return this._mesh;
  26329. };
  26330. /**
  26331. * Returns the rendering mesh of the submesh.
  26332. */
  26333. SubMesh.prototype.getRenderingMesh = function () {
  26334. return this._renderingMesh;
  26335. };
  26336. /**
  26337. * Returns the submesh material.
  26338. */
  26339. SubMesh.prototype.getMaterial = function () {
  26340. var rootMaterial = this._renderingMesh.material;
  26341. if (rootMaterial && rootMaterial.getSubMaterial) {
  26342. var multiMaterial = rootMaterial;
  26343. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  26344. if (this._currentMaterial !== effectiveMaterial) {
  26345. this._currentMaterial = effectiveMaterial;
  26346. this._materialDefines = null;
  26347. }
  26348. return effectiveMaterial;
  26349. }
  26350. if (!rootMaterial) {
  26351. return this._mesh.getScene().defaultMaterial;
  26352. }
  26353. return rootMaterial;
  26354. };
  26355. // Methods
  26356. /**
  26357. * Sets a new updated BoundingInfo object to the submesh.
  26358. * Returns the SubMesh.
  26359. */
  26360. SubMesh.prototype.refreshBoundingInfo = function () {
  26361. this._lastColliderWorldVertices = null;
  26362. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  26363. return this;
  26364. }
  26365. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26366. if (!data) {
  26367. this._boundingInfo = this._mesh.getBoundingInfo();
  26368. return this;
  26369. }
  26370. var indices = this._renderingMesh.getIndices();
  26371. var extend;
  26372. //is this the only submesh?
  26373. if (this.indexStart === 0 && this.indexCount === indices.length) {
  26374. var boundingInfo = this._renderingMesh.getBoundingInfo();
  26375. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  26376. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  26377. }
  26378. else {
  26379. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  26380. }
  26381. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26382. return this;
  26383. };
  26384. SubMesh.prototype._checkCollision = function (collider) {
  26385. var boundingInfo = this._renderingMesh.getBoundingInfo();
  26386. return boundingInfo._checkCollision(collider);
  26387. };
  26388. /**
  26389. * Updates the submesh BoundingInfo.
  26390. * Returns the Submesh.
  26391. */
  26392. SubMesh.prototype.updateBoundingInfo = function (world) {
  26393. var boundingInfo = this.getBoundingInfo();
  26394. if (!boundingInfo) {
  26395. this.refreshBoundingInfo();
  26396. boundingInfo = this.getBoundingInfo();
  26397. }
  26398. boundingInfo.update(world);
  26399. return this;
  26400. };
  26401. /**
  26402. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  26403. * Boolean returned.
  26404. */
  26405. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  26406. var boundingInfo = this.getBoundingInfo();
  26407. if (!boundingInfo) {
  26408. return false;
  26409. }
  26410. return boundingInfo.isInFrustum(frustumPlanes);
  26411. };
  26412. /**
  26413. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  26414. * Boolean returned.
  26415. */
  26416. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  26417. var boundingInfo = this.getBoundingInfo();
  26418. if (!boundingInfo) {
  26419. return false;
  26420. }
  26421. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  26422. };
  26423. /**
  26424. * Renders the submesh.
  26425. * Returns it.
  26426. */
  26427. SubMesh.prototype.render = function (enableAlphaMode) {
  26428. this._renderingMesh.render(this, enableAlphaMode);
  26429. return this;
  26430. };
  26431. /**
  26432. * Returns a new Index Buffer.
  26433. * Type returned : WebGLBuffer.
  26434. */
  26435. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  26436. if (!this._linesIndexBuffer) {
  26437. var linesIndices = [];
  26438. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  26439. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  26440. }
  26441. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  26442. this.linesIndexCount = linesIndices.length;
  26443. }
  26444. return this._linesIndexBuffer;
  26445. };
  26446. /**
  26447. * True is the passed Ray intersects the submesh bounding box.
  26448. * Boolean returned.
  26449. */
  26450. SubMesh.prototype.canIntersects = function (ray) {
  26451. var boundingInfo = this.getBoundingInfo();
  26452. if (!boundingInfo) {
  26453. return false;
  26454. }
  26455. return ray.intersectsBox(boundingInfo.boundingBox);
  26456. };
  26457. /**
  26458. * Returns an object IntersectionInfo.
  26459. */
  26460. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  26461. var intersectInfo = null;
  26462. // LineMesh first as it's also a Mesh...
  26463. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  26464. var lineMesh = this._mesh;
  26465. // Line test
  26466. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  26467. var p0 = positions[indices[index]];
  26468. var p1 = positions[indices[index + 1]];
  26469. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  26470. if (length < 0) {
  26471. continue;
  26472. }
  26473. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  26474. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  26475. if (fastCheck) {
  26476. break;
  26477. }
  26478. }
  26479. }
  26480. }
  26481. else {
  26482. // Triangles test
  26483. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  26484. var p0 = positions[indices[index]];
  26485. var p1 = positions[indices[index + 1]];
  26486. var p2 = positions[indices[index + 2]];
  26487. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  26488. if (currentIntersectInfo) {
  26489. if (currentIntersectInfo.distance < 0) {
  26490. continue;
  26491. }
  26492. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  26493. intersectInfo = currentIntersectInfo;
  26494. intersectInfo.faceId = index / 3;
  26495. if (fastCheck) {
  26496. break;
  26497. }
  26498. }
  26499. }
  26500. }
  26501. }
  26502. return intersectInfo;
  26503. };
  26504. SubMesh.prototype._rebuild = function () {
  26505. if (this._linesIndexBuffer) {
  26506. this._linesIndexBuffer = null;
  26507. }
  26508. };
  26509. // Clone
  26510. /**
  26511. * Creates a new Submesh from the passed Mesh.
  26512. */
  26513. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  26514. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  26515. if (!this.IsGlobal) {
  26516. var boundingInfo = this.getBoundingInfo();
  26517. if (!boundingInfo) {
  26518. return result;
  26519. }
  26520. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  26521. }
  26522. return result;
  26523. };
  26524. // Dispose
  26525. /**
  26526. * Disposes the Submesh.
  26527. * Returns nothing.
  26528. */
  26529. SubMesh.prototype.dispose = function () {
  26530. if (this._linesIndexBuffer) {
  26531. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  26532. this._linesIndexBuffer = null;
  26533. }
  26534. // Remove from mesh
  26535. var index = this._mesh.subMeshes.indexOf(this);
  26536. this._mesh.subMeshes.splice(index, 1);
  26537. };
  26538. // Statics
  26539. /**
  26540. * Creates a new Submesh from the passed parameters :
  26541. * - materialIndex (integer) : the index of the main mesh material.
  26542. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  26543. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  26544. * - mesh (Mesh) : the main mesh to create the submesh from.
  26545. * - renderingMesh (optional Mesh) : rendering mesh.
  26546. */
  26547. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  26548. var minVertexIndex = Number.MAX_VALUE;
  26549. var maxVertexIndex = -Number.MAX_VALUE;
  26550. renderingMesh = (renderingMesh || mesh);
  26551. var indices = renderingMesh.getIndices();
  26552. for (var index = startIndex; index < startIndex + indexCount; index++) {
  26553. var vertexIndex = indices[index];
  26554. if (vertexIndex < minVertexIndex)
  26555. minVertexIndex = vertexIndex;
  26556. if (vertexIndex > maxVertexIndex)
  26557. maxVertexIndex = vertexIndex;
  26558. }
  26559. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  26560. };
  26561. return SubMesh;
  26562. }(BaseSubMesh));
  26563. BABYLON.SubMesh = SubMesh;
  26564. })(BABYLON || (BABYLON = {}));
  26565. //# sourceMappingURL=babylon.subMesh.js.map
  26566. var BABYLON;
  26567. (function (BABYLON) {
  26568. var EffectFallbacks = /** @class */ (function () {
  26569. function EffectFallbacks() {
  26570. this._defines = {};
  26571. this._currentRank = 32;
  26572. this._maxRank = -1;
  26573. }
  26574. EffectFallbacks.prototype.unBindMesh = function () {
  26575. this._mesh = null;
  26576. };
  26577. EffectFallbacks.prototype.addFallback = function (rank, define) {
  26578. if (!this._defines[rank]) {
  26579. if (rank < this._currentRank) {
  26580. this._currentRank = rank;
  26581. }
  26582. if (rank > this._maxRank) {
  26583. this._maxRank = rank;
  26584. }
  26585. this._defines[rank] = new Array();
  26586. }
  26587. this._defines[rank].push(define);
  26588. };
  26589. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  26590. this._mesh = mesh;
  26591. if (rank < this._currentRank) {
  26592. this._currentRank = rank;
  26593. }
  26594. if (rank > this._maxRank) {
  26595. this._maxRank = rank;
  26596. }
  26597. };
  26598. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  26599. get: function () {
  26600. return this._currentRank <= this._maxRank;
  26601. },
  26602. enumerable: true,
  26603. configurable: true
  26604. });
  26605. EffectFallbacks.prototype.reduce = function (currentDefines) {
  26606. // First we try to switch to CPU skinning
  26607. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  26608. this._mesh.computeBonesUsingShaders = false;
  26609. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  26610. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  26611. var scene = this._mesh.getScene();
  26612. for (var index = 0; index < scene.meshes.length; index++) {
  26613. var otherMesh = scene.meshes[index];
  26614. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  26615. otherMesh.computeBonesUsingShaders = false;
  26616. }
  26617. }
  26618. }
  26619. else {
  26620. var currentFallbacks = this._defines[this._currentRank];
  26621. if (currentFallbacks) {
  26622. for (var index = 0; index < currentFallbacks.length; index++) {
  26623. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  26624. }
  26625. }
  26626. this._currentRank++;
  26627. }
  26628. return currentDefines;
  26629. };
  26630. return EffectFallbacks;
  26631. }());
  26632. BABYLON.EffectFallbacks = EffectFallbacks;
  26633. var EffectCreationOptions = /** @class */ (function () {
  26634. function EffectCreationOptions() {
  26635. }
  26636. return EffectCreationOptions;
  26637. }());
  26638. BABYLON.EffectCreationOptions = EffectCreationOptions;
  26639. var Effect = /** @class */ (function () {
  26640. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  26641. if (samplers === void 0) { samplers = null; }
  26642. if (defines === void 0) { defines = null; }
  26643. if (fallbacks === void 0) { fallbacks = null; }
  26644. if (onCompiled === void 0) { onCompiled = null; }
  26645. if (onError === void 0) { onError = null; }
  26646. var _this = this;
  26647. this.uniqueId = 0;
  26648. this.onCompileObservable = new BABYLON.Observable();
  26649. this.onErrorObservable = new BABYLON.Observable();
  26650. this.onBindObservable = new BABYLON.Observable();
  26651. this._uniformBuffersNames = {};
  26652. this._isReady = false;
  26653. this._compilationError = "";
  26654. this.name = baseName;
  26655. if (attributesNamesOrOptions.attributes) {
  26656. var options = attributesNamesOrOptions;
  26657. this._engine = uniformsNamesOrEngine;
  26658. this._attributesNames = options.attributes;
  26659. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  26660. this._samplers = options.samplers;
  26661. this.defines = options.defines;
  26662. this.onError = options.onError;
  26663. this.onCompiled = options.onCompiled;
  26664. this._fallbacks = options.fallbacks;
  26665. this._indexParameters = options.indexParameters;
  26666. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  26667. if (options.uniformBuffersNames) {
  26668. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  26669. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  26670. }
  26671. }
  26672. }
  26673. else {
  26674. this._engine = engine;
  26675. this.defines = defines;
  26676. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  26677. this._samplers = samplers;
  26678. this._attributesNames = attributesNamesOrOptions;
  26679. this.onError = onError;
  26680. this.onCompiled = onCompiled;
  26681. this._indexParameters = indexParameters;
  26682. this._fallbacks = fallbacks;
  26683. }
  26684. this.uniqueId = Effect._uniqueIdSeed++;
  26685. var vertexSource;
  26686. var fragmentSource;
  26687. if (baseName.vertexElement) {
  26688. vertexSource = document.getElementById(baseName.vertexElement);
  26689. if (!vertexSource) {
  26690. vertexSource = baseName.vertexElement;
  26691. }
  26692. }
  26693. else {
  26694. vertexSource = baseName.vertex || baseName;
  26695. }
  26696. if (baseName.fragmentElement) {
  26697. fragmentSource = document.getElementById(baseName.fragmentElement);
  26698. if (!fragmentSource) {
  26699. fragmentSource = baseName.fragmentElement;
  26700. }
  26701. }
  26702. else {
  26703. fragmentSource = baseName.fragment || baseName;
  26704. }
  26705. this._loadVertexShader(vertexSource, function (vertexCode) {
  26706. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  26707. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  26708. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  26709. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  26710. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  26711. if (baseName) {
  26712. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  26713. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  26714. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  26715. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  26716. }
  26717. else {
  26718. _this._vertexSourceCode = migratedVertexCode;
  26719. _this._fragmentSourceCode = migratedFragmentCode;
  26720. }
  26721. _this._prepareEffect();
  26722. });
  26723. });
  26724. });
  26725. });
  26726. });
  26727. });
  26728. }
  26729. Object.defineProperty(Effect.prototype, "key", {
  26730. get: function () {
  26731. return this._key;
  26732. },
  26733. enumerable: true,
  26734. configurable: true
  26735. });
  26736. // Properties
  26737. Effect.prototype.isReady = function () {
  26738. return this._isReady;
  26739. };
  26740. Effect.prototype.getEngine = function () {
  26741. return this._engine;
  26742. };
  26743. Effect.prototype.getProgram = function () {
  26744. return this._program;
  26745. };
  26746. Effect.prototype.getAttributesNames = function () {
  26747. return this._attributesNames;
  26748. };
  26749. Effect.prototype.getAttributeLocation = function (index) {
  26750. return this._attributes[index];
  26751. };
  26752. Effect.prototype.getAttributeLocationByName = function (name) {
  26753. var index = this._attributesNames.indexOf(name);
  26754. return this._attributes[index];
  26755. };
  26756. Effect.prototype.getAttributesCount = function () {
  26757. return this._attributes.length;
  26758. };
  26759. Effect.prototype.getUniformIndex = function (uniformName) {
  26760. return this._uniformsNames.indexOf(uniformName);
  26761. };
  26762. Effect.prototype.getUniform = function (uniformName) {
  26763. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  26764. };
  26765. Effect.prototype.getSamplers = function () {
  26766. return this._samplers;
  26767. };
  26768. Effect.prototype.getCompilationError = function () {
  26769. return this._compilationError;
  26770. };
  26771. // Methods
  26772. Effect.prototype.executeWhenCompiled = function (func) {
  26773. if (this.isReady()) {
  26774. func(this);
  26775. return;
  26776. }
  26777. this.onCompileObservable.add(function (effect) {
  26778. func(effect);
  26779. });
  26780. };
  26781. Effect.prototype._loadVertexShader = function (vertex, callback) {
  26782. if (BABYLON.Tools.IsWindowObjectExist()) {
  26783. // DOM element ?
  26784. if (vertex instanceof HTMLElement) {
  26785. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  26786. callback(vertexCode);
  26787. return;
  26788. }
  26789. }
  26790. // Base64 encoded ?
  26791. if (vertex.substr(0, 7) === "base64:") {
  26792. var vertexBinary = window.atob(vertex.substr(7));
  26793. callback(vertexBinary);
  26794. return;
  26795. }
  26796. // Is in local store ?
  26797. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  26798. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  26799. return;
  26800. }
  26801. var vertexShaderUrl;
  26802. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  26803. vertexShaderUrl = vertex;
  26804. }
  26805. else {
  26806. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  26807. }
  26808. // Vertex shader
  26809. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  26810. };
  26811. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  26812. if (BABYLON.Tools.IsWindowObjectExist()) {
  26813. // DOM element ?
  26814. if (fragment instanceof HTMLElement) {
  26815. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  26816. callback(fragmentCode);
  26817. return;
  26818. }
  26819. }
  26820. // Base64 encoded ?
  26821. if (fragment.substr(0, 7) === "base64:") {
  26822. var fragmentBinary = window.atob(fragment.substr(7));
  26823. callback(fragmentBinary);
  26824. return;
  26825. }
  26826. // Is in local store ?
  26827. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  26828. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  26829. return;
  26830. }
  26831. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  26832. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  26833. return;
  26834. }
  26835. var fragmentShaderUrl;
  26836. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  26837. fragmentShaderUrl = fragment;
  26838. }
  26839. else {
  26840. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  26841. }
  26842. // Fragment shader
  26843. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  26844. };
  26845. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  26846. // Rebuild shaders source code
  26847. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  26848. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  26849. vertexCode = prefix + vertexCode;
  26850. fragmentCode = prefix + fragmentCode;
  26851. // Number lines of shaders source code
  26852. var i = 2;
  26853. var regex = /\n/gm;
  26854. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  26855. i = 2;
  26856. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  26857. // Dump shaders name and formatted source code
  26858. if (this.name.vertexElement) {
  26859. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  26860. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  26861. }
  26862. else if (this.name.vertex) {
  26863. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  26864. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  26865. }
  26866. else {
  26867. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  26868. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  26869. }
  26870. };
  26871. ;
  26872. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  26873. var preparedSourceCode = this._processPrecision(sourceCode);
  26874. if (this._engine.webGLVersion == 1) {
  26875. callback(preparedSourceCode);
  26876. return;
  26877. }
  26878. // Already converted
  26879. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  26880. callback(preparedSourceCode.replace("#version 300 es", ""));
  26881. return;
  26882. }
  26883. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  26884. // Remove extensions
  26885. // #extension GL_OES_standard_derivatives : enable
  26886. // #extension GL_EXT_shader_texture_lod : enable
  26887. // #extension GL_EXT_frag_depth : enable
  26888. // #extension GL_EXT_draw_buffers : require
  26889. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  26890. var result = preparedSourceCode.replace(regex, "");
  26891. // Migrate to GLSL v300
  26892. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  26893. result = result.replace(/attribute[ \t]/g, "in ");
  26894. result = result.replace(/[ \t]attribute/g, " in");
  26895. if (isFragment) {
  26896. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  26897. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  26898. result = result.replace(/texture2D\s*\(/g, "texture(");
  26899. result = result.replace(/textureCube\s*\(/g, "texture(");
  26900. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  26901. result = result.replace(/gl_FragColor/g, "glFragColor");
  26902. result = result.replace(/gl_FragData/g, "glFragData");
  26903. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  26904. }
  26905. callback(result);
  26906. };
  26907. Effect.prototype._processIncludes = function (sourceCode, callback) {
  26908. var _this = this;
  26909. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  26910. var match = regex.exec(sourceCode);
  26911. var returnValue = new String(sourceCode);
  26912. while (match != null) {
  26913. var includeFile = match[1];
  26914. // Uniform declaration
  26915. if (includeFile.indexOf("__decl__") !== -1) {
  26916. includeFile = includeFile.replace(/__decl__/, "");
  26917. if (this._engine.supportsUniformBuffers) {
  26918. includeFile = includeFile.replace(/Vertex/, "Ubo");
  26919. includeFile = includeFile.replace(/Fragment/, "Ubo");
  26920. }
  26921. includeFile = includeFile + "Declaration";
  26922. }
  26923. if (Effect.IncludesShadersStore[includeFile]) {
  26924. // Substitution
  26925. var includeContent = Effect.IncludesShadersStore[includeFile];
  26926. if (match[2]) {
  26927. var splits = match[3].split(",");
  26928. for (var index = 0; index < splits.length; index += 2) {
  26929. var source = new RegExp(splits[index], "g");
  26930. var dest = splits[index + 1];
  26931. includeContent = includeContent.replace(source, dest);
  26932. }
  26933. }
  26934. if (match[4]) {
  26935. var indexString = match[5];
  26936. if (indexString.indexOf("..") !== -1) {
  26937. var indexSplits = indexString.split("..");
  26938. var minIndex = parseInt(indexSplits[0]);
  26939. var maxIndex = parseInt(indexSplits[1]);
  26940. var sourceIncludeContent = includeContent.slice(0);
  26941. includeContent = "";
  26942. if (isNaN(maxIndex)) {
  26943. maxIndex = this._indexParameters[indexSplits[1]];
  26944. }
  26945. for (var i = minIndex; i < maxIndex; i++) {
  26946. if (!this._engine.supportsUniformBuffers) {
  26947. // Ubo replacement
  26948. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  26949. return p1 + "{X}";
  26950. });
  26951. }
  26952. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  26953. }
  26954. }
  26955. else {
  26956. if (!this._engine.supportsUniformBuffers) {
  26957. // Ubo replacement
  26958. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  26959. return p1 + "{X}";
  26960. });
  26961. }
  26962. includeContent = includeContent.replace(/\{X\}/g, indexString);
  26963. }
  26964. }
  26965. // Replace
  26966. returnValue = returnValue.replace(match[0], includeContent);
  26967. }
  26968. else {
  26969. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  26970. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  26971. Effect.IncludesShadersStore[includeFile] = fileContent;
  26972. _this._processIncludes(returnValue, callback);
  26973. });
  26974. return;
  26975. }
  26976. match = regex.exec(sourceCode);
  26977. }
  26978. callback(returnValue);
  26979. };
  26980. Effect.prototype._processPrecision = function (source) {
  26981. if (source.indexOf("precision highp float") === -1) {
  26982. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26983. source = "precision mediump float;\n" + source;
  26984. }
  26985. else {
  26986. source = "precision highp float;\n" + source;
  26987. }
  26988. }
  26989. else {
  26990. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26991. source = source.replace("precision highp float", "precision mediump float");
  26992. }
  26993. }
  26994. return source;
  26995. };
  26996. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  26997. var _this = this;
  26998. this._isReady = false;
  26999. this._vertexSourceCodeOverride = vertexSourceCode;
  27000. this._fragmentSourceCodeOverride = fragmentSourceCode;
  27001. this.onError = function (effect, error) {
  27002. if (onError) {
  27003. onError(error);
  27004. }
  27005. };
  27006. this.onCompiled = function () {
  27007. var scenes = _this.getEngine().scenes;
  27008. for (var i = 0; i < scenes.length; i++) {
  27009. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27010. }
  27011. if (onCompiled) {
  27012. onCompiled(_this._program);
  27013. }
  27014. };
  27015. this._fallbacks = null;
  27016. this._prepareEffect();
  27017. };
  27018. Effect.prototype._prepareEffect = function () {
  27019. var attributesNames = this._attributesNames;
  27020. var defines = this.defines;
  27021. var fallbacks = this._fallbacks;
  27022. this._valueCache = {};
  27023. var previousProgram = this._program;
  27024. try {
  27025. var engine = this._engine;
  27026. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  27027. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  27028. }
  27029. else {
  27030. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  27031. }
  27032. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  27033. if (engine.supportsUniformBuffers) {
  27034. for (var name in this._uniformBuffersNames) {
  27035. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  27036. }
  27037. }
  27038. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  27039. this._attributes = engine.getAttributes(this._program, attributesNames);
  27040. var index;
  27041. for (index = 0; index < this._samplers.length; index++) {
  27042. var sampler = this.getUniform(this._samplers[index]);
  27043. if (sampler == null) {
  27044. this._samplers.splice(index, 1);
  27045. index--;
  27046. }
  27047. }
  27048. engine.bindSamplers(this);
  27049. this._compilationError = "";
  27050. this._isReady = true;
  27051. if (this.onCompiled) {
  27052. this.onCompiled(this);
  27053. }
  27054. this.onCompileObservable.notifyObservers(this);
  27055. this.onCompileObservable.clear();
  27056. // Unbind mesh reference in fallbacks
  27057. if (this._fallbacks) {
  27058. this._fallbacks.unBindMesh();
  27059. }
  27060. if (previousProgram) {
  27061. this.getEngine()._deleteProgram(previousProgram);
  27062. }
  27063. }
  27064. catch (e) {
  27065. this._compilationError = e.message;
  27066. // Let's go through fallbacks then
  27067. BABYLON.Tools.Error("Unable to compile effect:");
  27068. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  27069. return " " + uniform;
  27070. }));
  27071. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  27072. return " " + attribute;
  27073. }));
  27074. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  27075. BABYLON.Tools.Error("Error: " + this._compilationError);
  27076. if (previousProgram) {
  27077. this._program = previousProgram;
  27078. this._isReady = true;
  27079. if (this.onError) {
  27080. this.onError(this, this._compilationError);
  27081. }
  27082. this.onErrorObservable.notifyObservers(this);
  27083. }
  27084. if (fallbacks && fallbacks.isMoreFallbacks) {
  27085. BABYLON.Tools.Error("Trying next fallback.");
  27086. this.defines = fallbacks.reduce(this.defines);
  27087. this._prepareEffect();
  27088. }
  27089. else {
  27090. if (this.onError) {
  27091. this.onError(this, this._compilationError);
  27092. }
  27093. this.onErrorObservable.notifyObservers(this);
  27094. this.onErrorObservable.clear();
  27095. // Unbind mesh reference in fallbacks
  27096. if (this._fallbacks) {
  27097. this._fallbacks.unBindMesh();
  27098. }
  27099. }
  27100. }
  27101. };
  27102. Object.defineProperty(Effect.prototype, "isSupported", {
  27103. get: function () {
  27104. return this._compilationError === "";
  27105. },
  27106. enumerable: true,
  27107. configurable: true
  27108. });
  27109. Effect.prototype._bindTexture = function (channel, texture) {
  27110. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  27111. };
  27112. Effect.prototype.setTexture = function (channel, texture) {
  27113. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  27114. };
  27115. Effect.prototype.setTextureArray = function (channel, textures) {
  27116. if (this._samplers.indexOf(channel + "Ex") === -1) {
  27117. var initialPos = this._samplers.indexOf(channel);
  27118. for (var index = 1; index < textures.length; index++) {
  27119. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  27120. }
  27121. }
  27122. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  27123. };
  27124. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  27125. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  27126. };
  27127. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  27128. var cache = this._valueCache[uniformName];
  27129. var flag = matrix.updateFlag;
  27130. if (cache !== undefined && cache === flag) {
  27131. return false;
  27132. }
  27133. this._valueCache[uniformName] = flag;
  27134. return true;
  27135. };
  27136. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  27137. var cache = this._valueCache[uniformName];
  27138. if (!cache) {
  27139. cache = [x, y];
  27140. this._valueCache[uniformName] = cache;
  27141. return true;
  27142. }
  27143. var changed = false;
  27144. if (cache[0] !== x) {
  27145. cache[0] = x;
  27146. changed = true;
  27147. }
  27148. if (cache[1] !== y) {
  27149. cache[1] = y;
  27150. changed = true;
  27151. }
  27152. return changed;
  27153. };
  27154. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  27155. var cache = this._valueCache[uniformName];
  27156. if (!cache) {
  27157. cache = [x, y, z];
  27158. this._valueCache[uniformName] = cache;
  27159. return true;
  27160. }
  27161. var changed = false;
  27162. if (cache[0] !== x) {
  27163. cache[0] = x;
  27164. changed = true;
  27165. }
  27166. if (cache[1] !== y) {
  27167. cache[1] = y;
  27168. changed = true;
  27169. }
  27170. if (cache[2] !== z) {
  27171. cache[2] = z;
  27172. changed = true;
  27173. }
  27174. return changed;
  27175. };
  27176. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  27177. var cache = this._valueCache[uniformName];
  27178. if (!cache) {
  27179. cache = [x, y, z, w];
  27180. this._valueCache[uniformName] = cache;
  27181. return true;
  27182. }
  27183. var changed = false;
  27184. if (cache[0] !== x) {
  27185. cache[0] = x;
  27186. changed = true;
  27187. }
  27188. if (cache[1] !== y) {
  27189. cache[1] = y;
  27190. changed = true;
  27191. }
  27192. if (cache[2] !== z) {
  27193. cache[2] = z;
  27194. changed = true;
  27195. }
  27196. if (cache[3] !== w) {
  27197. cache[3] = w;
  27198. changed = true;
  27199. }
  27200. return changed;
  27201. };
  27202. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  27203. var bufferName = this._uniformBuffersNames[name];
  27204. if (Effect._baseCache[bufferName] === buffer) {
  27205. return;
  27206. }
  27207. Effect._baseCache[bufferName] = buffer;
  27208. this._engine.bindUniformBufferBase(buffer, bufferName);
  27209. };
  27210. Effect.prototype.bindUniformBlock = function (blockName, index) {
  27211. this._engine.bindUniformBlock(this._program, blockName, index);
  27212. };
  27213. Effect.prototype.setIntArray = function (uniformName, array) {
  27214. this._valueCache[uniformName] = null;
  27215. this._engine.setIntArray(this.getUniform(uniformName), array);
  27216. return this;
  27217. };
  27218. Effect.prototype.setIntArray2 = function (uniformName, array) {
  27219. this._valueCache[uniformName] = null;
  27220. this._engine.setIntArray2(this.getUniform(uniformName), array);
  27221. return this;
  27222. };
  27223. Effect.prototype.setIntArray3 = function (uniformName, array) {
  27224. this._valueCache[uniformName] = null;
  27225. this._engine.setIntArray3(this.getUniform(uniformName), array);
  27226. return this;
  27227. };
  27228. Effect.prototype.setIntArray4 = function (uniformName, array) {
  27229. this._valueCache[uniformName] = null;
  27230. this._engine.setIntArray4(this.getUniform(uniformName), array);
  27231. return this;
  27232. };
  27233. Effect.prototype.setFloatArray = function (uniformName, array) {
  27234. this._valueCache[uniformName] = null;
  27235. this._engine.setFloatArray(this.getUniform(uniformName), array);
  27236. return this;
  27237. };
  27238. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  27239. this._valueCache[uniformName] = null;
  27240. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  27241. return this;
  27242. };
  27243. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  27244. this._valueCache[uniformName] = null;
  27245. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  27246. return this;
  27247. };
  27248. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  27249. this._valueCache[uniformName] = null;
  27250. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  27251. return this;
  27252. };
  27253. Effect.prototype.setArray = function (uniformName, array) {
  27254. this._valueCache[uniformName] = null;
  27255. this._engine.setArray(this.getUniform(uniformName), array);
  27256. return this;
  27257. };
  27258. Effect.prototype.setArray2 = function (uniformName, array) {
  27259. this._valueCache[uniformName] = null;
  27260. this._engine.setArray2(this.getUniform(uniformName), array);
  27261. return this;
  27262. };
  27263. Effect.prototype.setArray3 = function (uniformName, array) {
  27264. this._valueCache[uniformName] = null;
  27265. this._engine.setArray3(this.getUniform(uniformName), array);
  27266. return this;
  27267. };
  27268. Effect.prototype.setArray4 = function (uniformName, array) {
  27269. this._valueCache[uniformName] = null;
  27270. this._engine.setArray4(this.getUniform(uniformName), array);
  27271. return this;
  27272. };
  27273. Effect.prototype.setMatrices = function (uniformName, matrices) {
  27274. if (!matrices) {
  27275. return this;
  27276. }
  27277. this._valueCache[uniformName] = null;
  27278. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  27279. return this;
  27280. };
  27281. Effect.prototype.setMatrix = function (uniformName, matrix) {
  27282. if (this._cacheMatrix(uniformName, matrix)) {
  27283. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  27284. }
  27285. return this;
  27286. };
  27287. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  27288. this._valueCache[uniformName] = null;
  27289. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  27290. return this;
  27291. };
  27292. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  27293. this._valueCache[uniformName] = null;
  27294. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  27295. return this;
  27296. };
  27297. Effect.prototype.setFloat = function (uniformName, value) {
  27298. var cache = this._valueCache[uniformName];
  27299. if (cache !== undefined && cache === value)
  27300. return this;
  27301. this._valueCache[uniformName] = value;
  27302. this._engine.setFloat(this.getUniform(uniformName), value);
  27303. return this;
  27304. };
  27305. Effect.prototype.setBool = function (uniformName, bool) {
  27306. var cache = this._valueCache[uniformName];
  27307. if (cache !== undefined && cache === bool)
  27308. return this;
  27309. this._valueCache[uniformName] = bool;
  27310. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  27311. return this;
  27312. };
  27313. Effect.prototype.setVector2 = function (uniformName, vector2) {
  27314. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  27315. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  27316. }
  27317. return this;
  27318. };
  27319. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  27320. if (this._cacheFloat2(uniformName, x, y)) {
  27321. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  27322. }
  27323. return this;
  27324. };
  27325. Effect.prototype.setVector3 = function (uniformName, vector3) {
  27326. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  27327. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  27328. }
  27329. return this;
  27330. };
  27331. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  27332. if (this._cacheFloat3(uniformName, x, y, z)) {
  27333. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  27334. }
  27335. return this;
  27336. };
  27337. Effect.prototype.setVector4 = function (uniformName, vector4) {
  27338. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  27339. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  27340. }
  27341. return this;
  27342. };
  27343. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  27344. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  27345. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  27346. }
  27347. return this;
  27348. };
  27349. Effect.prototype.setColor3 = function (uniformName, color3) {
  27350. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  27351. this._engine.setColor3(this.getUniform(uniformName), color3);
  27352. }
  27353. return this;
  27354. };
  27355. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  27356. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  27357. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  27358. }
  27359. return this;
  27360. };
  27361. Effect.ResetCache = function () {
  27362. Effect._baseCache = {};
  27363. };
  27364. Effect._uniqueIdSeed = 0;
  27365. Effect._baseCache = {};
  27366. // Statics
  27367. Effect.ShadersStore = {};
  27368. Effect.IncludesShadersStore = {};
  27369. return Effect;
  27370. }());
  27371. BABYLON.Effect = Effect;
  27372. })(BABYLON || (BABYLON = {}));
  27373. //# sourceMappingURL=babylon.effect.js.map
  27374. var __assign = (this && this.__assign) || Object.assign || function(t) {
  27375. for (var s, i = 1, n = arguments.length; i < n; i++) {
  27376. s = arguments[i];
  27377. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  27378. t[p] = s[p];
  27379. }
  27380. return t;
  27381. };
  27382. var BABYLON;
  27383. (function (BABYLON) {
  27384. var MaterialDefines = /** @class */ (function () {
  27385. function MaterialDefines() {
  27386. this._isDirty = true;
  27387. this._areLightsDirty = true;
  27388. this._areAttributesDirty = true;
  27389. this._areTexturesDirty = true;
  27390. this._areFresnelDirty = true;
  27391. this._areMiscDirty = true;
  27392. this._areImageProcessingDirty = true;
  27393. this._normals = false;
  27394. this._uvs = false;
  27395. this._needNormals = false;
  27396. this._needUVs = false;
  27397. }
  27398. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  27399. get: function () {
  27400. return this._isDirty;
  27401. },
  27402. enumerable: true,
  27403. configurable: true
  27404. });
  27405. MaterialDefines.prototype.markAsProcessed = function () {
  27406. this._isDirty = false;
  27407. this._areAttributesDirty = false;
  27408. this._areTexturesDirty = false;
  27409. this._areFresnelDirty = false;
  27410. this._areLightsDirty = false;
  27411. this._areMiscDirty = false;
  27412. this._areImageProcessingDirty = false;
  27413. };
  27414. MaterialDefines.prototype.markAsUnprocessed = function () {
  27415. this._isDirty = true;
  27416. };
  27417. MaterialDefines.prototype.markAllAsDirty = function () {
  27418. this._areTexturesDirty = true;
  27419. this._areAttributesDirty = true;
  27420. this._areLightsDirty = true;
  27421. this._areFresnelDirty = true;
  27422. this._areMiscDirty = true;
  27423. this._areImageProcessingDirty = true;
  27424. this._isDirty = true;
  27425. };
  27426. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  27427. this._areImageProcessingDirty = true;
  27428. this._isDirty = true;
  27429. };
  27430. MaterialDefines.prototype.markAsLightDirty = function () {
  27431. this._areLightsDirty = true;
  27432. this._isDirty = true;
  27433. };
  27434. MaterialDefines.prototype.markAsAttributesDirty = function () {
  27435. this._areAttributesDirty = true;
  27436. this._isDirty = true;
  27437. };
  27438. MaterialDefines.prototype.markAsTexturesDirty = function () {
  27439. this._areTexturesDirty = true;
  27440. this._isDirty = true;
  27441. };
  27442. MaterialDefines.prototype.markAsFresnelDirty = function () {
  27443. this._areFresnelDirty = true;
  27444. this._isDirty = true;
  27445. };
  27446. MaterialDefines.prototype.markAsMiscDirty = function () {
  27447. this._areMiscDirty = true;
  27448. this._isDirty = true;
  27449. };
  27450. MaterialDefines.prototype.rebuild = function () {
  27451. if (this._keys) {
  27452. delete this._keys;
  27453. }
  27454. this._keys = [];
  27455. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  27456. var key = _a[_i];
  27457. if (key[0] === "_") {
  27458. continue;
  27459. }
  27460. this._keys.push(key);
  27461. }
  27462. };
  27463. MaterialDefines.prototype.isEqual = function (other) {
  27464. if (this._keys.length !== other._keys.length) {
  27465. return false;
  27466. }
  27467. for (var index = 0; index < this._keys.length; index++) {
  27468. var prop = this._keys[index];
  27469. if (this[prop] !== other[prop]) {
  27470. return false;
  27471. }
  27472. }
  27473. return true;
  27474. };
  27475. MaterialDefines.prototype.cloneTo = function (other) {
  27476. if (this._keys.length !== other._keys.length) {
  27477. other._keys = this._keys.slice(0);
  27478. }
  27479. for (var index = 0; index < this._keys.length; index++) {
  27480. var prop = this._keys[index];
  27481. other[prop] = this[prop];
  27482. }
  27483. };
  27484. MaterialDefines.prototype.reset = function () {
  27485. for (var index = 0; index < this._keys.length; index++) {
  27486. var prop = this._keys[index];
  27487. if (typeof (this[prop]) === "number") {
  27488. this[prop] = 0;
  27489. }
  27490. else {
  27491. this[prop] = false;
  27492. }
  27493. }
  27494. };
  27495. MaterialDefines.prototype.toString = function () {
  27496. var result = "";
  27497. for (var index = 0; index < this._keys.length; index++) {
  27498. var prop = this._keys[index];
  27499. var value = this[prop];
  27500. if (typeof (value) === "number") {
  27501. result += "#define " + prop + " " + this[prop] + "\n";
  27502. }
  27503. else if (value) {
  27504. result += "#define " + prop + "\n";
  27505. }
  27506. }
  27507. return result;
  27508. };
  27509. return MaterialDefines;
  27510. }());
  27511. BABYLON.MaterialDefines = MaterialDefines;
  27512. var Material = /** @class */ (function () {
  27513. function Material(name, scene, doNotAdd) {
  27514. this.checkReadyOnEveryCall = false;
  27515. this.checkReadyOnlyOnce = false;
  27516. this.state = "";
  27517. this.alpha = 1.0;
  27518. this._backFaceCulling = true;
  27519. this.doNotSerialize = false;
  27520. this.storeEffectOnSubMeshes = false;
  27521. /**
  27522. * An event triggered when the material is disposed.
  27523. * @type {BABYLON.Observable}
  27524. */
  27525. this.onDisposeObservable = new BABYLON.Observable();
  27526. /**
  27527. * An event triggered when the material is bound.
  27528. * @type {BABYLON.Observable}
  27529. */
  27530. this.onBindObservable = new BABYLON.Observable();
  27531. /**
  27532. * An event triggered when the material is unbound.
  27533. * @type {BABYLON.Observable}
  27534. */
  27535. this.onUnBindObservable = new BABYLON.Observable();
  27536. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  27537. this._needDepthPrePass = false;
  27538. this.disableDepthWrite = false;
  27539. this.forceDepthWrite = false;
  27540. this.separateCullingPass = false;
  27541. this._fogEnabled = true;
  27542. this.pointSize = 1.0;
  27543. this.zOffset = 0;
  27544. this._wasPreviouslyReady = false;
  27545. this._fillMode = Material.TriangleFillMode;
  27546. this.name = name;
  27547. this.id = name || BABYLON.Tools.RandomId();
  27548. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  27549. if (this._scene.useRightHandedSystem) {
  27550. this.sideOrientation = Material.ClockWiseSideOrientation;
  27551. }
  27552. else {
  27553. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  27554. }
  27555. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  27556. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  27557. if (!doNotAdd) {
  27558. this._scene.materials.push(this);
  27559. }
  27560. }
  27561. Object.defineProperty(Material, "TriangleFillMode", {
  27562. get: function () {
  27563. return Material._TriangleFillMode;
  27564. },
  27565. enumerable: true,
  27566. configurable: true
  27567. });
  27568. Object.defineProperty(Material, "WireFrameFillMode", {
  27569. get: function () {
  27570. return Material._WireFrameFillMode;
  27571. },
  27572. enumerable: true,
  27573. configurable: true
  27574. });
  27575. Object.defineProperty(Material, "PointFillMode", {
  27576. get: function () {
  27577. return Material._PointFillMode;
  27578. },
  27579. enumerable: true,
  27580. configurable: true
  27581. });
  27582. Object.defineProperty(Material, "PointListDrawMode", {
  27583. get: function () {
  27584. return Material._PointListDrawMode;
  27585. },
  27586. enumerable: true,
  27587. configurable: true
  27588. });
  27589. Object.defineProperty(Material, "LineListDrawMode", {
  27590. get: function () {
  27591. return Material._LineListDrawMode;
  27592. },
  27593. enumerable: true,
  27594. configurable: true
  27595. });
  27596. Object.defineProperty(Material, "LineLoopDrawMode", {
  27597. get: function () {
  27598. return Material._LineLoopDrawMode;
  27599. },
  27600. enumerable: true,
  27601. configurable: true
  27602. });
  27603. Object.defineProperty(Material, "LineStripDrawMode", {
  27604. get: function () {
  27605. return Material._LineStripDrawMode;
  27606. },
  27607. enumerable: true,
  27608. configurable: true
  27609. });
  27610. Object.defineProperty(Material, "TriangleStripDrawMode", {
  27611. get: function () {
  27612. return Material._TriangleStripDrawMode;
  27613. },
  27614. enumerable: true,
  27615. configurable: true
  27616. });
  27617. Object.defineProperty(Material, "TriangleFanDrawMode", {
  27618. get: function () {
  27619. return Material._TriangleFanDrawMode;
  27620. },
  27621. enumerable: true,
  27622. configurable: true
  27623. });
  27624. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  27625. get: function () {
  27626. return Material._ClockWiseSideOrientation;
  27627. },
  27628. enumerable: true,
  27629. configurable: true
  27630. });
  27631. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  27632. get: function () {
  27633. return Material._CounterClockWiseSideOrientation;
  27634. },
  27635. enumerable: true,
  27636. configurable: true
  27637. });
  27638. Object.defineProperty(Material, "TextureDirtyFlag", {
  27639. get: function () {
  27640. return Material._TextureDirtyFlag;
  27641. },
  27642. enumerable: true,
  27643. configurable: true
  27644. });
  27645. Object.defineProperty(Material, "LightDirtyFlag", {
  27646. get: function () {
  27647. return Material._LightDirtyFlag;
  27648. },
  27649. enumerable: true,
  27650. configurable: true
  27651. });
  27652. Object.defineProperty(Material, "FresnelDirtyFlag", {
  27653. get: function () {
  27654. return Material._FresnelDirtyFlag;
  27655. },
  27656. enumerable: true,
  27657. configurable: true
  27658. });
  27659. Object.defineProperty(Material, "AttributesDirtyFlag", {
  27660. get: function () {
  27661. return Material._AttributesDirtyFlag;
  27662. },
  27663. enumerable: true,
  27664. configurable: true
  27665. });
  27666. Object.defineProperty(Material, "MiscDirtyFlag", {
  27667. get: function () {
  27668. return Material._MiscDirtyFlag;
  27669. },
  27670. enumerable: true,
  27671. configurable: true
  27672. });
  27673. Object.defineProperty(Material.prototype, "backFaceCulling", {
  27674. get: function () {
  27675. return this._backFaceCulling;
  27676. },
  27677. set: function (value) {
  27678. if (this._backFaceCulling === value) {
  27679. return;
  27680. }
  27681. this._backFaceCulling = value;
  27682. this.markAsDirty(Material.TextureDirtyFlag);
  27683. },
  27684. enumerable: true,
  27685. configurable: true
  27686. });
  27687. Object.defineProperty(Material.prototype, "onDispose", {
  27688. set: function (callback) {
  27689. if (this._onDisposeObserver) {
  27690. this.onDisposeObservable.remove(this._onDisposeObserver);
  27691. }
  27692. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27693. },
  27694. enumerable: true,
  27695. configurable: true
  27696. });
  27697. Object.defineProperty(Material.prototype, "onBind", {
  27698. set: function (callback) {
  27699. if (this._onBindObserver) {
  27700. this.onBindObservable.remove(this._onBindObserver);
  27701. }
  27702. this._onBindObserver = this.onBindObservable.add(callback);
  27703. },
  27704. enumerable: true,
  27705. configurable: true
  27706. });
  27707. Object.defineProperty(Material.prototype, "alphaMode", {
  27708. get: function () {
  27709. return this._alphaMode;
  27710. },
  27711. set: function (value) {
  27712. if (this._alphaMode === value) {
  27713. return;
  27714. }
  27715. this._alphaMode = value;
  27716. this.markAsDirty(Material.TextureDirtyFlag);
  27717. },
  27718. enumerable: true,
  27719. configurable: true
  27720. });
  27721. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  27722. get: function () {
  27723. return this._needDepthPrePass;
  27724. },
  27725. set: function (value) {
  27726. if (this._needDepthPrePass === value) {
  27727. return;
  27728. }
  27729. this._needDepthPrePass = value;
  27730. if (this._needDepthPrePass) {
  27731. this.checkReadyOnEveryCall = true;
  27732. }
  27733. },
  27734. enumerable: true,
  27735. configurable: true
  27736. });
  27737. Object.defineProperty(Material.prototype, "fogEnabled", {
  27738. get: function () {
  27739. return this._fogEnabled;
  27740. },
  27741. set: function (value) {
  27742. if (this._fogEnabled === value) {
  27743. return;
  27744. }
  27745. this._fogEnabled = value;
  27746. this.markAsDirty(Material.MiscDirtyFlag);
  27747. },
  27748. enumerable: true,
  27749. configurable: true
  27750. });
  27751. Object.defineProperty(Material.prototype, "wireframe", {
  27752. get: function () {
  27753. return this._fillMode === Material.WireFrameFillMode;
  27754. },
  27755. set: function (value) {
  27756. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  27757. },
  27758. enumerable: true,
  27759. configurable: true
  27760. });
  27761. Object.defineProperty(Material.prototype, "pointsCloud", {
  27762. get: function () {
  27763. return this._fillMode === Material.PointFillMode;
  27764. },
  27765. set: function (value) {
  27766. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  27767. },
  27768. enumerable: true,
  27769. configurable: true
  27770. });
  27771. Object.defineProperty(Material.prototype, "fillMode", {
  27772. get: function () {
  27773. return this._fillMode;
  27774. },
  27775. set: function (value) {
  27776. if (this._fillMode === value) {
  27777. return;
  27778. }
  27779. this._fillMode = value;
  27780. this.markAsDirty(Material.MiscDirtyFlag);
  27781. },
  27782. enumerable: true,
  27783. configurable: true
  27784. });
  27785. /**
  27786. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27787. * subclasses should override adding information pertainent to themselves
  27788. */
  27789. Material.prototype.toString = function (fullDetails) {
  27790. var ret = "Name: " + this.name;
  27791. if (fullDetails) {
  27792. }
  27793. return ret;
  27794. };
  27795. /**
  27796. * Child classes can use it to update shaders
  27797. */
  27798. Material.prototype.getClassName = function () {
  27799. return "Material";
  27800. };
  27801. Object.defineProperty(Material.prototype, "isFrozen", {
  27802. get: function () {
  27803. return this.checkReadyOnlyOnce;
  27804. },
  27805. enumerable: true,
  27806. configurable: true
  27807. });
  27808. Material.prototype.freeze = function () {
  27809. this.checkReadyOnlyOnce = true;
  27810. };
  27811. Material.prototype.unfreeze = function () {
  27812. this.checkReadyOnlyOnce = false;
  27813. };
  27814. Material.prototype.isReady = function (mesh, useInstances) {
  27815. return true;
  27816. };
  27817. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  27818. return false;
  27819. };
  27820. Material.prototype.getEffect = function () {
  27821. return this._effect;
  27822. };
  27823. Material.prototype.getScene = function () {
  27824. return this._scene;
  27825. };
  27826. Material.prototype.needAlphaBlending = function () {
  27827. return (this.alpha < 1.0);
  27828. };
  27829. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  27830. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  27831. };
  27832. Material.prototype.needAlphaTesting = function () {
  27833. return false;
  27834. };
  27835. Material.prototype.getAlphaTestTexture = function () {
  27836. return null;
  27837. };
  27838. Material.prototype.markDirty = function () {
  27839. this._wasPreviouslyReady = false;
  27840. };
  27841. Material.prototype._preBind = function (effect, overrideOrientation) {
  27842. if (overrideOrientation === void 0) { overrideOrientation = null; }
  27843. var engine = this._scene.getEngine();
  27844. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  27845. var reverse = orientation === Material.ClockWiseSideOrientation;
  27846. engine.enableEffect(effect ? effect : this._effect);
  27847. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  27848. return reverse;
  27849. };
  27850. Material.prototype.bind = function (world, mesh) {
  27851. };
  27852. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  27853. };
  27854. Material.prototype.bindOnlyWorldMatrix = function (world) {
  27855. };
  27856. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  27857. sceneUbo.bindToEffect(effect, "Scene");
  27858. };
  27859. Material.prototype.bindView = function (effect) {
  27860. if (!this._useUBO) {
  27861. effect.setMatrix("view", this.getScene().getViewMatrix());
  27862. }
  27863. else {
  27864. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27865. }
  27866. };
  27867. Material.prototype.bindViewProjection = function (effect) {
  27868. if (!this._useUBO) {
  27869. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  27870. }
  27871. else {
  27872. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27873. }
  27874. };
  27875. Material.prototype._afterBind = function (mesh) {
  27876. this._scene._cachedMaterial = this;
  27877. if (mesh) {
  27878. this._scene._cachedVisibility = mesh.visibility;
  27879. }
  27880. else {
  27881. this._scene._cachedVisibility = 1;
  27882. }
  27883. if (mesh) {
  27884. this.onBindObservable.notifyObservers(mesh);
  27885. }
  27886. if (this.disableDepthWrite) {
  27887. var engine = this._scene.getEngine();
  27888. this._cachedDepthWriteState = engine.getDepthWrite();
  27889. engine.setDepthWrite(false);
  27890. }
  27891. };
  27892. Material.prototype.unbind = function () {
  27893. this.onUnBindObservable.notifyObservers(this);
  27894. if (this.disableDepthWrite) {
  27895. var engine = this._scene.getEngine();
  27896. engine.setDepthWrite(this._cachedDepthWriteState);
  27897. }
  27898. };
  27899. Material.prototype.getActiveTextures = function () {
  27900. return [];
  27901. };
  27902. Material.prototype.hasTexture = function (texture) {
  27903. return false;
  27904. };
  27905. Material.prototype.clone = function (name) {
  27906. return null;
  27907. };
  27908. Material.prototype.getBindedMeshes = function () {
  27909. var result = new Array();
  27910. for (var index = 0; index < this._scene.meshes.length; index++) {
  27911. var mesh = this._scene.meshes[index];
  27912. if (mesh.material === this) {
  27913. result.push(mesh);
  27914. }
  27915. }
  27916. return result;
  27917. };
  27918. /**
  27919. * Force shader compilation including textures ready check
  27920. */
  27921. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  27922. var _this = this;
  27923. var localOptions = __assign({ alphaTest: null, clipPlane: false }, options);
  27924. var subMesh = new BABYLON.BaseSubMesh();
  27925. var scene = this.getScene();
  27926. var engine = scene.getEngine();
  27927. var checkReady = function () {
  27928. if (!_this._scene || !_this._scene.getEngine()) {
  27929. return;
  27930. }
  27931. if (subMesh._materialDefines) {
  27932. subMesh._materialDefines._renderId = -1;
  27933. }
  27934. var alphaTestState = engine.getAlphaTesting();
  27935. var clipPlaneState = scene.clipPlane;
  27936. engine.setAlphaTesting(localOptions.alphaTest || (!_this.needAlphaBlendingForMesh(mesh) && _this.needAlphaTesting()));
  27937. if (localOptions.clipPlane) {
  27938. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  27939. }
  27940. if (_this.storeEffectOnSubMeshes) {
  27941. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  27942. if (onCompiled) {
  27943. onCompiled(_this);
  27944. }
  27945. }
  27946. else {
  27947. setTimeout(checkReady, 16);
  27948. }
  27949. }
  27950. else {
  27951. if (_this.isReady(mesh)) {
  27952. if (onCompiled) {
  27953. onCompiled(_this);
  27954. }
  27955. }
  27956. else {
  27957. setTimeout(checkReady, 16);
  27958. }
  27959. }
  27960. engine.setAlphaTesting(alphaTestState);
  27961. if (options && options.clipPlane) {
  27962. scene.clipPlane = clipPlaneState;
  27963. }
  27964. };
  27965. checkReady();
  27966. };
  27967. Material.prototype.markAsDirty = function (flag) {
  27968. if (flag & Material.TextureDirtyFlag) {
  27969. this._markAllSubMeshesAsTexturesDirty();
  27970. }
  27971. if (flag & Material.LightDirtyFlag) {
  27972. this._markAllSubMeshesAsLightsDirty();
  27973. }
  27974. if (flag & Material.FresnelDirtyFlag) {
  27975. this._markAllSubMeshesAsFresnelDirty();
  27976. }
  27977. if (flag & Material.AttributesDirtyFlag) {
  27978. this._markAllSubMeshesAsAttributesDirty();
  27979. }
  27980. if (flag & Material.MiscDirtyFlag) {
  27981. this._markAllSubMeshesAsMiscDirty();
  27982. }
  27983. this.getScene().resetCachedMaterial();
  27984. };
  27985. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  27986. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  27987. var mesh = _a[_i];
  27988. if (!mesh.subMeshes) {
  27989. continue;
  27990. }
  27991. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  27992. var subMesh = _c[_b];
  27993. if (subMesh.getMaterial() !== this) {
  27994. continue;
  27995. }
  27996. if (!subMesh._materialDefines) {
  27997. continue;
  27998. }
  27999. func(subMesh._materialDefines);
  28000. }
  28001. }
  28002. };
  28003. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  28004. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  28005. };
  28006. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  28007. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  28008. };
  28009. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  28010. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  28011. };
  28012. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  28013. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  28014. };
  28015. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  28016. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  28017. };
  28018. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  28019. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  28020. };
  28021. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  28022. // Animations
  28023. this.getScene().stopAnimation(this);
  28024. // Remove from scene
  28025. var index = this._scene.materials.indexOf(this);
  28026. if (index >= 0) {
  28027. this._scene.materials.splice(index, 1);
  28028. }
  28029. // Remove from meshes
  28030. for (index = 0; index < this._scene.meshes.length; index++) {
  28031. var mesh = this._scene.meshes[index];
  28032. if (mesh.material === this) {
  28033. mesh.material = null;
  28034. if (mesh.geometry) {
  28035. var geometry = (mesh.geometry);
  28036. if (this.storeEffectOnSubMeshes) {
  28037. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  28038. var subMesh = _a[_i];
  28039. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  28040. if (forceDisposeEffect && subMesh._materialEffect) {
  28041. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  28042. }
  28043. }
  28044. }
  28045. else {
  28046. geometry._releaseVertexArrayObject(this._effect);
  28047. }
  28048. }
  28049. }
  28050. }
  28051. this._uniformBuffer.dispose();
  28052. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  28053. if (forceDisposeEffect && this._effect) {
  28054. if (!this.storeEffectOnSubMeshes) {
  28055. this._scene.getEngine()._releaseEffect(this._effect);
  28056. }
  28057. this._effect = null;
  28058. }
  28059. // Callback
  28060. this.onDisposeObservable.notifyObservers(this);
  28061. this.onDisposeObservable.clear();
  28062. this.onBindObservable.clear();
  28063. this.onUnBindObservable.clear();
  28064. };
  28065. Material.prototype.serialize = function () {
  28066. return BABYLON.SerializationHelper.Serialize(this);
  28067. };
  28068. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  28069. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  28070. multiMaterial.id = parsedMultiMaterial.id;
  28071. if (BABYLON.Tags) {
  28072. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  28073. }
  28074. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  28075. var subMatId = parsedMultiMaterial.materials[matIndex];
  28076. if (subMatId) {
  28077. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  28078. }
  28079. else {
  28080. multiMaterial.subMaterials.push(null);
  28081. }
  28082. }
  28083. return multiMaterial;
  28084. };
  28085. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  28086. if (!parsedMaterial.customType) {
  28087. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  28088. }
  28089. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  28090. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  28091. if (!BABYLON.LegacyPBRMaterial) {
  28092. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  28093. return;
  28094. }
  28095. }
  28096. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  28097. return materialType.Parse(parsedMaterial, scene, rootUrl);
  28098. ;
  28099. };
  28100. // Triangle views
  28101. Material._TriangleFillMode = 0;
  28102. Material._WireFrameFillMode = 1;
  28103. Material._PointFillMode = 2;
  28104. // Draw modes
  28105. Material._PointListDrawMode = 3;
  28106. Material._LineListDrawMode = 4;
  28107. Material._LineLoopDrawMode = 5;
  28108. Material._LineStripDrawMode = 6;
  28109. Material._TriangleStripDrawMode = 7;
  28110. Material._TriangleFanDrawMode = 8;
  28111. Material._ClockWiseSideOrientation = 0;
  28112. Material._CounterClockWiseSideOrientation = 1;
  28113. Material._TextureDirtyFlag = 1;
  28114. Material._LightDirtyFlag = 2;
  28115. Material._FresnelDirtyFlag = 4;
  28116. Material._AttributesDirtyFlag = 8;
  28117. Material._MiscDirtyFlag = 16;
  28118. __decorate([
  28119. BABYLON.serialize()
  28120. ], Material.prototype, "id", void 0);
  28121. __decorate([
  28122. BABYLON.serialize()
  28123. ], Material.prototype, "name", void 0);
  28124. __decorate([
  28125. BABYLON.serialize()
  28126. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  28127. __decorate([
  28128. BABYLON.serialize()
  28129. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  28130. __decorate([
  28131. BABYLON.serialize()
  28132. ], Material.prototype, "state", void 0);
  28133. __decorate([
  28134. BABYLON.serialize()
  28135. ], Material.prototype, "alpha", void 0);
  28136. __decorate([
  28137. BABYLON.serialize("backFaceCulling")
  28138. ], Material.prototype, "_backFaceCulling", void 0);
  28139. __decorate([
  28140. BABYLON.serialize()
  28141. ], Material.prototype, "sideOrientation", void 0);
  28142. __decorate([
  28143. BABYLON.serialize("alphaMode")
  28144. ], Material.prototype, "_alphaMode", void 0);
  28145. __decorate([
  28146. BABYLON.serialize()
  28147. ], Material.prototype, "_needDepthPrePass", void 0);
  28148. __decorate([
  28149. BABYLON.serialize()
  28150. ], Material.prototype, "disableDepthWrite", void 0);
  28151. __decorate([
  28152. BABYLON.serialize()
  28153. ], Material.prototype, "forceDepthWrite", void 0);
  28154. __decorate([
  28155. BABYLON.serialize()
  28156. ], Material.prototype, "separateCullingPass", void 0);
  28157. __decorate([
  28158. BABYLON.serialize("fogEnabled")
  28159. ], Material.prototype, "_fogEnabled", void 0);
  28160. __decorate([
  28161. BABYLON.serialize()
  28162. ], Material.prototype, "pointSize", void 0);
  28163. __decorate([
  28164. BABYLON.serialize()
  28165. ], Material.prototype, "zOffset", void 0);
  28166. __decorate([
  28167. BABYLON.serialize()
  28168. ], Material.prototype, "wireframe", null);
  28169. __decorate([
  28170. BABYLON.serialize()
  28171. ], Material.prototype, "pointsCloud", null);
  28172. __decorate([
  28173. BABYLON.serialize()
  28174. ], Material.prototype, "fillMode", null);
  28175. return Material;
  28176. }());
  28177. BABYLON.Material = Material;
  28178. })(BABYLON || (BABYLON = {}));
  28179. //# sourceMappingURL=babylon.material.js.map
  28180. var BABYLON;
  28181. (function (BABYLON) {
  28182. var UniformBuffer = /** @class */ (function () {
  28183. /**
  28184. * Uniform buffer objects.
  28185. *
  28186. * Handles blocks of uniform on the GPU.
  28187. *
  28188. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  28189. *
  28190. * For more information, please refer to :
  28191. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  28192. */
  28193. function UniformBuffer(engine, data, dynamic) {
  28194. this._engine = engine;
  28195. this._noUBO = !engine.supportsUniformBuffers;
  28196. this._dynamic = dynamic;
  28197. this._data = data || [];
  28198. this._uniformLocations = {};
  28199. this._uniformSizes = {};
  28200. this._uniformLocationPointer = 0;
  28201. this._needSync = false;
  28202. if (this._noUBO) {
  28203. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  28204. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  28205. this.updateFloat = this._updateFloatForEffect;
  28206. this.updateFloat2 = this._updateFloat2ForEffect;
  28207. this.updateFloat3 = this._updateFloat3ForEffect;
  28208. this.updateFloat4 = this._updateFloat4ForEffect;
  28209. this.updateMatrix = this._updateMatrixForEffect;
  28210. this.updateVector3 = this._updateVector3ForEffect;
  28211. this.updateVector4 = this._updateVector4ForEffect;
  28212. this.updateColor3 = this._updateColor3ForEffect;
  28213. this.updateColor4 = this._updateColor4ForEffect;
  28214. }
  28215. else {
  28216. this._engine._uniformBuffers.push(this);
  28217. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  28218. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  28219. this.updateFloat = this._updateFloatForUniform;
  28220. this.updateFloat2 = this._updateFloat2ForUniform;
  28221. this.updateFloat3 = this._updateFloat3ForUniform;
  28222. this.updateFloat4 = this._updateFloat4ForUniform;
  28223. this.updateMatrix = this._updateMatrixForUniform;
  28224. this.updateVector3 = this._updateVector3ForUniform;
  28225. this.updateVector4 = this._updateVector4ForUniform;
  28226. this.updateColor3 = this._updateColor3ForUniform;
  28227. this.updateColor4 = this._updateColor4ForUniform;
  28228. }
  28229. }
  28230. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  28231. // Properties
  28232. /**
  28233. * Indicates if the buffer is using the WebGL2 UBO implementation,
  28234. * or just falling back on setUniformXXX calls.
  28235. */
  28236. get: function () {
  28237. return !this._noUBO;
  28238. },
  28239. enumerable: true,
  28240. configurable: true
  28241. });
  28242. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  28243. /**
  28244. * Indicates if the WebGL underlying uniform buffer is in sync
  28245. * with the javascript cache data.
  28246. */
  28247. get: function () {
  28248. return !this._needSync;
  28249. },
  28250. enumerable: true,
  28251. configurable: true
  28252. });
  28253. /**
  28254. * Indicates if the WebGL underlying uniform buffer is dynamic.
  28255. * Also, a dynamic UniformBuffer will disable cache verification and always
  28256. * update the underlying WebGL uniform buffer to the GPU.
  28257. */
  28258. UniformBuffer.prototype.isDynamic = function () {
  28259. return this._dynamic !== undefined;
  28260. };
  28261. /**
  28262. * The data cache on JS side.
  28263. */
  28264. UniformBuffer.prototype.getData = function () {
  28265. return this._bufferData;
  28266. };
  28267. /**
  28268. * The underlying WebGL Uniform buffer.
  28269. */
  28270. UniformBuffer.prototype.getBuffer = function () {
  28271. return this._buffer;
  28272. };
  28273. /**
  28274. * std140 layout specifies how to align data within an UBO structure.
  28275. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  28276. * for specs.
  28277. */
  28278. UniformBuffer.prototype._fillAlignment = function (size) {
  28279. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  28280. // and 4x4 matrices
  28281. // TODO : change if other types are used
  28282. var alignment;
  28283. if (size <= 2) {
  28284. alignment = size;
  28285. }
  28286. else {
  28287. alignment = 4;
  28288. }
  28289. if ((this._uniformLocationPointer % alignment) !== 0) {
  28290. var oldPointer = this._uniformLocationPointer;
  28291. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  28292. var diff = this._uniformLocationPointer - oldPointer;
  28293. for (var i = 0; i < diff; i++) {
  28294. this._data.push(0);
  28295. }
  28296. }
  28297. };
  28298. /**
  28299. * Adds an uniform in the buffer.
  28300. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  28301. * for the layout to be correct !
  28302. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28303. * @param {number|number[]} size Data size, or data directly.
  28304. */
  28305. UniformBuffer.prototype.addUniform = function (name, size) {
  28306. if (this._noUBO) {
  28307. return;
  28308. }
  28309. if (this._uniformLocations[name] !== undefined) {
  28310. // Already existing uniform
  28311. return;
  28312. }
  28313. // This function must be called in the order of the shader layout !
  28314. // size can be the size of the uniform, or data directly
  28315. var data;
  28316. if (size instanceof Array) {
  28317. data = size;
  28318. size = data.length;
  28319. }
  28320. else {
  28321. size = size;
  28322. data = [];
  28323. // Fill with zeros
  28324. for (var i = 0; i < size; i++) {
  28325. data.push(0);
  28326. }
  28327. }
  28328. this._fillAlignment(size);
  28329. this._uniformSizes[name] = size;
  28330. this._uniformLocations[name] = this._uniformLocationPointer;
  28331. this._uniformLocationPointer += size;
  28332. for (var i = 0; i < size; i++) {
  28333. this._data.push(data[i]);
  28334. }
  28335. this._needSync = true;
  28336. };
  28337. /**
  28338. * Wrapper for addUniform.
  28339. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28340. * @param {Matrix} mat A 4x4 matrix.
  28341. */
  28342. UniformBuffer.prototype.addMatrix = function (name, mat) {
  28343. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  28344. };
  28345. /**
  28346. * Wrapper for addUniform.
  28347. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28348. * @param {number} x
  28349. * @param {number} y
  28350. */
  28351. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  28352. var temp = [x, y];
  28353. this.addUniform(name, temp);
  28354. };
  28355. /**
  28356. * Wrapper for addUniform.
  28357. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28358. * @param {number} x
  28359. * @param {number} y
  28360. * @param {number} z
  28361. */
  28362. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  28363. var temp = [x, y, z];
  28364. this.addUniform(name, temp);
  28365. };
  28366. /**
  28367. * Wrapper for addUniform.
  28368. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28369. * @param {Color3} color
  28370. */
  28371. UniformBuffer.prototype.addColor3 = function (name, color) {
  28372. var temp = new Array();
  28373. color.toArray(temp);
  28374. this.addUniform(name, temp);
  28375. };
  28376. /**
  28377. * Wrapper for addUniform.
  28378. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28379. * @param {Color3} color
  28380. * @param {number} alpha
  28381. */
  28382. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  28383. var temp = new Array();
  28384. color.toArray(temp);
  28385. temp.push(alpha);
  28386. this.addUniform(name, temp);
  28387. };
  28388. /**
  28389. * Wrapper for addUniform.
  28390. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28391. * @param {Vector3} vector
  28392. */
  28393. UniformBuffer.prototype.addVector3 = function (name, vector) {
  28394. var temp = new Array();
  28395. vector.toArray(temp);
  28396. this.addUniform(name, temp);
  28397. };
  28398. /**
  28399. * Wrapper for addUniform.
  28400. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28401. */
  28402. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  28403. this.addUniform(name, 12);
  28404. };
  28405. /**
  28406. * Wrapper for addUniform.
  28407. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28408. */
  28409. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  28410. this.addUniform(name, 8);
  28411. };
  28412. /**
  28413. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  28414. */
  28415. UniformBuffer.prototype.create = function () {
  28416. if (this._noUBO) {
  28417. return;
  28418. }
  28419. if (this._buffer) {
  28420. return; // nothing to do
  28421. }
  28422. // See spec, alignment must be filled as a vec4
  28423. this._fillAlignment(4);
  28424. this._bufferData = new Float32Array(this._data);
  28425. this._rebuild();
  28426. this._needSync = true;
  28427. };
  28428. UniformBuffer.prototype._rebuild = function () {
  28429. if (this._noUBO) {
  28430. return;
  28431. }
  28432. if (this._dynamic) {
  28433. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  28434. }
  28435. else {
  28436. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  28437. }
  28438. };
  28439. /**
  28440. * Updates the WebGL Uniform Buffer on the GPU.
  28441. * If the `dynamic` flag is set to true, no cache comparison is done.
  28442. * Otherwise, the buffer will be updated only if the cache differs.
  28443. */
  28444. UniformBuffer.prototype.update = function () {
  28445. if (!this._buffer) {
  28446. this.create();
  28447. return;
  28448. }
  28449. if (!this._dynamic && !this._needSync) {
  28450. return;
  28451. }
  28452. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  28453. this._needSync = false;
  28454. };
  28455. /**
  28456. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  28457. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  28458. * @param {number[]|Float32Array} data Flattened data
  28459. * @param {number} size Size of the data.
  28460. */
  28461. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  28462. var location = this._uniformLocations[uniformName];
  28463. if (location === undefined) {
  28464. if (this._buffer) {
  28465. // Cannot add an uniform if the buffer is already created
  28466. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  28467. return;
  28468. }
  28469. this.addUniform(uniformName, size);
  28470. location = this._uniformLocations[uniformName];
  28471. }
  28472. if (!this._buffer) {
  28473. this.create();
  28474. }
  28475. if (!this._dynamic) {
  28476. // Cache for static uniform buffers
  28477. var changed = false;
  28478. for (var i = 0; i < size; i++) {
  28479. if (this._bufferData[location + i] !== data[i]) {
  28480. changed = true;
  28481. this._bufferData[location + i] = data[i];
  28482. }
  28483. }
  28484. this._needSync = this._needSync || changed;
  28485. }
  28486. else {
  28487. // No cache for dynamic
  28488. for (var i = 0; i < size; i++) {
  28489. this._bufferData[location + i] = data[i];
  28490. }
  28491. }
  28492. };
  28493. // Update methods
  28494. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  28495. // To match std140, matrix must be realigned
  28496. for (var i = 0; i < 3; i++) {
  28497. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  28498. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  28499. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  28500. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  28501. }
  28502. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  28503. };
  28504. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  28505. this._currentEffect.setMatrix3x3(name, matrix);
  28506. };
  28507. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  28508. this._currentEffect.setMatrix2x2(name, matrix);
  28509. };
  28510. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  28511. // To match std140, matrix must be realigned
  28512. for (var i = 0; i < 2; i++) {
  28513. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  28514. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  28515. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  28516. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  28517. }
  28518. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  28519. };
  28520. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  28521. this._currentEffect.setFloat(name, x);
  28522. };
  28523. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  28524. UniformBuffer._tempBuffer[0] = x;
  28525. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  28526. };
  28527. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  28528. if (suffix === void 0) { suffix = ""; }
  28529. this._currentEffect.setFloat2(name + suffix, x, y);
  28530. };
  28531. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  28532. if (suffix === void 0) { suffix = ""; }
  28533. UniformBuffer._tempBuffer[0] = x;
  28534. UniformBuffer._tempBuffer[1] = y;
  28535. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  28536. };
  28537. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  28538. if (suffix === void 0) { suffix = ""; }
  28539. this._currentEffect.setFloat3(name + suffix, x, y, z);
  28540. };
  28541. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  28542. if (suffix === void 0) { suffix = ""; }
  28543. UniformBuffer._tempBuffer[0] = x;
  28544. UniformBuffer._tempBuffer[1] = y;
  28545. UniformBuffer._tempBuffer[2] = z;
  28546. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28547. };
  28548. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  28549. if (suffix === void 0) { suffix = ""; }
  28550. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  28551. };
  28552. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  28553. if (suffix === void 0) { suffix = ""; }
  28554. UniformBuffer._tempBuffer[0] = x;
  28555. UniformBuffer._tempBuffer[1] = y;
  28556. UniformBuffer._tempBuffer[2] = z;
  28557. UniformBuffer._tempBuffer[3] = w;
  28558. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28559. };
  28560. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  28561. this._currentEffect.setMatrix(name, mat);
  28562. };
  28563. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  28564. this.updateUniform(name, mat.toArray(), 16);
  28565. };
  28566. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  28567. this._currentEffect.setVector3(name, vector);
  28568. };
  28569. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  28570. vector.toArray(UniformBuffer._tempBuffer);
  28571. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28572. };
  28573. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  28574. this._currentEffect.setVector4(name, vector);
  28575. };
  28576. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  28577. vector.toArray(UniformBuffer._tempBuffer);
  28578. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28579. };
  28580. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  28581. if (suffix === void 0) { suffix = ""; }
  28582. this._currentEffect.setColor3(name + suffix, color);
  28583. };
  28584. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  28585. if (suffix === void 0) { suffix = ""; }
  28586. color.toArray(UniformBuffer._tempBuffer);
  28587. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28588. };
  28589. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  28590. if (suffix === void 0) { suffix = ""; }
  28591. this._currentEffect.setColor4(name + suffix, color, alpha);
  28592. };
  28593. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  28594. if (suffix === void 0) { suffix = ""; }
  28595. color.toArray(UniformBuffer._tempBuffer);
  28596. UniformBuffer._tempBuffer[3] = alpha;
  28597. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28598. };
  28599. /**
  28600. * Sets a sampler uniform on the effect.
  28601. * @param {string} name Name of the sampler.
  28602. * @param {Texture} texture
  28603. */
  28604. UniformBuffer.prototype.setTexture = function (name, texture) {
  28605. this._currentEffect.setTexture(name, texture);
  28606. };
  28607. /**
  28608. * Directly updates the value of the uniform in the cache AND on the GPU.
  28609. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  28610. * @param {number[]|Float32Array} data Flattened data
  28611. */
  28612. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  28613. this.updateUniform(uniformName, data, data.length);
  28614. this.update();
  28615. };
  28616. /**
  28617. * Binds this uniform buffer to an effect.
  28618. * @param {Effect} effect
  28619. * @param {string} name Name of the uniform block in the shader.
  28620. */
  28621. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  28622. this._currentEffect = effect;
  28623. if (this._noUBO || !this._buffer) {
  28624. return;
  28625. }
  28626. effect.bindUniformBuffer(this._buffer, name);
  28627. };
  28628. /**
  28629. * Disposes the uniform buffer.
  28630. */
  28631. UniformBuffer.prototype.dispose = function () {
  28632. if (this._noUBO) {
  28633. return;
  28634. }
  28635. var index = this._engine._uniformBuffers.indexOf(this);
  28636. if (index !== -1) {
  28637. this._engine._uniformBuffers.splice(index, 1);
  28638. }
  28639. if (!this._buffer) {
  28640. return;
  28641. }
  28642. if (this._engine._releaseBuffer(this._buffer)) {
  28643. this._buffer = null;
  28644. }
  28645. };
  28646. // Pool for avoiding memory leaks
  28647. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  28648. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  28649. return UniformBuffer;
  28650. }());
  28651. BABYLON.UniformBuffer = UniformBuffer;
  28652. })(BABYLON || (BABYLON = {}));
  28653. //# sourceMappingURL=babylon.uniformBuffer.js.map
  28654. var BABYLON;
  28655. (function (BABYLON) {
  28656. var VertexData = /** @class */ (function () {
  28657. function VertexData() {
  28658. }
  28659. VertexData.prototype.set = function (data, kind) {
  28660. switch (kind) {
  28661. case BABYLON.VertexBuffer.PositionKind:
  28662. this.positions = data;
  28663. break;
  28664. case BABYLON.VertexBuffer.NormalKind:
  28665. this.normals = data;
  28666. break;
  28667. case BABYLON.VertexBuffer.TangentKind:
  28668. this.tangents = data;
  28669. break;
  28670. case BABYLON.VertexBuffer.UVKind:
  28671. this.uvs = data;
  28672. break;
  28673. case BABYLON.VertexBuffer.UV2Kind:
  28674. this.uvs2 = data;
  28675. break;
  28676. case BABYLON.VertexBuffer.UV3Kind:
  28677. this.uvs3 = data;
  28678. break;
  28679. case BABYLON.VertexBuffer.UV4Kind:
  28680. this.uvs4 = data;
  28681. break;
  28682. case BABYLON.VertexBuffer.UV5Kind:
  28683. this.uvs5 = data;
  28684. break;
  28685. case BABYLON.VertexBuffer.UV6Kind:
  28686. this.uvs6 = data;
  28687. break;
  28688. case BABYLON.VertexBuffer.ColorKind:
  28689. this.colors = data;
  28690. break;
  28691. case BABYLON.VertexBuffer.MatricesIndicesKind:
  28692. this.matricesIndices = data;
  28693. break;
  28694. case BABYLON.VertexBuffer.MatricesWeightsKind:
  28695. this.matricesWeights = data;
  28696. break;
  28697. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  28698. this.matricesIndicesExtra = data;
  28699. break;
  28700. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  28701. this.matricesWeightsExtra = data;
  28702. break;
  28703. }
  28704. };
  28705. /**
  28706. * Associates the vertexData to the passed Mesh.
  28707. * Sets it as updatable or not (default `false`).
  28708. * Returns the VertexData.
  28709. */
  28710. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  28711. this._applyTo(mesh, updatable);
  28712. return this;
  28713. };
  28714. /**
  28715. * Associates the vertexData to the passed Geometry.
  28716. * Sets it as updatable or not (default `false`).
  28717. * Returns the VertexData.
  28718. */
  28719. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  28720. this._applyTo(geometry, updatable);
  28721. return this;
  28722. };
  28723. /**
  28724. * Updates the associated mesh.
  28725. * Returns the VertexData.
  28726. */
  28727. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  28728. this._update(mesh);
  28729. return this;
  28730. };
  28731. /**
  28732. * Updates the associated geometry.
  28733. * Returns the VertexData.
  28734. */
  28735. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  28736. this._update(geometry);
  28737. return this;
  28738. };
  28739. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  28740. if (updatable === void 0) { updatable = false; }
  28741. if (this.positions) {
  28742. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  28743. }
  28744. if (this.normals) {
  28745. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  28746. }
  28747. if (this.tangents) {
  28748. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  28749. }
  28750. if (this.uvs) {
  28751. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  28752. }
  28753. if (this.uvs2) {
  28754. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  28755. }
  28756. if (this.uvs3) {
  28757. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  28758. }
  28759. if (this.uvs4) {
  28760. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  28761. }
  28762. if (this.uvs5) {
  28763. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  28764. }
  28765. if (this.uvs6) {
  28766. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  28767. }
  28768. if (this.colors) {
  28769. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  28770. }
  28771. if (this.matricesIndices) {
  28772. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  28773. }
  28774. if (this.matricesWeights) {
  28775. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  28776. }
  28777. if (this.matricesIndicesExtra) {
  28778. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  28779. }
  28780. if (this.matricesWeightsExtra) {
  28781. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  28782. }
  28783. if (this.indices) {
  28784. meshOrGeometry.setIndices(this.indices, null, updatable);
  28785. }
  28786. return this;
  28787. };
  28788. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  28789. if (this.positions) {
  28790. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  28791. }
  28792. if (this.normals) {
  28793. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  28794. }
  28795. if (this.tangents) {
  28796. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  28797. }
  28798. if (this.uvs) {
  28799. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  28800. }
  28801. if (this.uvs2) {
  28802. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  28803. }
  28804. if (this.uvs3) {
  28805. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  28806. }
  28807. if (this.uvs4) {
  28808. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  28809. }
  28810. if (this.uvs5) {
  28811. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  28812. }
  28813. if (this.uvs6) {
  28814. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  28815. }
  28816. if (this.colors) {
  28817. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  28818. }
  28819. if (this.matricesIndices) {
  28820. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  28821. }
  28822. if (this.matricesWeights) {
  28823. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  28824. }
  28825. if (this.matricesIndicesExtra) {
  28826. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  28827. }
  28828. if (this.matricesWeightsExtra) {
  28829. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  28830. }
  28831. if (this.indices) {
  28832. meshOrGeometry.setIndices(this.indices, null);
  28833. }
  28834. return this;
  28835. };
  28836. /**
  28837. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  28838. * Returns the VertexData.
  28839. */
  28840. VertexData.prototype.transform = function (matrix) {
  28841. var transformed = BABYLON.Vector3.Zero();
  28842. var index;
  28843. if (this.positions) {
  28844. var position = BABYLON.Vector3.Zero();
  28845. for (index = 0; index < this.positions.length; index += 3) {
  28846. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  28847. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  28848. this.positions[index] = transformed.x;
  28849. this.positions[index + 1] = transformed.y;
  28850. this.positions[index + 2] = transformed.z;
  28851. }
  28852. }
  28853. if (this.normals) {
  28854. var normal = BABYLON.Vector3.Zero();
  28855. for (index = 0; index < this.normals.length; index += 3) {
  28856. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  28857. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  28858. this.normals[index] = transformed.x;
  28859. this.normals[index + 1] = transformed.y;
  28860. this.normals[index + 2] = transformed.z;
  28861. }
  28862. }
  28863. if (this.tangents) {
  28864. var tangent = BABYLON.Vector4.Zero();
  28865. var tangentTransformed = BABYLON.Vector4.Zero();
  28866. for (index = 0; index < this.tangents.length; index += 4) {
  28867. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  28868. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  28869. this.tangents[index] = tangentTransformed.x;
  28870. this.tangents[index + 1] = tangentTransformed.y;
  28871. this.tangents[index + 2] = tangentTransformed.z;
  28872. this.tangents[index + 3] = tangentTransformed.w;
  28873. }
  28874. }
  28875. return this;
  28876. };
  28877. /**
  28878. * Merges the passed VertexData into the current one.
  28879. * Returns the modified VertexData.
  28880. */
  28881. VertexData.prototype.merge = function (other, options) {
  28882. options = options || {};
  28883. if (other.indices) {
  28884. if (!this.indices) {
  28885. this.indices = [];
  28886. }
  28887. var offset = this.positions ? this.positions.length / 3 : 0;
  28888. for (var index = 0; index < other.indices.length; index++) {
  28889. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  28890. this.indices.push(other.indices[index] + offset);
  28891. }
  28892. }
  28893. this.positions = this._mergeElement(this.positions, other.positions);
  28894. if (!this.positions) {
  28895. return this;
  28896. }
  28897. var count = this.positions.length / 3;
  28898. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  28899. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  28900. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  28901. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  28902. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  28903. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  28904. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  28905. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  28906. this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
  28907. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  28908. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  28909. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  28910. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  28911. return this;
  28912. };
  28913. VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
  28914. if (length === void 0) { length = 0; }
  28915. if (defaultValue === void 0) { defaultValue = 0; }
  28916. if (!other && !source) {
  28917. return null;
  28918. }
  28919. if (!other) {
  28920. var padding = new Float32Array(source.length);
  28921. padding.fill(defaultValue);
  28922. return this._mergeElement(source, padding, length);
  28923. }
  28924. if (!source) {
  28925. if (length === 0 || length === other.length) {
  28926. return other;
  28927. }
  28928. var padding = new Float32Array(length - other.length);
  28929. padding.fill(defaultValue);
  28930. return this._mergeElement(padding, other, length);
  28931. }
  28932. var len = other.length + source.length;
  28933. var isSrcTypedArray = source instanceof Float32Array;
  28934. var isOthTypedArray = other instanceof Float32Array;
  28935. // use non-loop method when the source is Float32Array
  28936. if (isSrcTypedArray) {
  28937. var ret32 = new Float32Array(len);
  28938. ret32.set(source);
  28939. ret32.set(other, source.length);
  28940. return ret32;
  28941. // source is number[], when other is also use concat
  28942. }
  28943. else if (!isOthTypedArray) {
  28944. return source.concat(other);
  28945. // source is a number[], but other is a Float32Array, loop required
  28946. }
  28947. else {
  28948. var ret = source.slice(0); // copy source to a separate array
  28949. for (var i = 0, len = other.length; i < len; i++) {
  28950. ret.push(other[i]);
  28951. }
  28952. return ret;
  28953. }
  28954. };
  28955. /**
  28956. * Serializes the VertexData.
  28957. * Returns a serialized object.
  28958. */
  28959. VertexData.prototype.serialize = function () {
  28960. var serializationObject = this.serialize();
  28961. if (this.positions) {
  28962. serializationObject.positions = this.positions;
  28963. }
  28964. if (this.normals) {
  28965. serializationObject.normals = this.normals;
  28966. }
  28967. if (this.tangents) {
  28968. serializationObject.tangents = this.tangents;
  28969. }
  28970. if (this.uvs) {
  28971. serializationObject.uvs = this.uvs;
  28972. }
  28973. if (this.uvs2) {
  28974. serializationObject.uvs2 = this.uvs2;
  28975. }
  28976. if (this.uvs3) {
  28977. serializationObject.uvs3 = this.uvs3;
  28978. }
  28979. if (this.uvs4) {
  28980. serializationObject.uvs4 = this.uvs4;
  28981. }
  28982. if (this.uvs5) {
  28983. serializationObject.uvs5 = this.uvs5;
  28984. }
  28985. if (this.uvs6) {
  28986. serializationObject.uvs6 = this.uvs6;
  28987. }
  28988. if (this.colors) {
  28989. serializationObject.colors = this.colors;
  28990. }
  28991. if (this.matricesIndices) {
  28992. serializationObject.matricesIndices = this.matricesIndices;
  28993. serializationObject.matricesIndices._isExpanded = true;
  28994. }
  28995. if (this.matricesWeights) {
  28996. serializationObject.matricesWeights = this.matricesWeights;
  28997. }
  28998. if (this.matricesIndicesExtra) {
  28999. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  29000. serializationObject.matricesIndicesExtra._isExpanded = true;
  29001. }
  29002. if (this.matricesWeightsExtra) {
  29003. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  29004. }
  29005. serializationObject.indices = this.indices;
  29006. return serializationObject;
  29007. };
  29008. // Statics
  29009. /**
  29010. * Returns the object VertexData associated to the passed mesh.
  29011. */
  29012. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  29013. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  29014. };
  29015. /**
  29016. * Returns the object VertexData associated to the passed geometry.
  29017. */
  29018. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  29019. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  29020. };
  29021. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  29022. var result = new VertexData();
  29023. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29024. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  29025. }
  29026. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29027. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  29028. }
  29029. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  29030. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  29031. }
  29032. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29033. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  29034. }
  29035. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29036. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  29037. }
  29038. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29039. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  29040. }
  29041. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29042. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  29043. }
  29044. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29045. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  29046. }
  29047. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29048. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  29049. }
  29050. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29051. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  29052. }
  29053. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29054. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  29055. }
  29056. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29057. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  29058. }
  29059. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  29060. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  29061. }
  29062. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  29063. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  29064. }
  29065. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  29066. return result;
  29067. };
  29068. /**
  29069. * Creates the vertexData of the Ribbon.
  29070. */
  29071. VertexData.CreateRibbon = function (options) {
  29072. var pathArray = options.pathArray;
  29073. var closeArray = options.closeArray || false;
  29074. var closePath = options.closePath || false;
  29075. var invertUV = options.invertUV || false;
  29076. var defaultOffset = Math.floor(pathArray[0].length / 2);
  29077. var offset = options.offset || defaultOffset;
  29078. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  29079. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29080. var customUV = options.uvs;
  29081. var customColors = options.colors;
  29082. var positions = [];
  29083. var indices = [];
  29084. var normals = [];
  29085. var uvs = [];
  29086. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  29087. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  29088. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  29089. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  29090. var minlg; // minimal length among all paths from pathArray
  29091. var lg = []; // array of path lengths : nb of vertex per path
  29092. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  29093. var p; // path iterator
  29094. var i; // point iterator
  29095. var j; // point iterator
  29096. // if single path in pathArray
  29097. if (pathArray.length < 2) {
  29098. var ar1 = [];
  29099. var ar2 = [];
  29100. for (i = 0; i < pathArray[0].length - offset; i++) {
  29101. ar1.push(pathArray[0][i]);
  29102. ar2.push(pathArray[0][i + offset]);
  29103. }
  29104. pathArray = [ar1, ar2];
  29105. }
  29106. // positions and horizontal distances (u)
  29107. var idc = 0;
  29108. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  29109. var path;
  29110. var l;
  29111. minlg = pathArray[0].length;
  29112. var vectlg;
  29113. var dist;
  29114. for (p = 0; p < pathArray.length; p++) {
  29115. uTotalDistance[p] = 0;
  29116. us[p] = [0];
  29117. path = pathArray[p];
  29118. l = path.length;
  29119. minlg = (minlg < l) ? minlg : l;
  29120. j = 0;
  29121. while (j < l) {
  29122. positions.push(path[j].x, path[j].y, path[j].z);
  29123. if (j > 0) {
  29124. vectlg = path[j].subtract(path[j - 1]).length();
  29125. dist = vectlg + uTotalDistance[p];
  29126. us[p].push(dist);
  29127. uTotalDistance[p] = dist;
  29128. }
  29129. j++;
  29130. }
  29131. if (closePath) {
  29132. j--;
  29133. positions.push(path[0].x, path[0].y, path[0].z);
  29134. vectlg = path[j].subtract(path[0]).length();
  29135. dist = vectlg + uTotalDistance[p];
  29136. us[p].push(dist);
  29137. uTotalDistance[p] = dist;
  29138. }
  29139. lg[p] = l + closePathCorr;
  29140. idx[p] = idc;
  29141. idc += (l + closePathCorr);
  29142. }
  29143. // vertical distances (v)
  29144. var path1;
  29145. var path2;
  29146. var vertex1 = null;
  29147. var vertex2 = null;
  29148. for (i = 0; i < minlg + closePathCorr; i++) {
  29149. vTotalDistance[i] = 0;
  29150. vs[i] = [0];
  29151. for (p = 0; p < pathArray.length - 1; p++) {
  29152. path1 = pathArray[p];
  29153. path2 = pathArray[p + 1];
  29154. if (i === minlg) {
  29155. vertex1 = path1[0];
  29156. vertex2 = path2[0];
  29157. }
  29158. else {
  29159. vertex1 = path1[i];
  29160. vertex2 = path2[i];
  29161. }
  29162. vectlg = vertex2.subtract(vertex1).length();
  29163. dist = vectlg + vTotalDistance[i];
  29164. vs[i].push(dist);
  29165. vTotalDistance[i] = dist;
  29166. }
  29167. if (closeArray && vertex2 && vertex1) {
  29168. path1 = pathArray[p];
  29169. path2 = pathArray[0];
  29170. if (i === minlg) {
  29171. vertex2 = path2[0];
  29172. }
  29173. vectlg = vertex2.subtract(vertex1).length();
  29174. dist = vectlg + vTotalDistance[i];
  29175. vTotalDistance[i] = dist;
  29176. }
  29177. }
  29178. // uvs
  29179. var u;
  29180. var v;
  29181. if (customUV) {
  29182. for (p = 0; p < customUV.length; p++) {
  29183. uvs.push(customUV[p].x, customUV[p].y);
  29184. }
  29185. }
  29186. else {
  29187. for (p = 0; p < pathArray.length; p++) {
  29188. for (i = 0; i < minlg + closePathCorr; i++) {
  29189. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  29190. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  29191. if (invertUV) {
  29192. uvs.push(v, u);
  29193. }
  29194. else {
  29195. uvs.push(u, v);
  29196. }
  29197. }
  29198. }
  29199. }
  29200. // indices
  29201. p = 0; // path index
  29202. var pi = 0; // positions array index
  29203. var l1 = lg[p] - 1; // path1 length
  29204. var l2 = lg[p + 1] - 1; // path2 length
  29205. var min = (l1 < l2) ? l1 : l2; // current path stop index
  29206. var shft = idx[1] - idx[0]; // shift
  29207. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  29208. while (pi <= min && p < path1nb) {
  29209. // 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
  29210. indices.push(pi, pi + shft, pi + 1);
  29211. indices.push(pi + shft + 1, pi + 1, pi + shft);
  29212. pi += 1;
  29213. if (pi === min) {
  29214. p++;
  29215. if (p === lg.length - 1) {
  29216. shft = idx[0] - idx[p];
  29217. l1 = lg[p] - 1;
  29218. l2 = lg[0] - 1;
  29219. }
  29220. else {
  29221. shft = idx[p + 1] - idx[p];
  29222. l1 = lg[p] - 1;
  29223. l2 = lg[p + 1] - 1;
  29224. }
  29225. pi = idx[p];
  29226. min = (l1 < l2) ? l1 + pi : l2 + pi;
  29227. }
  29228. }
  29229. // normals
  29230. VertexData.ComputeNormals(positions, indices, normals);
  29231. if (closePath) {
  29232. var indexFirst = 0;
  29233. var indexLast = 0;
  29234. for (p = 0; p < pathArray.length; p++) {
  29235. indexFirst = idx[p] * 3;
  29236. if (p + 1 < pathArray.length) {
  29237. indexLast = (idx[p + 1] - 1) * 3;
  29238. }
  29239. else {
  29240. indexLast = normals.length - 3;
  29241. }
  29242. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  29243. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  29244. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  29245. normals[indexLast] = normals[indexFirst];
  29246. normals[indexLast + 1] = normals[indexFirst + 1];
  29247. normals[indexLast + 2] = normals[indexFirst + 2];
  29248. }
  29249. }
  29250. // sides
  29251. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29252. // Colors
  29253. var colors = null;
  29254. if (customColors) {
  29255. colors = new Float32Array(customColors.length * 4);
  29256. for (var c = 0; c < customColors.length; c++) {
  29257. colors[c * 4] = customColors[c].r;
  29258. colors[c * 4 + 1] = customColors[c].g;
  29259. colors[c * 4 + 2] = customColors[c].b;
  29260. colors[c * 4 + 3] = customColors[c].a;
  29261. }
  29262. }
  29263. // Result
  29264. var vertexData = new VertexData();
  29265. var positions32 = new Float32Array(positions);
  29266. var normals32 = new Float32Array(normals);
  29267. var uvs32 = new Float32Array(uvs);
  29268. vertexData.indices = indices;
  29269. vertexData.positions = positions32;
  29270. vertexData.normals = normals32;
  29271. vertexData.uvs = uvs32;
  29272. if (colors) {
  29273. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  29274. }
  29275. if (closePath) {
  29276. vertexData._idx = idx;
  29277. }
  29278. return vertexData;
  29279. };
  29280. /**
  29281. * Creates the VertexData of the Box.
  29282. */
  29283. VertexData.CreateBox = function (options) {
  29284. var normalsSource = [
  29285. new BABYLON.Vector3(0, 0, 1),
  29286. new BABYLON.Vector3(0, 0, -1),
  29287. new BABYLON.Vector3(1, 0, 0),
  29288. new BABYLON.Vector3(-1, 0, 0),
  29289. new BABYLON.Vector3(0, 1, 0),
  29290. new BABYLON.Vector3(0, -1, 0)
  29291. ];
  29292. var indices = [];
  29293. var positions = [];
  29294. var normals = [];
  29295. var uvs = [];
  29296. var width = options.width || options.size || 1;
  29297. var height = options.height || options.size || 1;
  29298. var depth = options.depth || options.size || 1;
  29299. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29300. var faceUV = options.faceUV || new Array(6);
  29301. var faceColors = options.faceColors;
  29302. var colors = [];
  29303. // default face colors and UV if undefined
  29304. for (var f = 0; f < 6; f++) {
  29305. if (faceUV[f] === undefined) {
  29306. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29307. }
  29308. if (faceColors && faceColors[f] === undefined) {
  29309. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29310. }
  29311. }
  29312. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  29313. // Create each face in turn.
  29314. for (var index = 0; index < normalsSource.length; index++) {
  29315. var normal = normalsSource[index];
  29316. // Get two vectors perpendicular to the face normal and to each other.
  29317. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  29318. var side2 = BABYLON.Vector3.Cross(normal, side1);
  29319. // Six indices (two triangles) per face.
  29320. var verticesLength = positions.length / 3;
  29321. indices.push(verticesLength);
  29322. indices.push(verticesLength + 1);
  29323. indices.push(verticesLength + 2);
  29324. indices.push(verticesLength);
  29325. indices.push(verticesLength + 2);
  29326. indices.push(verticesLength + 3);
  29327. // Four vertices per face.
  29328. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  29329. positions.push(vertex.x, vertex.y, vertex.z);
  29330. normals.push(normal.x, normal.y, normal.z);
  29331. uvs.push(faceUV[index].z, faceUV[index].w);
  29332. if (faceColors) {
  29333. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29334. }
  29335. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  29336. positions.push(vertex.x, vertex.y, vertex.z);
  29337. normals.push(normal.x, normal.y, normal.z);
  29338. uvs.push(faceUV[index].x, faceUV[index].w);
  29339. if (faceColors) {
  29340. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29341. }
  29342. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  29343. positions.push(vertex.x, vertex.y, vertex.z);
  29344. normals.push(normal.x, normal.y, normal.z);
  29345. uvs.push(faceUV[index].x, faceUV[index].y);
  29346. if (faceColors) {
  29347. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29348. }
  29349. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  29350. positions.push(vertex.x, vertex.y, vertex.z);
  29351. normals.push(normal.x, normal.y, normal.z);
  29352. uvs.push(faceUV[index].z, faceUV[index].y);
  29353. if (faceColors) {
  29354. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29355. }
  29356. }
  29357. // sides
  29358. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29359. // Result
  29360. var vertexData = new VertexData();
  29361. vertexData.indices = indices;
  29362. vertexData.positions = positions;
  29363. vertexData.normals = normals;
  29364. vertexData.uvs = uvs;
  29365. if (faceColors) {
  29366. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29367. vertexData.colors = totalColors;
  29368. }
  29369. return vertexData;
  29370. };
  29371. /**
  29372. * Creates the VertexData of the Sphere.
  29373. */
  29374. VertexData.CreateSphere = function (options) {
  29375. var segments = options.segments || 32;
  29376. var diameterX = options.diameterX || options.diameter || 1;
  29377. var diameterY = options.diameterY || options.diameter || 1;
  29378. var diameterZ = options.diameterZ || options.diameter || 1;
  29379. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29380. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  29381. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29382. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  29383. var totalZRotationSteps = 2 + segments;
  29384. var totalYRotationSteps = 2 * totalZRotationSteps;
  29385. var indices = [];
  29386. var positions = [];
  29387. var normals = [];
  29388. var uvs = [];
  29389. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  29390. var normalizedZ = zRotationStep / totalZRotationSteps;
  29391. var angleZ = normalizedZ * Math.PI * slice;
  29392. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  29393. var normalizedY = yRotationStep / totalYRotationSteps;
  29394. var angleY = normalizedY * Math.PI * 2 * arc;
  29395. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  29396. var rotationY = BABYLON.Matrix.RotationY(angleY);
  29397. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  29398. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  29399. var vertex = complete.multiply(radius);
  29400. var normal = complete.divide(radius).normalize();
  29401. positions.push(vertex.x, vertex.y, vertex.z);
  29402. normals.push(normal.x, normal.y, normal.z);
  29403. uvs.push(normalizedY, normalizedZ);
  29404. }
  29405. if (zRotationStep > 0) {
  29406. var verticesCount = positions.length / 3;
  29407. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  29408. indices.push((firstIndex));
  29409. indices.push((firstIndex + 1));
  29410. indices.push(firstIndex + totalYRotationSteps + 1);
  29411. indices.push((firstIndex + totalYRotationSteps + 1));
  29412. indices.push((firstIndex + 1));
  29413. indices.push((firstIndex + totalYRotationSteps + 2));
  29414. }
  29415. }
  29416. }
  29417. // Sides
  29418. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29419. // Result
  29420. var vertexData = new VertexData();
  29421. vertexData.indices = indices;
  29422. vertexData.positions = positions;
  29423. vertexData.normals = normals;
  29424. vertexData.uvs = uvs;
  29425. return vertexData;
  29426. };
  29427. /**
  29428. * Creates the VertexData of the Cylinder or Cone.
  29429. */
  29430. VertexData.CreateCylinder = function (options) {
  29431. var height = options.height || 2;
  29432. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  29433. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  29434. var tessellation = options.tessellation || 24;
  29435. var subdivisions = options.subdivisions || 1;
  29436. var hasRings = options.hasRings ? true : false;
  29437. var enclose = options.enclose ? true : false;
  29438. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29439. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29440. var faceUV = options.faceUV || new Array(3);
  29441. var faceColors = options.faceColors;
  29442. // default face colors and UV if undefined
  29443. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  29444. var ringNb = (hasRings) ? subdivisions : 1;
  29445. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  29446. var f;
  29447. for (f = 0; f < surfaceNb; f++) {
  29448. if (faceColors && faceColors[f] === undefined) {
  29449. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29450. }
  29451. }
  29452. for (f = 0; f < surfaceNb; f++) {
  29453. if (faceUV && faceUV[f] === undefined) {
  29454. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29455. }
  29456. }
  29457. var indices = new Array();
  29458. var positions = new Array();
  29459. var normals = new Array();
  29460. var uvs = new Array();
  29461. var colors = new Array();
  29462. var angle_step = Math.PI * 2 * arc / tessellation;
  29463. var angle;
  29464. var h;
  29465. var radius;
  29466. var tan = (diameterBottom - diameterTop) / 2 / height;
  29467. var ringVertex = BABYLON.Vector3.Zero();
  29468. var ringNormal = BABYLON.Vector3.Zero();
  29469. var ringFirstVertex = BABYLON.Vector3.Zero();
  29470. var ringFirstNormal = BABYLON.Vector3.Zero();
  29471. var quadNormal = BABYLON.Vector3.Zero();
  29472. var Y = BABYLON.Axis.Y;
  29473. // positions, normals, uvs
  29474. var i;
  29475. var j;
  29476. var r;
  29477. var ringIdx = 1;
  29478. var s = 1; // surface index
  29479. var cs = 0;
  29480. var v = 0;
  29481. for (i = 0; i <= subdivisions; i++) {
  29482. h = i / subdivisions;
  29483. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  29484. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  29485. for (r = 0; r < ringIdx; r++) {
  29486. if (hasRings) {
  29487. s += r;
  29488. }
  29489. if (enclose) {
  29490. s += 2 * r;
  29491. }
  29492. for (j = 0; j <= tessellation; j++) {
  29493. angle = j * angle_step;
  29494. // position
  29495. ringVertex.x = Math.cos(-angle) * radius;
  29496. ringVertex.y = -height / 2 + h * height;
  29497. ringVertex.z = Math.sin(-angle) * radius;
  29498. // normal
  29499. if (diameterTop === 0 && i === subdivisions) {
  29500. // if no top cap, reuse former normals
  29501. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  29502. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  29503. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  29504. }
  29505. else {
  29506. ringNormal.x = ringVertex.x;
  29507. ringNormal.z = ringVertex.z;
  29508. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  29509. ringNormal.normalize();
  29510. }
  29511. // keep first ring vertex values for enclose
  29512. if (j === 0) {
  29513. ringFirstVertex.copyFrom(ringVertex);
  29514. ringFirstNormal.copyFrom(ringNormal);
  29515. }
  29516. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29517. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  29518. if (hasRings) {
  29519. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  29520. }
  29521. else {
  29522. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  29523. }
  29524. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  29525. if (faceColors) {
  29526. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  29527. }
  29528. }
  29529. // if enclose, add four vertices and their dedicated normals
  29530. if (arc !== 1 && enclose) {
  29531. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29532. positions.push(0, ringVertex.y, 0);
  29533. positions.push(0, ringVertex.y, 0);
  29534. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  29535. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  29536. quadNormal.normalize();
  29537. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29538. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  29539. quadNormal.normalize();
  29540. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29541. if (hasRings) {
  29542. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  29543. }
  29544. else {
  29545. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  29546. }
  29547. uvs.push(faceUV[s + 1].x, v);
  29548. uvs.push(faceUV[s + 1].z, v);
  29549. if (hasRings) {
  29550. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  29551. }
  29552. else {
  29553. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  29554. }
  29555. uvs.push(faceUV[s + 2].x, v);
  29556. uvs.push(faceUV[s + 2].z, v);
  29557. if (faceColors) {
  29558. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29559. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29560. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29561. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29562. }
  29563. }
  29564. if (cs !== s) {
  29565. cs = s;
  29566. }
  29567. }
  29568. }
  29569. // indices
  29570. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  29571. var s;
  29572. i = 0;
  29573. for (s = 0; s < subdivisions; s++) {
  29574. var i0 = 0;
  29575. var i1 = 0;
  29576. var i2 = 0;
  29577. var i3 = 0;
  29578. for (j = 0; j < tessellation; j++) {
  29579. i0 = i * (e + 1) + j;
  29580. i1 = (i + 1) * (e + 1) + j;
  29581. i2 = i * (e + 1) + (j + 1);
  29582. i3 = (i + 1) * (e + 1) + (j + 1);
  29583. indices.push(i0, i1, i2);
  29584. indices.push(i3, i2, i1);
  29585. }
  29586. if (arc !== 1 && enclose) {
  29587. indices.push(i0 + 2, i1 + 2, i2 + 2);
  29588. indices.push(i3 + 2, i2 + 2, i1 + 2);
  29589. indices.push(i0 + 4, i1 + 4, i2 + 4);
  29590. indices.push(i3 + 4, i2 + 4, i1 + 4);
  29591. }
  29592. i = (hasRings) ? (i + 2) : (i + 1);
  29593. }
  29594. // Caps
  29595. var createCylinderCap = function (isTop) {
  29596. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  29597. if (radius === 0) {
  29598. return;
  29599. }
  29600. // Cap positions, normals & uvs
  29601. var angle;
  29602. var circleVector;
  29603. var i;
  29604. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  29605. var c = null;
  29606. if (faceColors) {
  29607. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  29608. }
  29609. // cap center
  29610. var vbase = positions.length / 3;
  29611. var offset = isTop ? height / 2 : -height / 2;
  29612. var center = new BABYLON.Vector3(0, offset, 0);
  29613. positions.push(center.x, center.y, center.z);
  29614. normals.push(0, isTop ? 1 : -1, 0);
  29615. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  29616. if (c) {
  29617. colors.push(c.r, c.g, c.b, c.a);
  29618. }
  29619. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  29620. for (i = 0; i <= tessellation; i++) {
  29621. angle = Math.PI * 2 * i * arc / tessellation;
  29622. var cos = Math.cos(-angle);
  29623. var sin = Math.sin(-angle);
  29624. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  29625. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  29626. positions.push(circleVector.x, circleVector.y, circleVector.z);
  29627. normals.push(0, isTop ? 1 : -1, 0);
  29628. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  29629. if (c) {
  29630. colors.push(c.r, c.g, c.b, c.a);
  29631. }
  29632. }
  29633. // Cap indices
  29634. for (i = 0; i < tessellation; i++) {
  29635. if (!isTop) {
  29636. indices.push(vbase);
  29637. indices.push(vbase + (i + 1));
  29638. indices.push(vbase + (i + 2));
  29639. }
  29640. else {
  29641. indices.push(vbase);
  29642. indices.push(vbase + (i + 2));
  29643. indices.push(vbase + (i + 1));
  29644. }
  29645. }
  29646. };
  29647. // add caps to geometry
  29648. createCylinderCap(false);
  29649. createCylinderCap(true);
  29650. // Sides
  29651. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29652. var vertexData = new VertexData();
  29653. vertexData.indices = indices;
  29654. vertexData.positions = positions;
  29655. vertexData.normals = normals;
  29656. vertexData.uvs = uvs;
  29657. if (faceColors) {
  29658. vertexData.colors = colors;
  29659. }
  29660. return vertexData;
  29661. };
  29662. /**
  29663. * Creates the VertexData of the Torus.
  29664. */
  29665. VertexData.CreateTorus = function (options) {
  29666. var indices = [];
  29667. var positions = [];
  29668. var normals = [];
  29669. var uvs = [];
  29670. var diameter = options.diameter || 1;
  29671. var thickness = options.thickness || 0.5;
  29672. var tessellation = options.tessellation || 16;
  29673. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29674. var stride = tessellation + 1;
  29675. for (var i = 0; i <= tessellation; i++) {
  29676. var u = i / tessellation;
  29677. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  29678. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  29679. for (var j = 0; j <= tessellation; j++) {
  29680. var v = 1 - j / tessellation;
  29681. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  29682. var dx = Math.cos(innerAngle);
  29683. var dy = Math.sin(innerAngle);
  29684. // Create a vertex.
  29685. var normal = new BABYLON.Vector3(dx, dy, 0);
  29686. var position = normal.scale(thickness / 2);
  29687. var textureCoordinate = new BABYLON.Vector2(u, v);
  29688. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  29689. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  29690. positions.push(position.x, position.y, position.z);
  29691. normals.push(normal.x, normal.y, normal.z);
  29692. uvs.push(textureCoordinate.x, textureCoordinate.y);
  29693. // And create indices for two triangles.
  29694. var nextI = (i + 1) % stride;
  29695. var nextJ = (j + 1) % stride;
  29696. indices.push(i * stride + j);
  29697. indices.push(i * stride + nextJ);
  29698. indices.push(nextI * stride + j);
  29699. indices.push(i * stride + nextJ);
  29700. indices.push(nextI * stride + nextJ);
  29701. indices.push(nextI * stride + j);
  29702. }
  29703. }
  29704. // Sides
  29705. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29706. // Result
  29707. var vertexData = new VertexData();
  29708. vertexData.indices = indices;
  29709. vertexData.positions = positions;
  29710. vertexData.normals = normals;
  29711. vertexData.uvs = uvs;
  29712. return vertexData;
  29713. };
  29714. /**
  29715. * Creates the VertexData of the LineSystem.
  29716. */
  29717. VertexData.CreateLineSystem = function (options) {
  29718. var indices = [];
  29719. var positions = [];
  29720. var lines = options.lines;
  29721. var colors = options.colors;
  29722. var vertexColors = [];
  29723. var idx = 0;
  29724. for (var l = 0; l < lines.length; l++) {
  29725. var points = lines[l];
  29726. for (var index = 0; index < points.length; index++) {
  29727. positions.push(points[index].x, points[index].y, points[index].z);
  29728. if (colors) {
  29729. var color = colors[l];
  29730. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  29731. }
  29732. if (index > 0) {
  29733. indices.push(idx - 1);
  29734. indices.push(idx);
  29735. }
  29736. idx++;
  29737. }
  29738. }
  29739. var vertexData = new VertexData();
  29740. vertexData.indices = indices;
  29741. vertexData.positions = positions;
  29742. if (colors) {
  29743. vertexData.colors = vertexColors;
  29744. }
  29745. return vertexData;
  29746. };
  29747. /**
  29748. * Create the VertexData of the DashedLines.
  29749. */
  29750. VertexData.CreateDashedLines = function (options) {
  29751. var dashSize = options.dashSize || 3;
  29752. var gapSize = options.gapSize || 1;
  29753. var dashNb = options.dashNb || 200;
  29754. var points = options.points;
  29755. var positions = new Array();
  29756. var indices = new Array();
  29757. var curvect = BABYLON.Vector3.Zero();
  29758. var lg = 0;
  29759. var nb = 0;
  29760. var shft = 0;
  29761. var dashshft = 0;
  29762. var curshft = 0;
  29763. var idx = 0;
  29764. var i = 0;
  29765. for (i = 0; i < points.length - 1; i++) {
  29766. points[i + 1].subtractToRef(points[i], curvect);
  29767. lg += curvect.length();
  29768. }
  29769. shft = lg / dashNb;
  29770. dashshft = dashSize * shft / (dashSize + gapSize);
  29771. for (i = 0; i < points.length - 1; i++) {
  29772. points[i + 1].subtractToRef(points[i], curvect);
  29773. nb = Math.floor(curvect.length() / shft);
  29774. curvect.normalize();
  29775. for (var j = 0; j < nb; j++) {
  29776. curshft = shft * j;
  29777. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  29778. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  29779. indices.push(idx, idx + 1);
  29780. idx += 2;
  29781. }
  29782. }
  29783. // Result
  29784. var vertexData = new VertexData();
  29785. vertexData.positions = positions;
  29786. vertexData.indices = indices;
  29787. return vertexData;
  29788. };
  29789. /**
  29790. * Creates the VertexData of the Ground.
  29791. */
  29792. VertexData.CreateGround = function (options) {
  29793. var indices = [];
  29794. var positions = [];
  29795. var normals = [];
  29796. var uvs = [];
  29797. var row, col;
  29798. var width = options.width || 1;
  29799. var height = options.height || 1;
  29800. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  29801. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  29802. for (row = 0; row <= subdivisionsY; row++) {
  29803. for (col = 0; col <= subdivisionsX; col++) {
  29804. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  29805. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29806. positions.push(position.x, position.y, position.z);
  29807. normals.push(normal.x, normal.y, normal.z);
  29808. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  29809. }
  29810. }
  29811. for (row = 0; row < subdivisionsY; row++) {
  29812. for (col = 0; col < subdivisionsX; col++) {
  29813. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29814. indices.push(col + 1 + row * (subdivisionsX + 1));
  29815. indices.push(col + row * (subdivisionsX + 1));
  29816. indices.push(col + (row + 1) * (subdivisionsX + 1));
  29817. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29818. indices.push(col + row * (subdivisionsX + 1));
  29819. }
  29820. }
  29821. // Result
  29822. var vertexData = new VertexData();
  29823. vertexData.indices = indices;
  29824. vertexData.positions = positions;
  29825. vertexData.normals = normals;
  29826. vertexData.uvs = uvs;
  29827. return vertexData;
  29828. };
  29829. /**
  29830. * Creates the VertexData of the TiledGround.
  29831. */
  29832. VertexData.CreateTiledGround = function (options) {
  29833. var xmin = options.xmin || -1.0;
  29834. var zmin = options.zmin || -1.0;
  29835. var xmax = options.xmax || 1.0;
  29836. var zmax = options.zmax || 1.0;
  29837. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  29838. var precision = options.precision || { w: 1, h: 1 };
  29839. var indices = new Array();
  29840. var positions = new Array();
  29841. var normals = new Array();
  29842. var uvs = new Array();
  29843. var row, col, tileRow, tileCol;
  29844. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  29845. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  29846. precision.w = (precision.w < 1) ? 1 : precision.w;
  29847. precision.h = (precision.h < 1) ? 1 : precision.h;
  29848. var tileSize = {
  29849. 'w': (xmax - xmin) / subdivisions.w,
  29850. 'h': (zmax - zmin) / subdivisions.h
  29851. };
  29852. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  29853. // Indices
  29854. var base = positions.length / 3;
  29855. var rowLength = precision.w + 1;
  29856. for (row = 0; row < precision.h; row++) {
  29857. for (col = 0; col < precision.w; col++) {
  29858. var square = [
  29859. base + col + row * rowLength,
  29860. base + (col + 1) + row * rowLength,
  29861. base + (col + 1) + (row + 1) * rowLength,
  29862. base + col + (row + 1) * rowLength
  29863. ];
  29864. indices.push(square[1]);
  29865. indices.push(square[2]);
  29866. indices.push(square[3]);
  29867. indices.push(square[0]);
  29868. indices.push(square[1]);
  29869. indices.push(square[3]);
  29870. }
  29871. }
  29872. // Position, normals and uvs
  29873. var position = BABYLON.Vector3.Zero();
  29874. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29875. for (row = 0; row <= precision.h; row++) {
  29876. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  29877. for (col = 0; col <= precision.w; col++) {
  29878. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  29879. position.y = 0;
  29880. positions.push(position.x, position.y, position.z);
  29881. normals.push(normal.x, normal.y, normal.z);
  29882. uvs.push(col / precision.w, row / precision.h);
  29883. }
  29884. }
  29885. }
  29886. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  29887. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  29888. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  29889. }
  29890. }
  29891. // Result
  29892. var vertexData = new VertexData();
  29893. vertexData.indices = indices;
  29894. vertexData.positions = positions;
  29895. vertexData.normals = normals;
  29896. vertexData.uvs = uvs;
  29897. return vertexData;
  29898. };
  29899. /**
  29900. * Creates the VertexData of the Ground designed from a heightmap.
  29901. */
  29902. VertexData.CreateGroundFromHeightMap = function (options) {
  29903. var indices = [];
  29904. var positions = [];
  29905. var normals = [];
  29906. var uvs = [];
  29907. var row, col;
  29908. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  29909. // Vertices
  29910. for (row = 0; row <= options.subdivisions; row++) {
  29911. for (col = 0; col <= options.subdivisions; col++) {
  29912. 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));
  29913. // Compute height
  29914. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  29915. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  29916. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  29917. var r = options.buffer[pos] / 255.0;
  29918. var g = options.buffer[pos + 1] / 255.0;
  29919. var b = options.buffer[pos + 2] / 255.0;
  29920. var gradient = r * filter.r + g * filter.g + b * filter.b;
  29921. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  29922. // Add vertex
  29923. positions.push(position.x, position.y, position.z);
  29924. normals.push(0, 0, 0);
  29925. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  29926. }
  29927. }
  29928. // Indices
  29929. for (row = 0; row < options.subdivisions; row++) {
  29930. for (col = 0; col < options.subdivisions; col++) {
  29931. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29932. indices.push(col + 1 + row * (options.subdivisions + 1));
  29933. indices.push(col + row * (options.subdivisions + 1));
  29934. indices.push(col + (row + 1) * (options.subdivisions + 1));
  29935. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29936. indices.push(col + row * (options.subdivisions + 1));
  29937. }
  29938. }
  29939. // Normals
  29940. VertexData.ComputeNormals(positions, indices, normals);
  29941. // Result
  29942. var vertexData = new VertexData();
  29943. vertexData.indices = indices;
  29944. vertexData.positions = positions;
  29945. vertexData.normals = normals;
  29946. vertexData.uvs = uvs;
  29947. return vertexData;
  29948. };
  29949. /**
  29950. * Creates the VertexData of the Plane.
  29951. */
  29952. VertexData.CreatePlane = function (options) {
  29953. var indices = [];
  29954. var positions = [];
  29955. var normals = [];
  29956. var uvs = [];
  29957. var width = options.width || options.size || 1;
  29958. var height = options.height || options.size || 1;
  29959. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29960. // Vertices
  29961. var halfWidth = width / 2.0;
  29962. var halfHeight = height / 2.0;
  29963. positions.push(-halfWidth, -halfHeight, 0);
  29964. normals.push(0, 0, -1.0);
  29965. uvs.push(0.0, 0.0);
  29966. positions.push(halfWidth, -halfHeight, 0);
  29967. normals.push(0, 0, -1.0);
  29968. uvs.push(1.0, 0.0);
  29969. positions.push(halfWidth, halfHeight, 0);
  29970. normals.push(0, 0, -1.0);
  29971. uvs.push(1.0, 1.0);
  29972. positions.push(-halfWidth, halfHeight, 0);
  29973. normals.push(0, 0, -1.0);
  29974. uvs.push(0.0, 1.0);
  29975. // Indices
  29976. indices.push(0);
  29977. indices.push(1);
  29978. indices.push(2);
  29979. indices.push(0);
  29980. indices.push(2);
  29981. indices.push(3);
  29982. // Sides
  29983. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29984. // Result
  29985. var vertexData = new VertexData();
  29986. vertexData.indices = indices;
  29987. vertexData.positions = positions;
  29988. vertexData.normals = normals;
  29989. vertexData.uvs = uvs;
  29990. return vertexData;
  29991. };
  29992. /**
  29993. * Creates the VertexData of the Disc or regular Polygon.
  29994. */
  29995. VertexData.CreateDisc = function (options) {
  29996. var positions = new Array();
  29997. var indices = new Array();
  29998. var normals = new Array();
  29999. var uvs = new Array();
  30000. var radius = options.radius || 0.5;
  30001. var tessellation = options.tessellation || 64;
  30002. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30003. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30004. // positions and uvs
  30005. positions.push(0, 0, 0); // disc center first
  30006. uvs.push(0.5, 0.5);
  30007. var theta = Math.PI * 2 * arc;
  30008. var step = theta / tessellation;
  30009. for (var a = 0; a < theta; a += step) {
  30010. var x = Math.cos(a);
  30011. var y = Math.sin(a);
  30012. var u = (x + 1) / 2;
  30013. var v = (1 - y) / 2;
  30014. positions.push(radius * x, radius * y, 0);
  30015. uvs.push(u, v);
  30016. }
  30017. if (arc === 1) {
  30018. positions.push(positions[3], positions[4], positions[5]); // close the circle
  30019. uvs.push(uvs[2], uvs[3]);
  30020. }
  30021. //indices
  30022. var vertexNb = positions.length / 3;
  30023. for (var i = 1; i < vertexNb - 1; i++) {
  30024. indices.push(i + 1, 0, i);
  30025. }
  30026. // result
  30027. VertexData.ComputeNormals(positions, indices, normals);
  30028. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30029. var vertexData = new VertexData();
  30030. vertexData.indices = indices;
  30031. vertexData.positions = positions;
  30032. vertexData.normals = normals;
  30033. vertexData.uvs = uvs;
  30034. return vertexData;
  30035. };
  30036. /**
  30037. * Re-creates the VertexData of the Polygon for sideOrientation.
  30038. */
  30039. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  30040. var faceUV = fUV || new Array(3);
  30041. var faceColors = fColors;
  30042. var colors = [];
  30043. // default face colors and UV if undefined
  30044. for (var f = 0; f < 3; f++) {
  30045. if (faceUV[f] === undefined) {
  30046. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30047. }
  30048. if (faceColors && faceColors[f] === undefined) {
  30049. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30050. }
  30051. }
  30052. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30053. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30054. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30055. var indices = polygon.getIndices();
  30056. // set face colours and textures
  30057. var idx = 0;
  30058. var face = 0;
  30059. for (var index = 0; index < normals.length; index += 3) {
  30060. //Edge Face no. 1
  30061. if (Math.abs(normals[index + 1]) < 0.001) {
  30062. face = 1;
  30063. }
  30064. //Top Face no. 0
  30065. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  30066. face = 0;
  30067. }
  30068. //Bottom Face no. 2
  30069. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  30070. face = 2;
  30071. }
  30072. idx = index / 3;
  30073. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  30074. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  30075. if (faceColors) {
  30076. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  30077. }
  30078. }
  30079. // sides
  30080. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  30081. // Result
  30082. var vertexData = new VertexData();
  30083. vertexData.indices = indices;
  30084. vertexData.positions = positions;
  30085. vertexData.normals = normals;
  30086. vertexData.uvs = uvs;
  30087. if (faceColors) {
  30088. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30089. vertexData.colors = totalColors;
  30090. }
  30091. return vertexData;
  30092. };
  30093. /**
  30094. * Creates the VertexData of the IcoSphere.
  30095. */
  30096. VertexData.CreateIcoSphere = function (options) {
  30097. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30098. var radius = options.radius || 1;
  30099. var flat = (options.flat === undefined) ? true : options.flat;
  30100. var subdivisions = options.subdivisions || 4;
  30101. var radiusX = options.radiusX || radius;
  30102. var radiusY = options.radiusY || radius;
  30103. var radiusZ = options.radiusZ || radius;
  30104. var t = (1 + Math.sqrt(5)) / 2;
  30105. // 12 vertex x,y,z
  30106. var ico_vertices = [
  30107. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  30108. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  30109. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  30110. ];
  30111. // index of 3 vertex makes a face of icopshere
  30112. var ico_indices = [
  30113. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  30114. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  30115. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  30116. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  30117. ];
  30118. // vertex for uv have aliased position, not for UV
  30119. var vertices_unalias_id = [
  30120. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  30121. // vertex alias
  30122. 0,
  30123. 2,
  30124. 3,
  30125. 3,
  30126. 3,
  30127. 4,
  30128. 7,
  30129. 8,
  30130. 9,
  30131. 9,
  30132. 10,
  30133. 11 // 23: B + 12
  30134. ];
  30135. // uv as integer step (not pixels !)
  30136. var ico_vertexuv = [
  30137. 5, 1, 3, 1, 6, 4, 0, 0,
  30138. 5, 3, 4, 2, 2, 2, 4, 0,
  30139. 2, 0, 1, 1, 6, 0, 6, 2,
  30140. // vertex alias (for same vertex on different faces)
  30141. 0, 4,
  30142. 3, 3,
  30143. 4, 4,
  30144. 3, 1,
  30145. 4, 2,
  30146. 4, 4,
  30147. 0, 2,
  30148. 1, 1,
  30149. 2, 2,
  30150. 3, 3,
  30151. 1, 3,
  30152. 2, 4 // 23: B + 12
  30153. ];
  30154. // Vertices[0, 1, ...9, A, B] : position on UV plane
  30155. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  30156. // First island of uv mapping
  30157. // v = 4h 3+ 2
  30158. // v = 3h 9+ 4
  30159. // v = 2h 9+ 5 B
  30160. // v = 1h 9 1 0
  30161. // v = 0h 3 8 7 A
  30162. // u = 0 1 2 3 4 5 6 *a
  30163. // Second island of uv mapping
  30164. // v = 4h 0+ B+ 4+
  30165. // v = 3h A+ 2+
  30166. // v = 2h 7+ 6 3+
  30167. // v = 1h 8+ 3+
  30168. // v = 0h
  30169. // u = 0 1 2 3 4 5 6 *a
  30170. // Face layout on texture UV mapping
  30171. // ============
  30172. // \ 4 /\ 16 / ======
  30173. // \ / \ / /\ 11 /
  30174. // \/ 7 \/ / \ /
  30175. // ======= / 10 \/
  30176. // /\ 17 /\ =======
  30177. // / \ / \ \ 15 /\
  30178. // / 8 \/ 12 \ \ / \
  30179. // ============ \/ 6 \
  30180. // \ 18 /\ ============
  30181. // \ / \ \ 5 /\ 0 /
  30182. // \/ 13 \ \ / \ /
  30183. // ======= \/ 1 \/
  30184. // =============
  30185. // /\ 19 /\ 2 /\
  30186. // / \ / \ / \
  30187. // / 14 \/ 9 \/ 3 \
  30188. // ===================
  30189. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  30190. var ustep = 138 / 1024;
  30191. var vstep = 239 / 1024;
  30192. var uoffset = 60 / 1024;
  30193. var voffset = 26 / 1024;
  30194. // Second island should have margin, not to touch the first island
  30195. // avoid any borderline artefact in pixel rounding
  30196. var island_u_offset = -40 / 1024;
  30197. var island_v_offset = +20 / 1024;
  30198. // face is either island 0 or 1 :
  30199. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  30200. var island = [
  30201. 0, 0, 0, 0, 1,
  30202. 0, 0, 1, 1, 0,
  30203. 0, 0, 1, 1, 0,
  30204. 0, 1, 1, 1, 0 // 15 - 19
  30205. ];
  30206. var indices = new Array();
  30207. var positions = new Array();
  30208. var normals = new Array();
  30209. var uvs = new Array();
  30210. var current_indice = 0;
  30211. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  30212. var face_vertex_pos = new Array(3);
  30213. var face_vertex_uv = new Array(3);
  30214. var v012;
  30215. for (v012 = 0; v012 < 3; v012++) {
  30216. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  30217. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  30218. }
  30219. // create all with normals
  30220. for (var face = 0; face < 20; face++) {
  30221. // 3 vertex per face
  30222. for (v012 = 0; v012 < 3; v012++) {
  30223. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  30224. var v_id = ico_indices[3 * face + v012];
  30225. // vertex have 3D position (x,y,z)
  30226. 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]);
  30227. // Normalize to get normal, then scale to radius
  30228. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  30229. // uv Coordinates from vertex ID
  30230. 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);
  30231. }
  30232. // Subdivide the face (interpolate pos, norm, uv)
  30233. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  30234. // - norm is linear interpolation of vertex corner normal
  30235. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  30236. // - uv is linear interpolation
  30237. //
  30238. // Topology is as below for sub-divide by 2
  30239. // vertex shown as v0,v1,v2
  30240. // interp index is i1 to progress in range [v0,v1[
  30241. // interp index is i2 to progress in range [v0,v2[
  30242. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  30243. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30244. //
  30245. //
  30246. // i2 v2
  30247. // ^ ^
  30248. // / / \
  30249. // / / \
  30250. // / / \
  30251. // / / (0,1) \
  30252. // / #---------\
  30253. // / / \ (0,0)'/ \
  30254. // / / \ / \
  30255. // / / \ / \
  30256. // / / (0,0) \ / (1,0) \
  30257. // / #---------#---------\
  30258. // v0 v1
  30259. //
  30260. // --------------------> i1
  30261. //
  30262. // interp of (i1,i2):
  30263. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  30264. // along i1 : lerp(x0,x1, i1/(S-i2))
  30265. //
  30266. // centroid of triangle is needed to get help normal computation
  30267. // (c1,c2) are used for centroid location
  30268. var interp_vertex = function (i1, i2, c1, c2) {
  30269. // vertex is interpolated from
  30270. // - face_vertex_pos[0..2]
  30271. // - face_vertex_uv[0..2]
  30272. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  30273. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  30274. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  30275. pos_interp.normalize();
  30276. var vertex_normal;
  30277. if (flat) {
  30278. // in flat mode, recalculate normal as face centroid normal
  30279. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  30280. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  30281. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  30282. }
  30283. else {
  30284. // in smooth mode, recalculate normal from each single vertex position
  30285. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  30286. }
  30287. // Vertex normal need correction due to X,Y,Z radius scaling
  30288. vertex_normal.x /= radiusX;
  30289. vertex_normal.y /= radiusY;
  30290. vertex_normal.z /= radiusZ;
  30291. vertex_normal.normalize();
  30292. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  30293. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  30294. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  30295. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  30296. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  30297. uvs.push(uv_interp.x, uv_interp.y);
  30298. // push each vertex has member of a face
  30299. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  30300. indices.push(current_indice);
  30301. current_indice++;
  30302. };
  30303. for (var i2 = 0; i2 < subdivisions; i2++) {
  30304. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  30305. // face : (i1,i2) for /\ :
  30306. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  30307. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30308. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30309. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30310. if (i1 + i2 + 1 < subdivisions) {
  30311. // face : (i1,i2)' for \/ :
  30312. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30313. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30314. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30315. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30316. }
  30317. }
  30318. }
  30319. }
  30320. // Sides
  30321. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30322. // Result
  30323. var vertexData = new VertexData();
  30324. vertexData.indices = indices;
  30325. vertexData.positions = positions;
  30326. vertexData.normals = normals;
  30327. vertexData.uvs = uvs;
  30328. return vertexData;
  30329. };
  30330. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  30331. /**
  30332. * Creates the VertexData of the Polyhedron.
  30333. */
  30334. VertexData.CreatePolyhedron = function (options) {
  30335. // provided polyhedron types :
  30336. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  30337. // 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)
  30338. var polyhedra = [];
  30339. 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]] };
  30340. 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]] };
  30341. polyhedra[2] = {
  30342. 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]],
  30343. 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]]
  30344. };
  30345. polyhedra[3] = {
  30346. 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]],
  30347. 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]]
  30348. };
  30349. polyhedra[4] = {
  30350. 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]],
  30351. 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]]
  30352. };
  30353. 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]] };
  30354. 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]] };
  30355. 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]] };
  30356. 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]] };
  30357. 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]] };
  30358. 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]] };
  30359. 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]] };
  30360. 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]] };
  30361. 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]] };
  30362. polyhedra[14] = {
  30363. 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]],
  30364. 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]]
  30365. };
  30366. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  30367. var size = options.size;
  30368. var sizeX = options.sizeX || size || 1;
  30369. var sizeY = options.sizeY || size || 1;
  30370. var sizeZ = options.sizeZ || size || 1;
  30371. var data = options.custom || polyhedra[type];
  30372. var nbfaces = data.face.length;
  30373. var faceUV = options.faceUV || new Array(nbfaces);
  30374. var faceColors = options.faceColors;
  30375. var flat = (options.flat === undefined) ? true : options.flat;
  30376. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30377. var positions = new Array();
  30378. var indices = new Array();
  30379. var normals = new Array();
  30380. var uvs = new Array();
  30381. var colors = new Array();
  30382. var index = 0;
  30383. var faceIdx = 0; // face cursor in the array "indexes"
  30384. var indexes = new Array();
  30385. var i = 0;
  30386. var f = 0;
  30387. var u, v, ang, x, y, tmp;
  30388. // default face colors and UV if undefined
  30389. if (flat) {
  30390. for (f = 0; f < nbfaces; f++) {
  30391. if (faceColors && faceColors[f] === undefined) {
  30392. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30393. }
  30394. if (faceUV && faceUV[f] === undefined) {
  30395. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30396. }
  30397. }
  30398. }
  30399. if (!flat) {
  30400. for (i = 0; i < data.vertex.length; i++) {
  30401. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  30402. uvs.push(0, 0);
  30403. }
  30404. for (f = 0; f < nbfaces; f++) {
  30405. for (i = 0; i < data.face[f].length - 2; i++) {
  30406. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  30407. }
  30408. }
  30409. }
  30410. else {
  30411. for (f = 0; f < nbfaces; f++) {
  30412. var fl = data.face[f].length; // number of vertices of the current face
  30413. ang = 2 * Math.PI / fl;
  30414. x = 0.5 * Math.tan(ang / 2);
  30415. y = 0.5;
  30416. // positions, uvs, colors
  30417. for (i = 0; i < fl; i++) {
  30418. // positions
  30419. 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);
  30420. indexes.push(index);
  30421. index++;
  30422. // uvs
  30423. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  30424. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  30425. uvs.push(u, v);
  30426. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  30427. y = x * Math.sin(ang) + y * Math.cos(ang);
  30428. x = tmp;
  30429. // colors
  30430. if (faceColors) {
  30431. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  30432. }
  30433. }
  30434. // indices from indexes
  30435. for (i = 0; i < fl - 2; i++) {
  30436. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  30437. }
  30438. faceIdx += fl;
  30439. }
  30440. }
  30441. VertexData.ComputeNormals(positions, indices, normals);
  30442. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30443. var vertexData = new VertexData();
  30444. vertexData.positions = positions;
  30445. vertexData.indices = indices;
  30446. vertexData.normals = normals;
  30447. vertexData.uvs = uvs;
  30448. if (faceColors && flat) {
  30449. vertexData.colors = colors;
  30450. }
  30451. return vertexData;
  30452. };
  30453. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  30454. /**
  30455. * Creates the VertexData of the Torus Knot.
  30456. */
  30457. VertexData.CreateTorusKnot = function (options) {
  30458. var indices = new Array();
  30459. var positions = new Array();
  30460. var normals = new Array();
  30461. var uvs = new Array();
  30462. var radius = options.radius || 2;
  30463. var tube = options.tube || 0.5;
  30464. var radialSegments = options.radialSegments || 32;
  30465. var tubularSegments = options.tubularSegments || 32;
  30466. var p = options.p || 2;
  30467. var q = options.q || 3;
  30468. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30469. // Helper
  30470. var getPos = function (angle) {
  30471. var cu = Math.cos(angle);
  30472. var su = Math.sin(angle);
  30473. var quOverP = q / p * angle;
  30474. var cs = Math.cos(quOverP);
  30475. var tx = radius * (2 + cs) * 0.5 * cu;
  30476. var ty = radius * (2 + cs) * su * 0.5;
  30477. var tz = radius * Math.sin(quOverP) * 0.5;
  30478. return new BABYLON.Vector3(tx, ty, tz);
  30479. };
  30480. // Vertices
  30481. var i;
  30482. var j;
  30483. for (i = 0; i <= radialSegments; i++) {
  30484. var modI = i % radialSegments;
  30485. var u = modI / radialSegments * 2 * p * Math.PI;
  30486. var p1 = getPos(u);
  30487. var p2 = getPos(u + 0.01);
  30488. var tang = p2.subtract(p1);
  30489. var n = p2.add(p1);
  30490. var bitan = BABYLON.Vector3.Cross(tang, n);
  30491. n = BABYLON.Vector3.Cross(bitan, tang);
  30492. bitan.normalize();
  30493. n.normalize();
  30494. for (j = 0; j < tubularSegments; j++) {
  30495. var modJ = j % tubularSegments;
  30496. var v = modJ / tubularSegments * 2 * Math.PI;
  30497. var cx = -tube * Math.cos(v);
  30498. var cy = tube * Math.sin(v);
  30499. positions.push(p1.x + cx * n.x + cy * bitan.x);
  30500. positions.push(p1.y + cx * n.y + cy * bitan.y);
  30501. positions.push(p1.z + cx * n.z + cy * bitan.z);
  30502. uvs.push(i / radialSegments);
  30503. uvs.push(j / tubularSegments);
  30504. }
  30505. }
  30506. for (i = 0; i < radialSegments; i++) {
  30507. for (j = 0; j < tubularSegments; j++) {
  30508. var jNext = (j + 1) % tubularSegments;
  30509. var a = i * tubularSegments + j;
  30510. var b = (i + 1) * tubularSegments + j;
  30511. var c = (i + 1) * tubularSegments + jNext;
  30512. var d = i * tubularSegments + jNext;
  30513. indices.push(d);
  30514. indices.push(b);
  30515. indices.push(a);
  30516. indices.push(d);
  30517. indices.push(c);
  30518. indices.push(b);
  30519. }
  30520. }
  30521. // Normals
  30522. VertexData.ComputeNormals(positions, indices, normals);
  30523. // Sides
  30524. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30525. // Result
  30526. var vertexData = new VertexData();
  30527. vertexData.indices = indices;
  30528. vertexData.positions = positions;
  30529. vertexData.normals = normals;
  30530. vertexData.uvs = uvs;
  30531. return vertexData;
  30532. };
  30533. // Tools
  30534. /**
  30535. * @param {any} - positions (number[] or Float32Array)
  30536. * @param {any} - indices (number[] or Uint16Array)
  30537. * @param {any} - normals (number[] or Float32Array)
  30538. * options (optional) :
  30539. * facetPositions : optional array of facet positions (vector3)
  30540. * facetNormals : optional array of facet normals (vector3)
  30541. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  30542. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  30543. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  30544. * bbSize : optional bounding box size data, required for facetPartitioning computation
  30545. * bInfo : optional bounding info, required for facetPartitioning computation
  30546. * useRightHandedSystem: optional boolean to for right handed system computation
  30547. * depthSort : optional boolean to enable the facet depth sort computation
  30548. * distanceTo : optional Vector3 to compute the facet depth from this location
  30549. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  30550. */
  30551. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  30552. // temporary scalar variables
  30553. var index = 0; // facet index
  30554. var p1p2x = 0.0; // p1p2 vector x coordinate
  30555. var p1p2y = 0.0; // p1p2 vector y coordinate
  30556. var p1p2z = 0.0; // p1p2 vector z coordinate
  30557. var p3p2x = 0.0; // p3p2 vector x coordinate
  30558. var p3p2y = 0.0; // p3p2 vector y coordinate
  30559. var p3p2z = 0.0; // p3p2 vector z coordinate
  30560. var faceNormalx = 0.0; // facet normal x coordinate
  30561. var faceNormaly = 0.0; // facet normal y coordinate
  30562. var faceNormalz = 0.0; // facet normal z coordinate
  30563. var length = 0.0; // facet normal length before normalization
  30564. var v1x = 0; // vector1 x index in the positions array
  30565. var v1y = 0; // vector1 y index in the positions array
  30566. var v1z = 0; // vector1 z index in the positions array
  30567. var v2x = 0; // vector2 x index in the positions array
  30568. var v2y = 0; // vector2 y index in the positions array
  30569. var v2z = 0; // vector2 z index in the positions array
  30570. var v3x = 0; // vector3 x index in the positions array
  30571. var v3y = 0; // vector3 y index in the positions array
  30572. var v3z = 0; // vector3 z index in the positions array
  30573. var computeFacetNormals = false;
  30574. var computeFacetPositions = false;
  30575. var computeFacetPartitioning = false;
  30576. var computeDepthSort = false;
  30577. var faceNormalSign = 1;
  30578. var ratio = 0;
  30579. var distanceTo = null;
  30580. if (options) {
  30581. computeFacetNormals = (options.facetNormals) ? true : false;
  30582. computeFacetPositions = (options.facetPositions) ? true : false;
  30583. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  30584. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  30585. ratio = options.ratio || 0;
  30586. computeDepthSort = (options.depthSort) ? true : false;
  30587. distanceTo = (options.distanceTo);
  30588. if (computeDepthSort) {
  30589. if (distanceTo === undefined) {
  30590. distanceTo = BABYLON.Vector3.Zero();
  30591. }
  30592. var depthSortedFacets = options.depthSortedFacets;
  30593. }
  30594. }
  30595. // facetPartitioning reinit if needed
  30596. var xSubRatio = 0;
  30597. var ySubRatio = 0;
  30598. var zSubRatio = 0;
  30599. var subSq = 0;
  30600. if (computeFacetPartitioning && options && options.bbSize) {
  30601. var ox = 0; // X partitioning index for facet position
  30602. var oy = 0; // Y partinioning index for facet position
  30603. var oz = 0; // Z partinioning index for facet position
  30604. var b1x = 0; // X partitioning index for facet v1 vertex
  30605. var b1y = 0; // Y partitioning index for facet v1 vertex
  30606. var b1z = 0; // z partitioning index for facet v1 vertex
  30607. var b2x = 0; // X partitioning index for facet v2 vertex
  30608. var b2y = 0; // Y partitioning index for facet v2 vertex
  30609. var b2z = 0; // Z partitioning index for facet v2 vertex
  30610. var b3x = 0; // X partitioning index for facet v3 vertex
  30611. var b3y = 0; // Y partitioning index for facet v3 vertex
  30612. var b3z = 0; // Z partitioning index for facet v3 vertex
  30613. var block_idx_o = 0; // facet barycenter block index
  30614. var block_idx_v1 = 0; // v1 vertex block index
  30615. var block_idx_v2 = 0; // v2 vertex block index
  30616. var block_idx_v3 = 0; // v3 vertex block index
  30617. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  30618. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  30619. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  30620. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  30621. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  30622. subSq = options.subDiv.max * options.subDiv.max;
  30623. options.facetPartitioning.length = 0;
  30624. }
  30625. // reset the normals
  30626. for (index = 0; index < positions.length; index++) {
  30627. normals[index] = 0.0;
  30628. }
  30629. // Loop : 1 indice triplet = 1 facet
  30630. var nbFaces = (indices.length / 3) | 0;
  30631. for (index = 0; index < nbFaces; index++) {
  30632. // get the indexes of the coordinates of each vertex of the facet
  30633. v1x = indices[index * 3] * 3;
  30634. v1y = v1x + 1;
  30635. v1z = v1x + 2;
  30636. v2x = indices[index * 3 + 1] * 3;
  30637. v2y = v2x + 1;
  30638. v2z = v2x + 2;
  30639. v3x = indices[index * 3 + 2] * 3;
  30640. v3y = v3x + 1;
  30641. v3z = v3x + 2;
  30642. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  30643. p1p2y = positions[v1y] - positions[v2y];
  30644. p1p2z = positions[v1z] - positions[v2z];
  30645. p3p2x = positions[v3x] - positions[v2x];
  30646. p3p2y = positions[v3y] - positions[v2y];
  30647. p3p2z = positions[v3z] - positions[v2z];
  30648. // compute the face normal with the cross product
  30649. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  30650. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  30651. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  30652. // normalize this normal and store it in the array facetData
  30653. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30654. length = (length === 0) ? 1.0 : length;
  30655. faceNormalx /= length;
  30656. faceNormaly /= length;
  30657. faceNormalz /= length;
  30658. if (computeFacetNormals && options) {
  30659. options.facetNormals[index].x = faceNormalx;
  30660. options.facetNormals[index].y = faceNormaly;
  30661. options.facetNormals[index].z = faceNormalz;
  30662. }
  30663. if (computeFacetPositions && options) {
  30664. // compute and the facet barycenter coordinates in the array facetPositions
  30665. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  30666. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  30667. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  30668. }
  30669. if (computeFacetPartitioning && options) {
  30670. // store the facet indexes in arrays in the main facetPartitioning array :
  30671. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  30672. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  30673. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  30674. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  30675. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30676. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30677. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30678. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30679. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30680. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30681. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30682. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30683. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30684. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  30685. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  30686. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  30687. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  30688. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  30689. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  30690. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  30691. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  30692. // push each facet index in each block containing the vertex
  30693. options.facetPartitioning[block_idx_v1].push(index);
  30694. if (block_idx_v2 != block_idx_v1) {
  30695. options.facetPartitioning[block_idx_v2].push(index);
  30696. }
  30697. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  30698. options.facetPartitioning[block_idx_v3].push(index);
  30699. }
  30700. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  30701. options.facetPartitioning[block_idx_o].push(index);
  30702. }
  30703. }
  30704. if (computeDepthSort && options && options.facetPositions) {
  30705. var dsf = depthSortedFacets[index];
  30706. dsf.ind = index * 3;
  30707. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  30708. }
  30709. // compute the normals anyway
  30710. normals[v1x] += faceNormalx; // accumulate all the normals per face
  30711. normals[v1y] += faceNormaly;
  30712. normals[v1z] += faceNormalz;
  30713. normals[v2x] += faceNormalx;
  30714. normals[v2y] += faceNormaly;
  30715. normals[v2z] += faceNormalz;
  30716. normals[v3x] += faceNormalx;
  30717. normals[v3y] += faceNormaly;
  30718. normals[v3z] += faceNormalz;
  30719. }
  30720. // last normalization of each normal
  30721. for (index = 0; index < normals.length / 3; index++) {
  30722. faceNormalx = normals[index * 3];
  30723. faceNormaly = normals[index * 3 + 1];
  30724. faceNormalz = normals[index * 3 + 2];
  30725. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30726. length = (length === 0) ? 1.0 : length;
  30727. faceNormalx /= length;
  30728. faceNormaly /= length;
  30729. faceNormalz /= length;
  30730. normals[index * 3] = faceNormalx;
  30731. normals[index * 3 + 1] = faceNormaly;
  30732. normals[index * 3 + 2] = faceNormalz;
  30733. }
  30734. };
  30735. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  30736. var li = indices.length;
  30737. var ln = normals.length;
  30738. var i;
  30739. var n;
  30740. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30741. switch (sideOrientation) {
  30742. case BABYLON.Mesh.FRONTSIDE:
  30743. // nothing changed
  30744. break;
  30745. case BABYLON.Mesh.BACKSIDE:
  30746. var tmp;
  30747. // indices
  30748. for (i = 0; i < li; i += 3) {
  30749. tmp = indices[i];
  30750. indices[i] = indices[i + 2];
  30751. indices[i + 2] = tmp;
  30752. }
  30753. // normals
  30754. for (n = 0; n < ln; n++) {
  30755. normals[n] = -normals[n];
  30756. }
  30757. break;
  30758. case BABYLON.Mesh.DOUBLESIDE:
  30759. // positions
  30760. var lp = positions.length;
  30761. var l = lp / 3;
  30762. for (var p = 0; p < lp; p++) {
  30763. positions[lp + p] = positions[p];
  30764. }
  30765. // indices
  30766. for (i = 0; i < li; i += 3) {
  30767. indices[i + li] = indices[i + 2] + l;
  30768. indices[i + 1 + li] = indices[i + 1] + l;
  30769. indices[i + 2 + li] = indices[i] + l;
  30770. }
  30771. // normals
  30772. for (n = 0; n < ln; n++) {
  30773. normals[ln + n] = -normals[n];
  30774. }
  30775. // uvs
  30776. var lu = uvs.length;
  30777. var u = 0;
  30778. for (u = 0; u < lu; u++) {
  30779. uvs[u + lu] = uvs[u];
  30780. }
  30781. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30782. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30783. u = 0;
  30784. for (i = 0; i < lu / 2; i++) {
  30785. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  30786. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  30787. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  30788. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  30789. u += 2;
  30790. }
  30791. break;
  30792. }
  30793. };
  30794. /**
  30795. * Creates a new VertexData from the imported parameters.
  30796. */
  30797. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  30798. var vertexData = new VertexData();
  30799. // positions
  30800. var positions = parsedVertexData.positions;
  30801. if (positions) {
  30802. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  30803. }
  30804. // normals
  30805. var normals = parsedVertexData.normals;
  30806. if (normals) {
  30807. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  30808. }
  30809. // tangents
  30810. var tangents = parsedVertexData.tangents;
  30811. if (tangents) {
  30812. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  30813. }
  30814. // uvs
  30815. var uvs = parsedVertexData.uvs;
  30816. if (uvs) {
  30817. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  30818. }
  30819. // uv2s
  30820. var uv2s = parsedVertexData.uv2s;
  30821. if (uv2s) {
  30822. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  30823. }
  30824. // uv3s
  30825. var uv3s = parsedVertexData.uv3s;
  30826. if (uv3s) {
  30827. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  30828. }
  30829. // uv4s
  30830. var uv4s = parsedVertexData.uv4s;
  30831. if (uv4s) {
  30832. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  30833. }
  30834. // uv5s
  30835. var uv5s = parsedVertexData.uv5s;
  30836. if (uv5s) {
  30837. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  30838. }
  30839. // uv6s
  30840. var uv6s = parsedVertexData.uv6s;
  30841. if (uv6s) {
  30842. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  30843. }
  30844. // colors
  30845. var colors = parsedVertexData.colors;
  30846. if (colors) {
  30847. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  30848. }
  30849. // matricesIndices
  30850. var matricesIndices = parsedVertexData.matricesIndices;
  30851. if (matricesIndices) {
  30852. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  30853. }
  30854. // matricesWeights
  30855. var matricesWeights = parsedVertexData.matricesWeights;
  30856. if (matricesWeights) {
  30857. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  30858. }
  30859. // indices
  30860. var indices = parsedVertexData.indices;
  30861. if (indices) {
  30862. vertexData.indices = indices;
  30863. }
  30864. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  30865. };
  30866. return VertexData;
  30867. }());
  30868. BABYLON.VertexData = VertexData;
  30869. })(BABYLON || (BABYLON = {}));
  30870. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  30871. var BABYLON;
  30872. (function (BABYLON) {
  30873. var Geometry = /** @class */ (function () {
  30874. function Geometry(id, scene, vertexData, updatable, mesh) {
  30875. if (updatable === void 0) { updatable = false; }
  30876. if (mesh === void 0) { mesh = null; }
  30877. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30878. this._totalVertices = 0;
  30879. this._isDisposed = false;
  30880. this._indexBufferIsUpdatable = false;
  30881. this.id = id;
  30882. this._engine = scene.getEngine();
  30883. this._meshes = [];
  30884. this._scene = scene;
  30885. //Init vertex buffer cache
  30886. this._vertexBuffers = {};
  30887. this._indices = [];
  30888. this._updatable = updatable;
  30889. // vertexData
  30890. if (vertexData) {
  30891. this.setAllVerticesData(vertexData, updatable);
  30892. }
  30893. else {
  30894. this._totalVertices = 0;
  30895. this._indices = [];
  30896. }
  30897. if (this._engine.getCaps().vertexArrayObject) {
  30898. this._vertexArrayObjects = {};
  30899. }
  30900. // applyToMesh
  30901. if (mesh) {
  30902. if (mesh.getClassName() === "LinesMesh") {
  30903. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  30904. this.updateExtend();
  30905. }
  30906. this.applyToMesh(mesh);
  30907. mesh.computeWorldMatrix(true);
  30908. }
  30909. }
  30910. Object.defineProperty(Geometry.prototype, "boundingBias", {
  30911. /**
  30912. * 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
  30913. * @returns The Bias Vector
  30914. */
  30915. get: function () {
  30916. return this._boundingBias;
  30917. },
  30918. set: function (value) {
  30919. if (this._boundingBias && this._boundingBias.equals(value)) {
  30920. return;
  30921. }
  30922. this._boundingBias = value.clone();
  30923. this.updateBoundingInfo(true, null);
  30924. },
  30925. enumerable: true,
  30926. configurable: true
  30927. });
  30928. Geometry.CreateGeometryForMesh = function (mesh) {
  30929. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  30930. geometry.applyToMesh(mesh);
  30931. return geometry;
  30932. };
  30933. Object.defineProperty(Geometry.prototype, "extend", {
  30934. get: function () {
  30935. return this._extend;
  30936. },
  30937. enumerable: true,
  30938. configurable: true
  30939. });
  30940. Geometry.prototype.getScene = function () {
  30941. return this._scene;
  30942. };
  30943. Geometry.prototype.getEngine = function () {
  30944. return this._engine;
  30945. };
  30946. Geometry.prototype.isReady = function () {
  30947. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  30948. };
  30949. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  30950. get: function () {
  30951. for (var index = 0; index < this._meshes.length; index++) {
  30952. if (!this._meshes[index].doNotSerialize) {
  30953. return false;
  30954. }
  30955. }
  30956. return true;
  30957. },
  30958. enumerable: true,
  30959. configurable: true
  30960. });
  30961. Geometry.prototype._rebuild = function () {
  30962. if (this._vertexArrayObjects) {
  30963. this._vertexArrayObjects = {};
  30964. }
  30965. // Index buffer
  30966. if (this._meshes.length !== 0 && this._indices) {
  30967. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  30968. }
  30969. // Vertex buffers
  30970. for (var key in this._vertexBuffers) {
  30971. var vertexBuffer = this._vertexBuffers[key];
  30972. vertexBuffer._rebuild();
  30973. }
  30974. };
  30975. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  30976. vertexData.applyToGeometry(this, updatable);
  30977. this.notifyUpdate();
  30978. };
  30979. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  30980. if (updatable === void 0) { updatable = false; }
  30981. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  30982. this.setVerticesBuffer(buffer);
  30983. };
  30984. Geometry.prototype.removeVerticesData = function (kind) {
  30985. if (this._vertexBuffers[kind]) {
  30986. this._vertexBuffers[kind].dispose();
  30987. delete this._vertexBuffers[kind];
  30988. }
  30989. };
  30990. Geometry.prototype.setVerticesBuffer = function (buffer) {
  30991. var kind = buffer.getKind();
  30992. if (this._vertexBuffers[kind]) {
  30993. this._vertexBuffers[kind].dispose();
  30994. }
  30995. this._vertexBuffers[kind] = buffer;
  30996. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30997. var data = buffer.getData();
  30998. var stride = buffer.getStrideSize();
  30999. this._totalVertices = data.length / stride;
  31000. this.updateExtend(data, stride);
  31001. this._resetPointsArrayCache();
  31002. var meshes = this._meshes;
  31003. var numOfMeshes = meshes.length;
  31004. for (var index = 0; index < numOfMeshes; index++) {
  31005. var mesh = meshes[index];
  31006. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31007. mesh._createGlobalSubMesh(false);
  31008. mesh.computeWorldMatrix(true);
  31009. }
  31010. }
  31011. this.notifyUpdate(kind);
  31012. if (this._vertexArrayObjects) {
  31013. this._disposeVertexArrayObjects();
  31014. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  31015. }
  31016. };
  31017. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  31018. var vertexBuffer = this.getVertexBuffer(kind);
  31019. if (!vertexBuffer) {
  31020. return;
  31021. }
  31022. vertexBuffer.updateDirectly(data, offset);
  31023. this.notifyUpdate(kind);
  31024. };
  31025. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  31026. if (updateExtends === void 0) { updateExtends = false; }
  31027. var vertexBuffer = this.getVertexBuffer(kind);
  31028. if (!vertexBuffer) {
  31029. return;
  31030. }
  31031. vertexBuffer.update(data);
  31032. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31033. var stride = vertexBuffer.getStrideSize();
  31034. this._totalVertices = data.length / stride;
  31035. this.updateBoundingInfo(updateExtends, data);
  31036. }
  31037. this.notifyUpdate(kind);
  31038. };
  31039. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  31040. if (updateExtends) {
  31041. this.updateExtend(data);
  31042. }
  31043. var meshes = this._meshes;
  31044. var numOfMeshes = meshes.length;
  31045. this._resetPointsArrayCache();
  31046. for (var index = 0; index < numOfMeshes; index++) {
  31047. var mesh = meshes[index];
  31048. if (updateExtends) {
  31049. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31050. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31051. var subMesh = mesh.subMeshes[subIndex];
  31052. subMesh.refreshBoundingInfo();
  31053. }
  31054. }
  31055. }
  31056. };
  31057. Geometry.prototype._bind = function (effect, indexToBind) {
  31058. if (!effect) {
  31059. return;
  31060. }
  31061. if (indexToBind === undefined) {
  31062. indexToBind = this._indexBuffer;
  31063. }
  31064. var vbs = this.getVertexBuffers();
  31065. if (!vbs) {
  31066. return;
  31067. }
  31068. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  31069. this._engine.bindBuffers(vbs, indexToBind, effect);
  31070. return;
  31071. }
  31072. // Using VAO
  31073. if (!this._vertexArrayObjects[effect.key]) {
  31074. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  31075. }
  31076. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  31077. };
  31078. Geometry.prototype.getTotalVertices = function () {
  31079. if (!this.isReady()) {
  31080. return 0;
  31081. }
  31082. return this._totalVertices;
  31083. };
  31084. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31085. var vertexBuffer = this.getVertexBuffer(kind);
  31086. if (!vertexBuffer) {
  31087. return null;
  31088. }
  31089. var orig = vertexBuffer.getData();
  31090. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  31091. return orig;
  31092. }
  31093. else {
  31094. var len = orig.length;
  31095. var copy = [];
  31096. for (var i = 0; i < len; i++) {
  31097. copy.push(orig[i]);
  31098. }
  31099. return copy;
  31100. }
  31101. };
  31102. /**
  31103. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31104. * Possible `kind` values :
  31105. * - BABYLON.VertexBuffer.PositionKind
  31106. * - BABYLON.VertexBuffer.UVKind
  31107. * - BABYLON.VertexBuffer.UV2Kind
  31108. * - BABYLON.VertexBuffer.UV3Kind
  31109. * - BABYLON.VertexBuffer.UV4Kind
  31110. * - BABYLON.VertexBuffer.UV5Kind
  31111. * - BABYLON.VertexBuffer.UV6Kind
  31112. * - BABYLON.VertexBuffer.ColorKind
  31113. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31114. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31115. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31116. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31117. */
  31118. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  31119. var vb = this._vertexBuffers[kind];
  31120. if (!vb) {
  31121. return false;
  31122. }
  31123. return vb.isUpdatable();
  31124. };
  31125. Geometry.prototype.getVertexBuffer = function (kind) {
  31126. if (!this.isReady()) {
  31127. return null;
  31128. }
  31129. return this._vertexBuffers[kind];
  31130. };
  31131. Geometry.prototype.getVertexBuffers = function () {
  31132. if (!this.isReady()) {
  31133. return null;
  31134. }
  31135. return this._vertexBuffers;
  31136. };
  31137. Geometry.prototype.isVerticesDataPresent = function (kind) {
  31138. if (!this._vertexBuffers) {
  31139. if (this._delayInfo) {
  31140. return this._delayInfo.indexOf(kind) !== -1;
  31141. }
  31142. return false;
  31143. }
  31144. return this._vertexBuffers[kind] !== undefined;
  31145. };
  31146. Geometry.prototype.getVerticesDataKinds = function () {
  31147. var result = [];
  31148. var kind;
  31149. if (!this._vertexBuffers && this._delayInfo) {
  31150. for (kind in this._delayInfo) {
  31151. result.push(kind);
  31152. }
  31153. }
  31154. else {
  31155. for (kind in this._vertexBuffers) {
  31156. result.push(kind);
  31157. }
  31158. }
  31159. return result;
  31160. };
  31161. Geometry.prototype.updateIndices = function (indices, offset) {
  31162. if (!this._indexBuffer) {
  31163. return;
  31164. }
  31165. if (!this._indexBufferIsUpdatable) {
  31166. this.setIndices(indices, null, true);
  31167. }
  31168. else {
  31169. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  31170. }
  31171. };
  31172. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  31173. if (totalVertices === void 0) { totalVertices = null; }
  31174. if (updatable === void 0) { updatable = false; }
  31175. if (this._indexBuffer) {
  31176. this._engine._releaseBuffer(this._indexBuffer);
  31177. }
  31178. this._disposeVertexArrayObjects();
  31179. this._indices = indices;
  31180. this._indexBufferIsUpdatable = updatable;
  31181. if (this._meshes.length !== 0 && this._indices) {
  31182. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  31183. }
  31184. if (totalVertices != undefined) {
  31185. this._totalVertices = totalVertices;
  31186. }
  31187. var meshes = this._meshes;
  31188. var numOfMeshes = meshes.length;
  31189. for (var index = 0; index < numOfMeshes; index++) {
  31190. meshes[index]._createGlobalSubMesh(true);
  31191. }
  31192. this.notifyUpdate();
  31193. };
  31194. Geometry.prototype.getTotalIndices = function () {
  31195. if (!this.isReady()) {
  31196. return 0;
  31197. }
  31198. return this._indices.length;
  31199. };
  31200. Geometry.prototype.getIndices = function (copyWhenShared) {
  31201. if (!this.isReady()) {
  31202. return null;
  31203. }
  31204. var orig = this._indices;
  31205. if (!copyWhenShared || this._meshes.length === 1) {
  31206. return orig;
  31207. }
  31208. else {
  31209. var len = orig.length;
  31210. var copy = [];
  31211. for (var i = 0; i < len; i++) {
  31212. copy.push(orig[i]);
  31213. }
  31214. return copy;
  31215. }
  31216. };
  31217. Geometry.prototype.getIndexBuffer = function () {
  31218. if (!this.isReady()) {
  31219. return null;
  31220. }
  31221. return this._indexBuffer;
  31222. };
  31223. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  31224. if (effect === void 0) { effect = null; }
  31225. if (!effect || !this._vertexArrayObjects) {
  31226. return;
  31227. }
  31228. if (this._vertexArrayObjects[effect.key]) {
  31229. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  31230. delete this._vertexArrayObjects[effect.key];
  31231. }
  31232. };
  31233. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  31234. var meshes = this._meshes;
  31235. var index = meshes.indexOf(mesh);
  31236. if (index === -1) {
  31237. return;
  31238. }
  31239. meshes.splice(index, 1);
  31240. mesh._geometry = null;
  31241. if (meshes.length === 0 && shouldDispose) {
  31242. this.dispose();
  31243. }
  31244. };
  31245. Geometry.prototype.applyToMesh = function (mesh) {
  31246. if (mesh._geometry === this) {
  31247. return;
  31248. }
  31249. var previousGeometry = mesh._geometry;
  31250. if (previousGeometry) {
  31251. previousGeometry.releaseForMesh(mesh);
  31252. }
  31253. var meshes = this._meshes;
  31254. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  31255. mesh._geometry = this;
  31256. this._scene.pushGeometry(this);
  31257. meshes.push(mesh);
  31258. if (this.isReady()) {
  31259. this._applyToMesh(mesh);
  31260. }
  31261. else {
  31262. mesh._boundingInfo = this._boundingInfo;
  31263. }
  31264. };
  31265. Geometry.prototype.updateExtend = function (data, stride) {
  31266. if (data === void 0) { data = null; }
  31267. if (!data) {
  31268. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  31269. }
  31270. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  31271. };
  31272. Geometry.prototype._applyToMesh = function (mesh) {
  31273. var numOfMeshes = this._meshes.length;
  31274. // vertexBuffers
  31275. for (var kind in this._vertexBuffers) {
  31276. if (numOfMeshes === 1) {
  31277. this._vertexBuffers[kind].create();
  31278. }
  31279. var buffer = this._vertexBuffers[kind].getBuffer();
  31280. if (buffer)
  31281. buffer.references = numOfMeshes;
  31282. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31283. if (!this._extend) {
  31284. this.updateExtend(this._vertexBuffers[kind].getData());
  31285. }
  31286. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31287. mesh._createGlobalSubMesh(false);
  31288. //bounding info was just created again, world matrix should be applied again.
  31289. mesh._updateBoundingInfo();
  31290. }
  31291. }
  31292. // indexBuffer
  31293. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  31294. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31295. }
  31296. if (this._indexBuffer) {
  31297. this._indexBuffer.references = numOfMeshes;
  31298. }
  31299. };
  31300. Geometry.prototype.notifyUpdate = function (kind) {
  31301. if (this.onGeometryUpdated) {
  31302. this.onGeometryUpdated(this, kind);
  31303. }
  31304. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  31305. var mesh = _a[_i];
  31306. mesh._markSubMeshesAsAttributesDirty();
  31307. }
  31308. };
  31309. Geometry.prototype.load = function (scene, onLoaded) {
  31310. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31311. return;
  31312. }
  31313. if (this.isReady()) {
  31314. if (onLoaded) {
  31315. onLoaded();
  31316. }
  31317. return;
  31318. }
  31319. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31320. this._queueLoad(scene, onLoaded);
  31321. };
  31322. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  31323. var _this = this;
  31324. if (!this.delayLoadingFile) {
  31325. return;
  31326. }
  31327. scene._addPendingData(this);
  31328. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31329. if (!_this._delayLoadingFunction) {
  31330. return;
  31331. }
  31332. _this._delayLoadingFunction(JSON.parse(data), _this);
  31333. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31334. _this._delayInfo = [];
  31335. scene._removePendingData(_this);
  31336. var meshes = _this._meshes;
  31337. var numOfMeshes = meshes.length;
  31338. for (var index = 0; index < numOfMeshes; index++) {
  31339. _this._applyToMesh(meshes[index]);
  31340. }
  31341. if (onLoaded) {
  31342. onLoaded();
  31343. }
  31344. }, function () { }, scene.database);
  31345. };
  31346. /**
  31347. * Invert the geometry to move from a right handed system to a left handed one.
  31348. */
  31349. Geometry.prototype.toLeftHanded = function () {
  31350. // Flip faces
  31351. var tIndices = this.getIndices(false);
  31352. if (tIndices != null && tIndices.length > 0) {
  31353. for (var i = 0; i < tIndices.length; i += 3) {
  31354. var tTemp = tIndices[i + 0];
  31355. tIndices[i + 0] = tIndices[i + 2];
  31356. tIndices[i + 2] = tTemp;
  31357. }
  31358. this.setIndices(tIndices);
  31359. }
  31360. // Negate position.z
  31361. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  31362. if (tPositions != null && tPositions.length > 0) {
  31363. for (var i = 0; i < tPositions.length; i += 3) {
  31364. tPositions[i + 2] = -tPositions[i + 2];
  31365. }
  31366. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  31367. }
  31368. // Negate normal.z
  31369. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  31370. if (tNormals != null && tNormals.length > 0) {
  31371. for (var i = 0; i < tNormals.length; i += 3) {
  31372. tNormals[i + 2] = -tNormals[i + 2];
  31373. }
  31374. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  31375. }
  31376. };
  31377. // Cache
  31378. Geometry.prototype._resetPointsArrayCache = function () {
  31379. this._positions = null;
  31380. };
  31381. Geometry.prototype._generatePointsArray = function () {
  31382. if (this._positions)
  31383. return true;
  31384. this._positions = [];
  31385. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31386. if (!data) {
  31387. return false;
  31388. }
  31389. for (var index = 0; index < data.length; index += 3) {
  31390. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  31391. }
  31392. return true;
  31393. };
  31394. Geometry.prototype.isDisposed = function () {
  31395. return this._isDisposed;
  31396. };
  31397. Geometry.prototype._disposeVertexArrayObjects = function () {
  31398. if (this._vertexArrayObjects) {
  31399. for (var kind in this._vertexArrayObjects) {
  31400. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  31401. }
  31402. this._vertexArrayObjects = {};
  31403. }
  31404. };
  31405. Geometry.prototype.dispose = function () {
  31406. var meshes = this._meshes;
  31407. var numOfMeshes = meshes.length;
  31408. var index;
  31409. for (index = 0; index < numOfMeshes; index++) {
  31410. this.releaseForMesh(meshes[index]);
  31411. }
  31412. this._meshes = [];
  31413. this._disposeVertexArrayObjects();
  31414. for (var kind in this._vertexBuffers) {
  31415. this._vertexBuffers[kind].dispose();
  31416. }
  31417. this._vertexBuffers = {};
  31418. this._totalVertices = 0;
  31419. if (this._indexBuffer) {
  31420. this._engine._releaseBuffer(this._indexBuffer);
  31421. }
  31422. this._indexBuffer = null;
  31423. this._indices = [];
  31424. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31425. this.delayLoadingFile = null;
  31426. this._delayLoadingFunction = null;
  31427. this._delayInfo = [];
  31428. this._boundingInfo = null;
  31429. this._scene.removeGeometry(this);
  31430. this._isDisposed = true;
  31431. };
  31432. Geometry.prototype.copy = function (id) {
  31433. var vertexData = new BABYLON.VertexData();
  31434. vertexData.indices = [];
  31435. var indices = this.getIndices();
  31436. if (indices) {
  31437. for (var index = 0; index < indices.length; index++) {
  31438. vertexData.indices.push(indices[index]);
  31439. }
  31440. }
  31441. var updatable = false;
  31442. var stopChecking = false;
  31443. var kind;
  31444. for (kind in this._vertexBuffers) {
  31445. // using slice() to make a copy of the array and not just reference it
  31446. var data = this.getVerticesData(kind);
  31447. if (data instanceof Float32Array) {
  31448. vertexData.set(new Float32Array(data), kind);
  31449. }
  31450. else {
  31451. vertexData.set(data.slice(0), kind);
  31452. }
  31453. if (!stopChecking) {
  31454. var vb = this.getVertexBuffer(kind);
  31455. if (vb) {
  31456. updatable = vb.isUpdatable();
  31457. stopChecking = !updatable;
  31458. }
  31459. }
  31460. }
  31461. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  31462. geometry.delayLoadState = this.delayLoadState;
  31463. geometry.delayLoadingFile = this.delayLoadingFile;
  31464. geometry._delayLoadingFunction = this._delayLoadingFunction;
  31465. for (kind in this._delayInfo) {
  31466. geometry._delayInfo = geometry._delayInfo || [];
  31467. geometry._delayInfo.push(kind);
  31468. }
  31469. // Bounding info
  31470. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31471. return geometry;
  31472. };
  31473. Geometry.prototype.serialize = function () {
  31474. var serializationObject = {};
  31475. serializationObject.id = this.id;
  31476. serializationObject.updatable = this._updatable;
  31477. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  31478. serializationObject.tags = BABYLON.Tags.GetTags(this);
  31479. }
  31480. return serializationObject;
  31481. };
  31482. Geometry.prototype.toNumberArray = function (origin) {
  31483. if (Array.isArray(origin)) {
  31484. return origin;
  31485. }
  31486. else {
  31487. return Array.prototype.slice.call(origin);
  31488. }
  31489. };
  31490. Geometry.prototype.serializeVerticeData = function () {
  31491. var serializationObject = this.serialize();
  31492. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31493. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  31494. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  31495. serializationObject.positions._updatable = true;
  31496. }
  31497. }
  31498. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31499. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  31500. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  31501. serializationObject.normals._updatable = true;
  31502. }
  31503. }
  31504. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31505. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  31506. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  31507. serializationObject.uvs._updatable = true;
  31508. }
  31509. }
  31510. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31511. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  31512. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  31513. serializationObject.uv2s._updatable = true;
  31514. }
  31515. }
  31516. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  31517. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  31518. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  31519. serializationObject.uv3s._updatable = true;
  31520. }
  31521. }
  31522. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  31523. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  31524. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  31525. serializationObject.uv4s._updatable = true;
  31526. }
  31527. }
  31528. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  31529. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  31530. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  31531. serializationObject.uv5s._updatable = true;
  31532. }
  31533. }
  31534. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  31535. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  31536. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  31537. serializationObject.uv6s._updatable = true;
  31538. }
  31539. }
  31540. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  31541. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  31542. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  31543. serializationObject.colors._updatable = true;
  31544. }
  31545. }
  31546. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31547. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  31548. serializationObject.matricesIndices._isExpanded = true;
  31549. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31550. serializationObject.matricesIndices._updatable = true;
  31551. }
  31552. }
  31553. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31554. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  31555. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31556. serializationObject.matricesWeights._updatable = true;
  31557. }
  31558. }
  31559. serializationObject.indices = this.toNumberArray(this.getIndices());
  31560. return serializationObject;
  31561. };
  31562. // Statics
  31563. Geometry.ExtractFromMesh = function (mesh, id) {
  31564. var geometry = mesh._geometry;
  31565. if (!geometry) {
  31566. return null;
  31567. }
  31568. return geometry.copy(id);
  31569. };
  31570. /**
  31571. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  31572. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  31573. * Be aware Math.random() could cause collisions, but:
  31574. * "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"
  31575. */
  31576. Geometry.RandomId = function () {
  31577. return BABYLON.Tools.RandomId();
  31578. };
  31579. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  31580. var scene = mesh.getScene();
  31581. // Geometry
  31582. var geometryId = parsedGeometry.geometryId;
  31583. if (geometryId) {
  31584. var geometry = scene.getGeometryByID(geometryId);
  31585. if (geometry) {
  31586. geometry.applyToMesh(mesh);
  31587. }
  31588. }
  31589. else if (parsedGeometry instanceof ArrayBuffer) {
  31590. var binaryInfo = mesh._binaryInfo;
  31591. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  31592. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  31593. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  31594. }
  31595. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  31596. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  31597. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  31598. }
  31599. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  31600. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  31601. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  31602. }
  31603. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  31604. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  31605. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  31606. }
  31607. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  31608. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  31609. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  31610. }
  31611. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  31612. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  31613. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  31614. }
  31615. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  31616. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  31617. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  31618. }
  31619. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  31620. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  31621. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  31622. }
  31623. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  31624. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  31625. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  31626. }
  31627. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  31628. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  31629. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  31630. }
  31631. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  31632. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  31633. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  31634. }
  31635. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  31636. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  31637. mesh.setIndices(indicesData, null);
  31638. }
  31639. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  31640. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  31641. mesh.subMeshes = [];
  31642. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  31643. var materialIndex = subMeshesData[(i * 5) + 0];
  31644. var verticesStart = subMeshesData[(i * 5) + 1];
  31645. var verticesCount = subMeshesData[(i * 5) + 2];
  31646. var indexStart = subMeshesData[(i * 5) + 3];
  31647. var indexCount = subMeshesData[(i * 5) + 4];
  31648. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  31649. }
  31650. }
  31651. }
  31652. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  31653. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  31654. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  31655. if (parsedGeometry.uvs) {
  31656. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  31657. }
  31658. if (parsedGeometry.uvs2) {
  31659. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  31660. }
  31661. if (parsedGeometry.uvs3) {
  31662. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  31663. }
  31664. if (parsedGeometry.uvs4) {
  31665. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  31666. }
  31667. if (parsedGeometry.uvs5) {
  31668. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  31669. }
  31670. if (parsedGeometry.uvs6) {
  31671. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  31672. }
  31673. if (parsedGeometry.colors) {
  31674. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  31675. }
  31676. if (parsedGeometry.matricesIndices) {
  31677. if (!parsedGeometry.matricesIndices._isExpanded) {
  31678. var floatIndices = [];
  31679. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  31680. var matricesIndex = parsedGeometry.matricesIndices[i];
  31681. floatIndices.push(matricesIndex & 0x000000FF);
  31682. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31683. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31684. floatIndices.push(matricesIndex >> 24);
  31685. }
  31686. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  31687. }
  31688. else {
  31689. delete parsedGeometry.matricesIndices._isExpanded;
  31690. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  31691. }
  31692. }
  31693. if (parsedGeometry.matricesIndicesExtra) {
  31694. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  31695. var floatIndices = [];
  31696. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  31697. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  31698. floatIndices.push(matricesIndex & 0x000000FF);
  31699. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31700. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31701. floatIndices.push(matricesIndex >> 24);
  31702. }
  31703. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  31704. }
  31705. else {
  31706. delete parsedGeometry.matricesIndices._isExpanded;
  31707. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  31708. }
  31709. }
  31710. if (parsedGeometry.matricesWeights) {
  31711. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  31712. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  31713. }
  31714. if (parsedGeometry.matricesWeightsExtra) {
  31715. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  31716. }
  31717. mesh.setIndices(parsedGeometry.indices, null);
  31718. }
  31719. // SubMeshes
  31720. if (parsedGeometry.subMeshes) {
  31721. mesh.subMeshes = [];
  31722. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  31723. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  31724. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  31725. }
  31726. }
  31727. // Flat shading
  31728. if (mesh._shouldGenerateFlatShading) {
  31729. mesh.convertToFlatShadedMesh();
  31730. delete mesh._shouldGenerateFlatShading;
  31731. }
  31732. // Update
  31733. mesh.computeWorldMatrix(true);
  31734. // Octree
  31735. if (scene['_selectionOctree']) {
  31736. scene['_selectionOctree'].addMesh(mesh);
  31737. }
  31738. };
  31739. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  31740. var epsilon = 1e-3;
  31741. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  31742. return;
  31743. }
  31744. var noInfluenceBoneIndex = 0.0;
  31745. if (parsedGeometry.skeletonId > -1) {
  31746. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  31747. if (!skeleton) {
  31748. return;
  31749. }
  31750. noInfluenceBoneIndex = skeleton.bones.length;
  31751. }
  31752. else {
  31753. return;
  31754. }
  31755. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31756. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31757. var matricesWeights = parsedGeometry.matricesWeights;
  31758. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  31759. var influencers = parsedGeometry.numBoneInfluencer;
  31760. var size = matricesWeights.length;
  31761. for (var i = 0; i < size; i += 4) {
  31762. var weight = 0.0;
  31763. var firstZeroWeight = -1;
  31764. for (var j = 0; j < 4; j++) {
  31765. var w = matricesWeights[i + j];
  31766. weight += w;
  31767. if (w < epsilon && firstZeroWeight < 0) {
  31768. firstZeroWeight = j;
  31769. }
  31770. }
  31771. if (matricesWeightsExtra) {
  31772. for (var j = 0; j < 4; j++) {
  31773. var w = matricesWeightsExtra[i + j];
  31774. weight += w;
  31775. if (w < epsilon && firstZeroWeight < 0) {
  31776. firstZeroWeight = j + 4;
  31777. }
  31778. }
  31779. }
  31780. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  31781. firstZeroWeight = influencers - 1;
  31782. }
  31783. if (weight > epsilon) {
  31784. var mweight = 1.0 / weight;
  31785. for (var j = 0; j < 4; j++) {
  31786. matricesWeights[i + j] *= mweight;
  31787. }
  31788. if (matricesWeightsExtra) {
  31789. for (var j = 0; j < 4; j++) {
  31790. matricesWeightsExtra[i + j] *= mweight;
  31791. }
  31792. }
  31793. }
  31794. else {
  31795. if (firstZeroWeight >= 4) {
  31796. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  31797. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  31798. }
  31799. else {
  31800. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  31801. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  31802. }
  31803. }
  31804. }
  31805. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  31806. if (parsedGeometry.matricesWeightsExtra) {
  31807. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  31808. }
  31809. };
  31810. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  31811. if (scene.getGeometryByID(parsedVertexData.id)) {
  31812. return null; // null since geometry could be something else than a box...
  31813. }
  31814. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  31815. if (BABYLON.Tags) {
  31816. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  31817. }
  31818. if (parsedVertexData.delayLoadingFile) {
  31819. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31820. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  31821. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  31822. geometry._delayInfo = [];
  31823. if (parsedVertexData.hasUVs) {
  31824. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  31825. }
  31826. if (parsedVertexData.hasUVs2) {
  31827. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  31828. }
  31829. if (parsedVertexData.hasUVs3) {
  31830. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  31831. }
  31832. if (parsedVertexData.hasUVs4) {
  31833. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  31834. }
  31835. if (parsedVertexData.hasUVs5) {
  31836. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  31837. }
  31838. if (parsedVertexData.hasUVs6) {
  31839. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  31840. }
  31841. if (parsedVertexData.hasColors) {
  31842. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  31843. }
  31844. if (parsedVertexData.hasMatricesIndices) {
  31845. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31846. }
  31847. if (parsedVertexData.hasMatricesWeights) {
  31848. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31849. }
  31850. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  31851. }
  31852. else {
  31853. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  31854. }
  31855. scene.pushGeometry(geometry, true);
  31856. return geometry;
  31857. };
  31858. return Geometry;
  31859. }());
  31860. BABYLON.Geometry = Geometry;
  31861. /////// Primitives //////////////////////////////////////////////
  31862. (function (Geometry) {
  31863. var Primitives;
  31864. (function (Primitives) {
  31865. /// Abstract class
  31866. var _Primitive = /** @class */ (function (_super) {
  31867. __extends(_Primitive, _super);
  31868. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  31869. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  31870. if (mesh === void 0) { mesh = null; }
  31871. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  31872. _this._canBeRegenerated = _canBeRegenerated;
  31873. _this._beingRegenerated = true;
  31874. _this.regenerate();
  31875. _this._beingRegenerated = false;
  31876. return _this;
  31877. }
  31878. _Primitive.prototype.canBeRegenerated = function () {
  31879. return this._canBeRegenerated;
  31880. };
  31881. _Primitive.prototype.regenerate = function () {
  31882. if (!this._canBeRegenerated) {
  31883. return;
  31884. }
  31885. this._beingRegenerated = true;
  31886. this.setAllVerticesData(this._regenerateVertexData(), false);
  31887. this._beingRegenerated = false;
  31888. };
  31889. _Primitive.prototype.asNewGeometry = function (id) {
  31890. return _super.prototype.copy.call(this, id);
  31891. };
  31892. // overrides
  31893. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  31894. if (!this._beingRegenerated) {
  31895. return;
  31896. }
  31897. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  31898. };
  31899. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  31900. if (!this._beingRegenerated) {
  31901. return;
  31902. }
  31903. _super.prototype.setVerticesData.call(this, kind, data, false);
  31904. };
  31905. // to override
  31906. // protected
  31907. _Primitive.prototype._regenerateVertexData = function () {
  31908. throw new Error("Abstract method");
  31909. };
  31910. _Primitive.prototype.copy = function (id) {
  31911. throw new Error("Must be overriden in sub-classes.");
  31912. };
  31913. _Primitive.prototype.serialize = function () {
  31914. var serializationObject = _super.prototype.serialize.call(this);
  31915. serializationObject.canBeRegenerated = this.canBeRegenerated();
  31916. return serializationObject;
  31917. };
  31918. return _Primitive;
  31919. }(Geometry));
  31920. Primitives._Primitive = _Primitive;
  31921. var Ribbon = /** @class */ (function (_super) {
  31922. __extends(Ribbon, _super);
  31923. // Members
  31924. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  31925. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31926. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31927. _this.pathArray = pathArray;
  31928. _this.closeArray = closeArray;
  31929. _this.closePath = closePath;
  31930. _this.offset = offset;
  31931. _this.side = side;
  31932. return _this;
  31933. }
  31934. Ribbon.prototype._regenerateVertexData = function () {
  31935. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  31936. };
  31937. Ribbon.prototype.copy = function (id) {
  31938. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  31939. };
  31940. return Ribbon;
  31941. }(_Primitive));
  31942. Primitives.Ribbon = Ribbon;
  31943. var Box = /** @class */ (function (_super) {
  31944. __extends(Box, _super);
  31945. // Members
  31946. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  31947. if (mesh === void 0) { mesh = null; }
  31948. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31949. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31950. _this.size = size;
  31951. _this.side = side;
  31952. return _this;
  31953. }
  31954. Box.prototype._regenerateVertexData = function () {
  31955. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  31956. };
  31957. Box.prototype.copy = function (id) {
  31958. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  31959. };
  31960. Box.prototype.serialize = function () {
  31961. var serializationObject = _super.prototype.serialize.call(this);
  31962. serializationObject.size = this.size;
  31963. return serializationObject;
  31964. };
  31965. Box.Parse = function (parsedBox, scene) {
  31966. if (scene.getGeometryByID(parsedBox.id)) {
  31967. return null; // null since geometry could be something else than a box...
  31968. }
  31969. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  31970. if (BABYLON.Tags) {
  31971. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  31972. }
  31973. scene.pushGeometry(box, true);
  31974. return box;
  31975. };
  31976. return Box;
  31977. }(_Primitive));
  31978. Primitives.Box = Box;
  31979. var Sphere = /** @class */ (function (_super) {
  31980. __extends(Sphere, _super);
  31981. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  31982. if (mesh === void 0) { mesh = null; }
  31983. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31984. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31985. _this.segments = segments;
  31986. _this.diameter = diameter;
  31987. _this.side = side;
  31988. return _this;
  31989. }
  31990. Sphere.prototype._regenerateVertexData = function () {
  31991. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  31992. };
  31993. Sphere.prototype.copy = function (id) {
  31994. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  31995. };
  31996. Sphere.prototype.serialize = function () {
  31997. var serializationObject = _super.prototype.serialize.call(this);
  31998. serializationObject.segments = this.segments;
  31999. serializationObject.diameter = this.diameter;
  32000. return serializationObject;
  32001. };
  32002. Sphere.Parse = function (parsedSphere, scene) {
  32003. if (scene.getGeometryByID(parsedSphere.id)) {
  32004. return null; // null since geometry could be something else than a sphere...
  32005. }
  32006. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  32007. if (BABYLON.Tags) {
  32008. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  32009. }
  32010. scene.pushGeometry(sphere, true);
  32011. return sphere;
  32012. };
  32013. return Sphere;
  32014. }(_Primitive));
  32015. Primitives.Sphere = Sphere;
  32016. var Disc = /** @class */ (function (_super) {
  32017. __extends(Disc, _super);
  32018. // Members
  32019. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  32020. if (mesh === void 0) { mesh = null; }
  32021. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32022. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32023. _this.radius = radius;
  32024. _this.tessellation = tessellation;
  32025. _this.side = side;
  32026. return _this;
  32027. }
  32028. Disc.prototype._regenerateVertexData = function () {
  32029. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  32030. };
  32031. Disc.prototype.copy = function (id) {
  32032. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  32033. };
  32034. return Disc;
  32035. }(_Primitive));
  32036. Primitives.Disc = Disc;
  32037. var Cylinder = /** @class */ (function (_super) {
  32038. __extends(Cylinder, _super);
  32039. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  32040. if (subdivisions === void 0) { subdivisions = 1; }
  32041. if (mesh === void 0) { mesh = null; }
  32042. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32043. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32044. _this.height = height;
  32045. _this.diameterTop = diameterTop;
  32046. _this.diameterBottom = diameterBottom;
  32047. _this.tessellation = tessellation;
  32048. _this.subdivisions = subdivisions;
  32049. _this.side = side;
  32050. return _this;
  32051. }
  32052. Cylinder.prototype._regenerateVertexData = function () {
  32053. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  32054. };
  32055. Cylinder.prototype.copy = function (id) {
  32056. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  32057. };
  32058. Cylinder.prototype.serialize = function () {
  32059. var serializationObject = _super.prototype.serialize.call(this);
  32060. serializationObject.height = this.height;
  32061. serializationObject.diameterTop = this.diameterTop;
  32062. serializationObject.diameterBottom = this.diameterBottom;
  32063. serializationObject.tessellation = this.tessellation;
  32064. return serializationObject;
  32065. };
  32066. Cylinder.Parse = function (parsedCylinder, scene) {
  32067. if (scene.getGeometryByID(parsedCylinder.id)) {
  32068. return null; // null since geometry could be something else than a cylinder...
  32069. }
  32070. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  32071. if (BABYLON.Tags) {
  32072. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  32073. }
  32074. scene.pushGeometry(cylinder, true);
  32075. return cylinder;
  32076. };
  32077. return Cylinder;
  32078. }(_Primitive));
  32079. Primitives.Cylinder = Cylinder;
  32080. var Torus = /** @class */ (function (_super) {
  32081. __extends(Torus, _super);
  32082. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  32083. if (mesh === void 0) { mesh = null; }
  32084. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32085. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32086. _this.diameter = diameter;
  32087. _this.thickness = thickness;
  32088. _this.tessellation = tessellation;
  32089. _this.side = side;
  32090. return _this;
  32091. }
  32092. Torus.prototype._regenerateVertexData = function () {
  32093. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  32094. };
  32095. Torus.prototype.copy = function (id) {
  32096. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  32097. };
  32098. Torus.prototype.serialize = function () {
  32099. var serializationObject = _super.prototype.serialize.call(this);
  32100. serializationObject.diameter = this.diameter;
  32101. serializationObject.thickness = this.thickness;
  32102. serializationObject.tessellation = this.tessellation;
  32103. return serializationObject;
  32104. };
  32105. Torus.Parse = function (parsedTorus, scene) {
  32106. if (scene.getGeometryByID(parsedTorus.id)) {
  32107. return null; // null since geometry could be something else than a torus...
  32108. }
  32109. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  32110. if (BABYLON.Tags) {
  32111. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  32112. }
  32113. scene.pushGeometry(torus, true);
  32114. return torus;
  32115. };
  32116. return Torus;
  32117. }(_Primitive));
  32118. Primitives.Torus = Torus;
  32119. var Ground = /** @class */ (function (_super) {
  32120. __extends(Ground, _super);
  32121. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  32122. if (mesh === void 0) { mesh = null; }
  32123. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32124. _this.width = width;
  32125. _this.height = height;
  32126. _this.subdivisions = subdivisions;
  32127. return _this;
  32128. }
  32129. Ground.prototype._regenerateVertexData = function () {
  32130. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  32131. };
  32132. Ground.prototype.copy = function (id) {
  32133. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  32134. };
  32135. Ground.prototype.serialize = function () {
  32136. var serializationObject = _super.prototype.serialize.call(this);
  32137. serializationObject.width = this.width;
  32138. serializationObject.height = this.height;
  32139. serializationObject.subdivisions = this.subdivisions;
  32140. return serializationObject;
  32141. };
  32142. Ground.Parse = function (parsedGround, scene) {
  32143. if (scene.getGeometryByID(parsedGround.id)) {
  32144. return null; // null since geometry could be something else than a ground...
  32145. }
  32146. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  32147. if (BABYLON.Tags) {
  32148. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  32149. }
  32150. scene.pushGeometry(ground, true);
  32151. return ground;
  32152. };
  32153. return Ground;
  32154. }(_Primitive));
  32155. Primitives.Ground = Ground;
  32156. var TiledGround = /** @class */ (function (_super) {
  32157. __extends(TiledGround, _super);
  32158. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  32159. if (mesh === void 0) { mesh = null; }
  32160. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32161. _this.xmin = xmin;
  32162. _this.zmin = zmin;
  32163. _this.xmax = xmax;
  32164. _this.zmax = zmax;
  32165. _this.subdivisions = subdivisions;
  32166. _this.precision = precision;
  32167. return _this;
  32168. }
  32169. TiledGround.prototype._regenerateVertexData = function () {
  32170. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  32171. };
  32172. TiledGround.prototype.copy = function (id) {
  32173. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  32174. };
  32175. return TiledGround;
  32176. }(_Primitive));
  32177. Primitives.TiledGround = TiledGround;
  32178. var Plane = /** @class */ (function (_super) {
  32179. __extends(Plane, _super);
  32180. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  32181. if (mesh === void 0) { mesh = null; }
  32182. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32183. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32184. _this.size = size;
  32185. _this.side = side;
  32186. return _this;
  32187. }
  32188. Plane.prototype._regenerateVertexData = function () {
  32189. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  32190. };
  32191. Plane.prototype.copy = function (id) {
  32192. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  32193. };
  32194. Plane.prototype.serialize = function () {
  32195. var serializationObject = _super.prototype.serialize.call(this);
  32196. serializationObject.size = this.size;
  32197. return serializationObject;
  32198. };
  32199. Plane.Parse = function (parsedPlane, scene) {
  32200. if (scene.getGeometryByID(parsedPlane.id)) {
  32201. return null; // null since geometry could be something else than a ground...
  32202. }
  32203. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  32204. if (BABYLON.Tags) {
  32205. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  32206. }
  32207. scene.pushGeometry(plane, true);
  32208. return plane;
  32209. };
  32210. return Plane;
  32211. }(_Primitive));
  32212. Primitives.Plane = Plane;
  32213. var TorusKnot = /** @class */ (function (_super) {
  32214. __extends(TorusKnot, _super);
  32215. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  32216. if (mesh === void 0) { mesh = null; }
  32217. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32218. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32219. _this.radius = radius;
  32220. _this.tube = tube;
  32221. _this.radialSegments = radialSegments;
  32222. _this.tubularSegments = tubularSegments;
  32223. _this.p = p;
  32224. _this.q = q;
  32225. _this.side = side;
  32226. return _this;
  32227. }
  32228. TorusKnot.prototype._regenerateVertexData = function () {
  32229. 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 });
  32230. };
  32231. TorusKnot.prototype.copy = function (id) {
  32232. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  32233. };
  32234. TorusKnot.prototype.serialize = function () {
  32235. var serializationObject = _super.prototype.serialize.call(this);
  32236. serializationObject.radius = this.radius;
  32237. serializationObject.tube = this.tube;
  32238. serializationObject.radialSegments = this.radialSegments;
  32239. serializationObject.tubularSegments = this.tubularSegments;
  32240. serializationObject.p = this.p;
  32241. serializationObject.q = this.q;
  32242. return serializationObject;
  32243. };
  32244. ;
  32245. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  32246. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  32247. return null; // null since geometry could be something else than a ground...
  32248. }
  32249. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  32250. if (BABYLON.Tags) {
  32251. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  32252. }
  32253. scene.pushGeometry(torusKnot, true);
  32254. return torusKnot;
  32255. };
  32256. return TorusKnot;
  32257. }(_Primitive));
  32258. Primitives.TorusKnot = TorusKnot;
  32259. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  32260. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  32261. })(BABYLON || (BABYLON = {}));
  32262. //# sourceMappingURL=babylon.geometry.js.map
  32263. var BABYLON;
  32264. (function (BABYLON) {
  32265. var PostProcessManager = /** @class */ (function () {
  32266. function PostProcessManager(scene) {
  32267. this._vertexBuffers = {};
  32268. this._scene = scene;
  32269. }
  32270. PostProcessManager.prototype._prepareBuffers = function () {
  32271. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  32272. return;
  32273. }
  32274. // VBO
  32275. var vertices = [];
  32276. vertices.push(1, 1);
  32277. vertices.push(-1, 1);
  32278. vertices.push(-1, -1);
  32279. vertices.push(1, -1);
  32280. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  32281. this._buildIndexBuffer();
  32282. };
  32283. PostProcessManager.prototype._buildIndexBuffer = function () {
  32284. // Indices
  32285. var indices = [];
  32286. indices.push(0);
  32287. indices.push(1);
  32288. indices.push(2);
  32289. indices.push(0);
  32290. indices.push(2);
  32291. indices.push(3);
  32292. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  32293. };
  32294. PostProcessManager.prototype._rebuild = function () {
  32295. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32296. if (!vb) {
  32297. return;
  32298. }
  32299. vb._rebuild();
  32300. this._buildIndexBuffer();
  32301. };
  32302. // Methods
  32303. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  32304. if (sourceTexture === void 0) { sourceTexture = null; }
  32305. if (postProcesses === void 0) { postProcesses = null; }
  32306. var camera = this._scene.activeCamera;
  32307. if (!camera) {
  32308. return false;
  32309. }
  32310. var postProcesses = postProcesses || camera._postProcesses;
  32311. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32312. return false;
  32313. }
  32314. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  32315. return true;
  32316. };
  32317. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  32318. if (targetTexture === void 0) { targetTexture = null; }
  32319. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  32320. var engine = this._scene.getEngine();
  32321. for (var index = 0; index < postProcesses.length; index++) {
  32322. if (index < postProcesses.length - 1) {
  32323. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  32324. }
  32325. else {
  32326. if (targetTexture) {
  32327. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  32328. }
  32329. else {
  32330. engine.restoreDefaultFramebuffer();
  32331. }
  32332. }
  32333. var pp = postProcesses[index];
  32334. var effect = pp.apply();
  32335. if (effect) {
  32336. pp.onBeforeRenderObservable.notifyObservers(effect);
  32337. // VBOs
  32338. this._prepareBuffers();
  32339. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32340. // Draw order
  32341. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  32342. pp.onAfterRenderObservable.notifyObservers(effect);
  32343. }
  32344. }
  32345. // Restore depth buffer
  32346. engine.setDepthBuffer(true);
  32347. engine.setDepthWrite(true);
  32348. };
  32349. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  32350. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  32351. var camera = this._scene.activeCamera;
  32352. if (!camera) {
  32353. return;
  32354. }
  32355. postProcesses = postProcesses || camera._postProcesses;
  32356. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32357. return;
  32358. }
  32359. var engine = this._scene.getEngine();
  32360. for (var index = 0, len = postProcesses.length; index < len; index++) {
  32361. if (index < len - 1) {
  32362. postProcesses[index + 1].activate(camera, targetTexture);
  32363. }
  32364. else {
  32365. if (targetTexture) {
  32366. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  32367. }
  32368. else {
  32369. engine.restoreDefaultFramebuffer();
  32370. }
  32371. }
  32372. if (doNotPresent) {
  32373. break;
  32374. }
  32375. var pp = postProcesses[index];
  32376. var effect = pp.apply();
  32377. if (effect) {
  32378. pp.onBeforeRenderObservable.notifyObservers(effect);
  32379. // VBOs
  32380. this._prepareBuffers();
  32381. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32382. // Draw order
  32383. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  32384. pp.onAfterRenderObservable.notifyObservers(effect);
  32385. }
  32386. }
  32387. // Restore states
  32388. engine.setDepthBuffer(true);
  32389. engine.setDepthWrite(true);
  32390. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32391. };
  32392. PostProcessManager.prototype.dispose = function () {
  32393. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32394. if (buffer) {
  32395. buffer.dispose();
  32396. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  32397. }
  32398. if (this._indexBuffer) {
  32399. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32400. this._indexBuffer = null;
  32401. }
  32402. };
  32403. return PostProcessManager;
  32404. }());
  32405. BABYLON.PostProcessManager = PostProcessManager;
  32406. })(BABYLON || (BABYLON = {}));
  32407. //# sourceMappingURL=babylon.postProcessManager.js.map
  32408. var BABYLON;
  32409. (function (BABYLON) {
  32410. /**
  32411. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  32412. */
  32413. var PerformanceMonitor = /** @class */ (function () {
  32414. /**
  32415. * constructor
  32416. * @param frameSampleSize The number of samples required to saturate the sliding window
  32417. */
  32418. function PerformanceMonitor(frameSampleSize) {
  32419. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  32420. this._enabled = true;
  32421. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  32422. }
  32423. /**
  32424. * Samples current frame
  32425. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  32426. */
  32427. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  32428. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  32429. if (!this._enabled)
  32430. return;
  32431. if (this._lastFrameTimeMs != null) {
  32432. var dt = timeMs - this._lastFrameTimeMs;
  32433. this._rollingFrameTime.add(dt);
  32434. }
  32435. this._lastFrameTimeMs = timeMs;
  32436. };
  32437. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  32438. /**
  32439. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  32440. * @return Average frame time in milliseconds
  32441. */
  32442. get: function () {
  32443. return this._rollingFrameTime.average;
  32444. },
  32445. enumerable: true,
  32446. configurable: true
  32447. });
  32448. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  32449. /**
  32450. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  32451. * @return Frame time variance in milliseconds squared
  32452. */
  32453. get: function () {
  32454. return this._rollingFrameTime.variance;
  32455. },
  32456. enumerable: true,
  32457. configurable: true
  32458. });
  32459. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  32460. /**
  32461. * Returns the frame time of the most recent frame
  32462. * @return Frame time in milliseconds
  32463. */
  32464. get: function () {
  32465. return this._rollingFrameTime.history(0);
  32466. },
  32467. enumerable: true,
  32468. configurable: true
  32469. });
  32470. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  32471. /**
  32472. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  32473. * @return Framerate in frames per second
  32474. */
  32475. get: function () {
  32476. return 1000.0 / this._rollingFrameTime.average;
  32477. },
  32478. enumerable: true,
  32479. configurable: true
  32480. });
  32481. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  32482. /**
  32483. * Returns the average framerate in frames per second using the most recent frame time
  32484. * @return Framerate in frames per second
  32485. */
  32486. get: function () {
  32487. var history = this._rollingFrameTime.history(0);
  32488. if (history === 0) {
  32489. return 0;
  32490. }
  32491. return 1000.0 / history;
  32492. },
  32493. enumerable: true,
  32494. configurable: true
  32495. });
  32496. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  32497. /**
  32498. * Returns true if enough samples have been taken to completely fill the sliding window
  32499. * @return true if saturated
  32500. */
  32501. get: function () {
  32502. return this._rollingFrameTime.isSaturated();
  32503. },
  32504. enumerable: true,
  32505. configurable: true
  32506. });
  32507. /**
  32508. * Enables contributions to the sliding window sample set
  32509. */
  32510. PerformanceMonitor.prototype.enable = function () {
  32511. this._enabled = true;
  32512. };
  32513. /**
  32514. * Disables contributions to the sliding window sample set
  32515. * Samples will not be interpolated over the disabled period
  32516. */
  32517. PerformanceMonitor.prototype.disable = function () {
  32518. this._enabled = false;
  32519. //clear last sample to avoid interpolating over the disabled period when next enabled
  32520. this._lastFrameTimeMs = null;
  32521. };
  32522. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  32523. /**
  32524. * Returns true if sampling is enabled
  32525. * @return true if enabled
  32526. */
  32527. get: function () {
  32528. return this._enabled;
  32529. },
  32530. enumerable: true,
  32531. configurable: true
  32532. });
  32533. /**
  32534. * Resets performance monitor
  32535. */
  32536. PerformanceMonitor.prototype.reset = function () {
  32537. //clear last sample to avoid interpolating over the disabled period when next enabled
  32538. this._lastFrameTimeMs = null;
  32539. //wipe record
  32540. this._rollingFrameTime.reset();
  32541. };
  32542. return PerformanceMonitor;
  32543. }());
  32544. BABYLON.PerformanceMonitor = PerformanceMonitor;
  32545. /**
  32546. * RollingAverage
  32547. *
  32548. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  32549. */
  32550. var RollingAverage = /** @class */ (function () {
  32551. /**
  32552. * constructor
  32553. * @param length The number of samples required to saturate the sliding window
  32554. */
  32555. function RollingAverage(length) {
  32556. this._samples = new Array(length);
  32557. this.reset();
  32558. }
  32559. /**
  32560. * Adds a sample to the sample set
  32561. * @param v The sample value
  32562. */
  32563. RollingAverage.prototype.add = function (v) {
  32564. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  32565. var delta;
  32566. //we need to check if we've already wrapped round
  32567. if (this.isSaturated()) {
  32568. //remove bottom of stack from mean
  32569. var bottomValue = this._samples[this._pos];
  32570. delta = bottomValue - this.average;
  32571. this.average -= delta / (this._sampleCount - 1);
  32572. this._m2 -= delta * (bottomValue - this.average);
  32573. }
  32574. else {
  32575. this._sampleCount++;
  32576. }
  32577. //add new value to mean
  32578. delta = v - this.average;
  32579. this.average += delta / (this._sampleCount);
  32580. this._m2 += delta * (v - this.average);
  32581. //set the new variance
  32582. this.variance = this._m2 / (this._sampleCount - 1);
  32583. this._samples[this._pos] = v;
  32584. this._pos++;
  32585. this._pos %= this._samples.length; //positive wrap around
  32586. };
  32587. /**
  32588. * Returns previously added values or null if outside of history or outside the sliding window domain
  32589. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  32590. * @return Value previously recorded with add() or null if outside of range
  32591. */
  32592. RollingAverage.prototype.history = function (i) {
  32593. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  32594. return 0;
  32595. }
  32596. var i0 = this._wrapPosition(this._pos - 1.0);
  32597. return this._samples[this._wrapPosition(i0 - i)];
  32598. };
  32599. /**
  32600. * Returns true if enough samples have been taken to completely fill the sliding window
  32601. * @return true if sample-set saturated
  32602. */
  32603. RollingAverage.prototype.isSaturated = function () {
  32604. return this._sampleCount >= this._samples.length;
  32605. };
  32606. /**
  32607. * Resets the rolling average (equivalent to 0 samples taken so far)
  32608. */
  32609. RollingAverage.prototype.reset = function () {
  32610. this.average = 0;
  32611. this.variance = 0;
  32612. this._sampleCount = 0;
  32613. this._pos = 0;
  32614. this._m2 = 0;
  32615. };
  32616. /**
  32617. * Wraps a value around the sample range boundaries
  32618. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  32619. * @return Wrapped position in sample range
  32620. */
  32621. RollingAverage.prototype._wrapPosition = function (i) {
  32622. var max = this._samples.length;
  32623. return ((i % max) + max) % max;
  32624. };
  32625. return RollingAverage;
  32626. }());
  32627. BABYLON.RollingAverage = RollingAverage;
  32628. })(BABYLON || (BABYLON = {}));
  32629. //# sourceMappingURL=babylon.performanceMonitor.js.map
  32630. var BABYLON;
  32631. (function (BABYLON) {
  32632. /**
  32633. * This groups together the common properties used for image processing either in direct forward pass
  32634. * or through post processing effect depending on the use of the image processing pipeline in your scene
  32635. * or not.
  32636. */
  32637. var ImageProcessingConfiguration = /** @class */ (function () {
  32638. function ImageProcessingConfiguration() {
  32639. /**
  32640. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  32641. */
  32642. this.colorCurves = new BABYLON.ColorCurves();
  32643. this._colorCurvesEnabled = false;
  32644. this._colorGradingEnabled = false;
  32645. this._colorGradingWithGreenDepth = true;
  32646. this._colorGradingBGR = true;
  32647. this._exposure = 1.0;
  32648. this._toneMappingEnabled = false;
  32649. this._contrast = 1.0;
  32650. /**
  32651. * Vignette stretch size.
  32652. */
  32653. this.vignetteStretch = 0;
  32654. /**
  32655. * Vignette centre X Offset.
  32656. */
  32657. this.vignetteCentreX = 0;
  32658. /**
  32659. * Vignette centre Y Offset.
  32660. */
  32661. this.vignetteCentreY = 0;
  32662. /**
  32663. * Vignette weight or intensity of the vignette effect.
  32664. */
  32665. this.vignetteWeight = 1.5;
  32666. /**
  32667. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  32668. * if vignetteEnabled is set to true.
  32669. */
  32670. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  32671. /**
  32672. * Camera field of view used by the Vignette effect.
  32673. */
  32674. this.vignetteCameraFov = 0.5;
  32675. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  32676. this._vignetteEnabled = false;
  32677. this._applyByPostProcess = false;
  32678. this._isEnabled = true;
  32679. /**
  32680. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  32681. * @type {BABYLON.Observable}
  32682. */
  32683. this.onUpdateParameters = new BABYLON.Observable();
  32684. }
  32685. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  32686. /**
  32687. * Gets wether the color curves effect is enabled.
  32688. */
  32689. get: function () {
  32690. return this._colorCurvesEnabled;
  32691. },
  32692. /**
  32693. * Sets wether the color curves effect is enabled.
  32694. */
  32695. set: function (value) {
  32696. if (this._colorCurvesEnabled === value) {
  32697. return;
  32698. }
  32699. this._colorCurvesEnabled = value;
  32700. this._updateParameters();
  32701. },
  32702. enumerable: true,
  32703. configurable: true
  32704. });
  32705. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  32706. /**
  32707. * Gets wether the color grading effect is enabled.
  32708. */
  32709. get: function () {
  32710. return this._colorGradingEnabled;
  32711. },
  32712. /**
  32713. * Sets wether the color grading effect is enabled.
  32714. */
  32715. set: function (value) {
  32716. if (this._colorGradingEnabled === value) {
  32717. return;
  32718. }
  32719. this._colorGradingEnabled = value;
  32720. this._updateParameters();
  32721. },
  32722. enumerable: true,
  32723. configurable: true
  32724. });
  32725. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  32726. /**
  32727. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  32728. */
  32729. get: function () {
  32730. return this._colorGradingWithGreenDepth;
  32731. },
  32732. /**
  32733. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  32734. */
  32735. set: function (value) {
  32736. if (this._colorGradingWithGreenDepth === value) {
  32737. return;
  32738. }
  32739. this._colorGradingWithGreenDepth = value;
  32740. this._updateParameters();
  32741. },
  32742. enumerable: true,
  32743. configurable: true
  32744. });
  32745. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  32746. /**
  32747. * Gets wether the color grading texture contains BGR values.
  32748. */
  32749. get: function () {
  32750. return this._colorGradingBGR;
  32751. },
  32752. /**
  32753. * Sets wether the color grading texture contains BGR values.
  32754. */
  32755. set: function (value) {
  32756. if (this._colorGradingBGR === value) {
  32757. return;
  32758. }
  32759. this._colorGradingBGR = value;
  32760. this._updateParameters();
  32761. },
  32762. enumerable: true,
  32763. configurable: true
  32764. });
  32765. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  32766. /**
  32767. * Gets the Exposure used in the effect.
  32768. */
  32769. get: function () {
  32770. return this._exposure;
  32771. },
  32772. /**
  32773. * Sets the Exposure used in the effect.
  32774. */
  32775. set: function (value) {
  32776. if (this._exposure === value) {
  32777. return;
  32778. }
  32779. this._exposure = value;
  32780. this._updateParameters();
  32781. },
  32782. enumerable: true,
  32783. configurable: true
  32784. });
  32785. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  32786. /**
  32787. * Gets wether the tone mapping effect is enabled.
  32788. */
  32789. get: function () {
  32790. return this._toneMappingEnabled;
  32791. },
  32792. /**
  32793. * Sets wether the tone mapping effect is enabled.
  32794. */
  32795. set: function (value) {
  32796. if (this._toneMappingEnabled === value) {
  32797. return;
  32798. }
  32799. this._toneMappingEnabled = value;
  32800. this._updateParameters();
  32801. },
  32802. enumerable: true,
  32803. configurable: true
  32804. });
  32805. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  32806. /**
  32807. * Gets the contrast used in the effect.
  32808. */
  32809. get: function () {
  32810. return this._contrast;
  32811. },
  32812. /**
  32813. * Sets the contrast used in the effect.
  32814. */
  32815. set: function (value) {
  32816. if (this._contrast === value) {
  32817. return;
  32818. }
  32819. this._contrast = value;
  32820. this._updateParameters();
  32821. },
  32822. enumerable: true,
  32823. configurable: true
  32824. });
  32825. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  32826. /**
  32827. * Gets the vignette blend mode allowing different kind of effect.
  32828. */
  32829. get: function () {
  32830. return this._vignetteBlendMode;
  32831. },
  32832. /**
  32833. * Sets the vignette blend mode allowing different kind of effect.
  32834. */
  32835. set: function (value) {
  32836. if (this._vignetteBlendMode === value) {
  32837. return;
  32838. }
  32839. this._vignetteBlendMode = value;
  32840. this._updateParameters();
  32841. },
  32842. enumerable: true,
  32843. configurable: true
  32844. });
  32845. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  32846. /**
  32847. * Gets wether the vignette effect is enabled.
  32848. */
  32849. get: function () {
  32850. return this._vignetteEnabled;
  32851. },
  32852. /**
  32853. * Sets wether the vignette effect is enabled.
  32854. */
  32855. set: function (value) {
  32856. if (this._vignetteEnabled === value) {
  32857. return;
  32858. }
  32859. this._vignetteEnabled = value;
  32860. this._updateParameters();
  32861. },
  32862. enumerable: true,
  32863. configurable: true
  32864. });
  32865. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  32866. /**
  32867. * Gets wether the image processing is applied through a post process or not.
  32868. */
  32869. get: function () {
  32870. return this._applyByPostProcess;
  32871. },
  32872. /**
  32873. * Sets wether the image processing is applied through a post process or not.
  32874. */
  32875. set: function (value) {
  32876. if (this._applyByPostProcess === value) {
  32877. return;
  32878. }
  32879. this._applyByPostProcess = value;
  32880. this._updateParameters();
  32881. },
  32882. enumerable: true,
  32883. configurable: true
  32884. });
  32885. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  32886. /**
  32887. * Gets wether the image processing is enabled or not.
  32888. */
  32889. get: function () {
  32890. return this._isEnabled;
  32891. },
  32892. /**
  32893. * Sets wether the image processing is enabled or not.
  32894. */
  32895. set: function (value) {
  32896. if (this._isEnabled === value) {
  32897. return;
  32898. }
  32899. this._isEnabled = value;
  32900. this._updateParameters();
  32901. },
  32902. enumerable: true,
  32903. configurable: true
  32904. });
  32905. /**
  32906. * Method called each time the image processing information changes requires to recompile the effect.
  32907. */
  32908. ImageProcessingConfiguration.prototype._updateParameters = function () {
  32909. this.onUpdateParameters.notifyObservers(this);
  32910. };
  32911. ImageProcessingConfiguration.prototype.getClassName = function () {
  32912. return "ImageProcessingConfiguration";
  32913. };
  32914. /**
  32915. * Prepare the list of uniforms associated with the Image Processing effects.
  32916. * @param uniformsList The list of uniforms used in the effect
  32917. * @param defines the list of defines currently in use
  32918. */
  32919. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  32920. if (defines.EXPOSURE) {
  32921. uniforms.push("exposureLinear");
  32922. }
  32923. if (defines.CONTRAST) {
  32924. uniforms.push("contrast");
  32925. }
  32926. if (defines.COLORGRADING) {
  32927. uniforms.push("colorTransformSettings");
  32928. }
  32929. if (defines.VIGNETTE) {
  32930. uniforms.push("vInverseScreenSize");
  32931. uniforms.push("vignetteSettings1");
  32932. uniforms.push("vignetteSettings2");
  32933. }
  32934. if (defines.COLORCURVES) {
  32935. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  32936. }
  32937. };
  32938. /**
  32939. * Prepare the list of samplers associated with the Image Processing effects.
  32940. * @param uniformsList The list of uniforms used in the effect
  32941. * @param defines the list of defines currently in use
  32942. */
  32943. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  32944. if (defines.COLORGRADING) {
  32945. samplersList.push("txColorTransform");
  32946. }
  32947. };
  32948. /**
  32949. * Prepare the list of defines associated to the shader.
  32950. * @param defines the list of defines to complete
  32951. */
  32952. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  32953. if (forPostProcess === void 0) { forPostProcess = false; }
  32954. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  32955. defines.VIGNETTE = false;
  32956. defines.TONEMAPPING = false;
  32957. defines.CONTRAST = false;
  32958. defines.EXPOSURE = false;
  32959. defines.COLORCURVES = false;
  32960. defines.COLORGRADING = false;
  32961. defines.COLORGRADING3D = false;
  32962. defines.IMAGEPROCESSING = false;
  32963. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  32964. return;
  32965. }
  32966. defines.VIGNETTE = this.vignetteEnabled;
  32967. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  32968. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  32969. defines.TONEMAPPING = this.toneMappingEnabled;
  32970. defines.CONTRAST = (this.contrast !== 1.0);
  32971. defines.EXPOSURE = (this.exposure !== 1.0);
  32972. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  32973. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  32974. if (defines.COLORGRADING) {
  32975. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  32976. }
  32977. else {
  32978. defines.COLORGRADING3D = false;
  32979. }
  32980. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  32981. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  32982. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  32983. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  32984. };
  32985. /**
  32986. * Returns true if all the image processing information are ready.
  32987. */
  32988. ImageProcessingConfiguration.prototype.isReady = function () {
  32989. // Color Grading texure can not be none blocking.
  32990. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  32991. };
  32992. /**
  32993. * Binds the image processing to the shader.
  32994. * @param effect The effect to bind to
  32995. */
  32996. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  32997. if (aspectRatio === void 0) { aspectRatio = 1; }
  32998. // Color Curves
  32999. if (this._colorCurvesEnabled && this.colorCurves) {
  33000. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  33001. }
  33002. // Vignette
  33003. if (this._vignetteEnabled) {
  33004. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  33005. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  33006. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  33007. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  33008. var vignetteScaleX = vignetteScaleY * aspectRatio;
  33009. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  33010. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  33011. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  33012. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  33013. var vignettePower = -2.0 * this.vignetteWeight;
  33014. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  33015. }
  33016. // Exposure
  33017. effect.setFloat("exposureLinear", this.exposure);
  33018. // Contrast
  33019. effect.setFloat("contrast", this.contrast);
  33020. // Color transform settings
  33021. if (this.colorGradingTexture) {
  33022. effect.setTexture("txColorTransform", this.colorGradingTexture);
  33023. var textureSize = this.colorGradingTexture.getSize().height;
  33024. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  33025. 0.5 / textureSize, // textureOffset
  33026. textureSize, // textureSize
  33027. this.colorGradingTexture.level // weight
  33028. );
  33029. }
  33030. };
  33031. /**
  33032. * Clones the current image processing instance.
  33033. * @return The cloned image processing
  33034. */
  33035. ImageProcessingConfiguration.prototype.clone = function () {
  33036. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  33037. };
  33038. /**
  33039. * Serializes the current image processing instance to a json representation.
  33040. * @return a JSON representation
  33041. */
  33042. ImageProcessingConfiguration.prototype.serialize = function () {
  33043. return BABYLON.SerializationHelper.Serialize(this);
  33044. };
  33045. /**
  33046. * Parses the image processing from a json representation.
  33047. * @param source the JSON source to parse
  33048. * @return The parsed image processing
  33049. */
  33050. ImageProcessingConfiguration.Parse = function (source) {
  33051. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  33052. };
  33053. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  33054. /**
  33055. * Used to apply the vignette as a mix with the pixel color.
  33056. */
  33057. get: function () {
  33058. return this._VIGNETTEMODE_MULTIPLY;
  33059. },
  33060. enumerable: true,
  33061. configurable: true
  33062. });
  33063. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  33064. /**
  33065. * Used to apply the vignette as a replacement of the pixel color.
  33066. */
  33067. get: function () {
  33068. return this._VIGNETTEMODE_OPAQUE;
  33069. },
  33070. enumerable: true,
  33071. configurable: true
  33072. });
  33073. // Static constants associated to the image processing.
  33074. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  33075. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  33076. __decorate([
  33077. BABYLON.serializeAsColorCurves()
  33078. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  33079. __decorate([
  33080. BABYLON.serialize()
  33081. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  33082. __decorate([
  33083. BABYLON.serializeAsTexture()
  33084. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  33085. __decorate([
  33086. BABYLON.serialize()
  33087. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  33088. __decorate([
  33089. BABYLON.serialize()
  33090. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  33091. __decorate([
  33092. BABYLON.serialize()
  33093. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  33094. __decorate([
  33095. BABYLON.serialize()
  33096. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  33097. __decorate([
  33098. BABYLON.serialize()
  33099. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  33100. __decorate([
  33101. BABYLON.serialize()
  33102. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  33103. __decorate([
  33104. BABYLON.serialize()
  33105. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  33106. __decorate([
  33107. BABYLON.serialize()
  33108. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  33109. __decorate([
  33110. BABYLON.serialize()
  33111. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  33112. __decorate([
  33113. BABYLON.serialize()
  33114. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  33115. __decorate([
  33116. BABYLON.serializeAsColor4()
  33117. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  33118. __decorate([
  33119. BABYLON.serialize()
  33120. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  33121. __decorate([
  33122. BABYLON.serialize()
  33123. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  33124. __decorate([
  33125. BABYLON.serialize()
  33126. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  33127. __decorate([
  33128. BABYLON.serialize()
  33129. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  33130. __decorate([
  33131. BABYLON.serialize()
  33132. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  33133. return ImageProcessingConfiguration;
  33134. }());
  33135. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  33136. })(BABYLON || (BABYLON = {}));
  33137. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  33138. var BABYLON;
  33139. (function (BABYLON) {
  33140. /**
  33141. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  33142. * It can help converting any input color in a desired output one. This can then be used to create effects
  33143. * from sepia, black and white to sixties or futuristic rendering...
  33144. *
  33145. * The only supported format is currently 3dl.
  33146. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  33147. */
  33148. var ColorGradingTexture = /** @class */ (function (_super) {
  33149. __extends(ColorGradingTexture, _super);
  33150. /**
  33151. * Instantiates a ColorGradingTexture from the following parameters.
  33152. *
  33153. * @param url The location of the color gradind data (currently only supporting 3dl)
  33154. * @param scene The scene the texture will be used in
  33155. */
  33156. function ColorGradingTexture(url, scene) {
  33157. var _this = _super.call(this, scene) || this;
  33158. if (!url) {
  33159. return _this;
  33160. }
  33161. _this._engine = scene.getEngine();
  33162. _this._textureMatrix = BABYLON.Matrix.Identity();
  33163. _this.name = url;
  33164. _this.url = url;
  33165. _this.hasAlpha = false;
  33166. _this.isCube = false;
  33167. _this.is3D = _this._engine.webGLVersion > 1;
  33168. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33169. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33170. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33171. _this.anisotropicFilteringLevel = 1;
  33172. _this._texture = _this._getFromCache(url, true);
  33173. if (!_this._texture) {
  33174. if (!scene.useDelayedTextureLoading) {
  33175. _this.loadTexture();
  33176. }
  33177. else {
  33178. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33179. }
  33180. }
  33181. return _this;
  33182. }
  33183. /**
  33184. * Returns the texture matrix used in most of the material.
  33185. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  33186. */
  33187. ColorGradingTexture.prototype.getTextureMatrix = function () {
  33188. return this._textureMatrix;
  33189. };
  33190. /**
  33191. * Occurs when the file being loaded is a .3dl LUT file.
  33192. */
  33193. ColorGradingTexture.prototype.load3dlTexture = function () {
  33194. var engine = this._engine;
  33195. var texture;
  33196. if (engine.webGLVersion === 1) {
  33197. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33198. }
  33199. else {
  33200. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33201. }
  33202. this._texture = texture;
  33203. var callback = function (text) {
  33204. if (typeof text !== "string") {
  33205. return;
  33206. }
  33207. var data = null;
  33208. var tempData = null;
  33209. var line;
  33210. var lines = text.split('\n');
  33211. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  33212. var maxColor = 0;
  33213. for (var i = 0; i < lines.length; i++) {
  33214. line = lines[i];
  33215. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  33216. continue;
  33217. if (line.indexOf('#') === 0)
  33218. continue;
  33219. var words = line.split(" ");
  33220. if (size === 0) {
  33221. // Number of space + one
  33222. size = words.length;
  33223. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  33224. tempData = new Float32Array(size * size * size * 4);
  33225. continue;
  33226. }
  33227. if (size != 0) {
  33228. var r = Math.max(parseInt(words[0]), 0);
  33229. var g = Math.max(parseInt(words[1]), 0);
  33230. var b = Math.max(parseInt(words[2]), 0);
  33231. maxColor = Math.max(r, maxColor);
  33232. maxColor = Math.max(g, maxColor);
  33233. maxColor = Math.max(b, maxColor);
  33234. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  33235. if (tempData) {
  33236. tempData[pixelStorageIndex + 0] = r;
  33237. tempData[pixelStorageIndex + 1] = g;
  33238. tempData[pixelStorageIndex + 2] = b;
  33239. }
  33240. pixelIndexSlice++;
  33241. if (pixelIndexSlice % size == 0) {
  33242. pixelIndexH++;
  33243. pixelIndexSlice = 0;
  33244. if (pixelIndexH % size == 0) {
  33245. pixelIndexW++;
  33246. pixelIndexH = 0;
  33247. }
  33248. }
  33249. }
  33250. }
  33251. if (tempData && data) {
  33252. for (var i = 0; i < tempData.length; i++) {
  33253. if (i > 0 && (i + 1) % 4 === 0) {
  33254. data[i] = 255;
  33255. }
  33256. else {
  33257. var value = tempData[i];
  33258. data[i] = (value / maxColor * 255);
  33259. }
  33260. }
  33261. }
  33262. if (texture.is3D) {
  33263. texture.updateSize(size, size, size);
  33264. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33265. }
  33266. else {
  33267. texture.updateSize(size * size, size);
  33268. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33269. }
  33270. };
  33271. BABYLON.Tools.LoadFile(this.url, callback);
  33272. return this._texture;
  33273. };
  33274. /**
  33275. * Starts the loading process of the texture.
  33276. */
  33277. ColorGradingTexture.prototype.loadTexture = function () {
  33278. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  33279. this.load3dlTexture();
  33280. }
  33281. };
  33282. /**
  33283. * Clones the color gradind texture.
  33284. */
  33285. ColorGradingTexture.prototype.clone = function () {
  33286. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  33287. // Base texture
  33288. newTexture.level = this.level;
  33289. return newTexture;
  33290. };
  33291. /**
  33292. * Called during delayed load for textures.
  33293. */
  33294. ColorGradingTexture.prototype.delayLoad = function () {
  33295. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33296. return;
  33297. }
  33298. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33299. this._texture = this._getFromCache(this.url, true);
  33300. if (!this._texture) {
  33301. this.loadTexture();
  33302. }
  33303. };
  33304. /**
  33305. * Parses a color grading texture serialized by Babylon.
  33306. * @param parsedTexture The texture information being parsedTexture
  33307. * @param scene The scene to load the texture in
  33308. * @param rootUrl The root url of the data assets to load
  33309. * @return A color gradind texture
  33310. */
  33311. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  33312. var texture = null;
  33313. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  33314. texture = new ColorGradingTexture(parsedTexture.name, scene);
  33315. texture.name = parsedTexture.name;
  33316. texture.level = parsedTexture.level;
  33317. }
  33318. return texture;
  33319. };
  33320. /**
  33321. * Serializes the LUT texture to json format.
  33322. */
  33323. ColorGradingTexture.prototype.serialize = function () {
  33324. if (!this.name) {
  33325. return null;
  33326. }
  33327. var serializationObject = {};
  33328. serializationObject.name = this.name;
  33329. serializationObject.level = this.level;
  33330. serializationObject.customType = "BABYLON.ColorGradingTexture";
  33331. return serializationObject;
  33332. };
  33333. /**
  33334. * Empty line regex stored for GC.
  33335. */
  33336. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  33337. return ColorGradingTexture;
  33338. }(BABYLON.BaseTexture));
  33339. BABYLON.ColorGradingTexture = ColorGradingTexture;
  33340. })(BABYLON || (BABYLON = {}));
  33341. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  33342. var BABYLON;
  33343. (function (BABYLON) {
  33344. /**
  33345. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33346. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33347. * 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;
  33348. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33349. */
  33350. var ColorCurves = /** @class */ (function () {
  33351. function ColorCurves() {
  33352. this._dirty = true;
  33353. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  33354. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  33355. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  33356. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  33357. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  33358. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  33359. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  33360. this._globalHue = 30;
  33361. this._globalDensity = 0;
  33362. this._globalSaturation = 0;
  33363. this._globalExposure = 0;
  33364. this._highlightsHue = 30;
  33365. this._highlightsDensity = 0;
  33366. this._highlightsSaturation = 0;
  33367. this._highlightsExposure = 0;
  33368. this._midtonesHue = 30;
  33369. this._midtonesDensity = 0;
  33370. this._midtonesSaturation = 0;
  33371. this._midtonesExposure = 0;
  33372. this._shadowsHue = 30;
  33373. this._shadowsDensity = 0;
  33374. this._shadowsSaturation = 0;
  33375. this._shadowsExposure = 0;
  33376. }
  33377. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  33378. /**
  33379. * Gets the global Hue value.
  33380. * 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).
  33381. */
  33382. get: function () {
  33383. return this._globalHue;
  33384. },
  33385. /**
  33386. * Sets the global Hue value.
  33387. * 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).
  33388. */
  33389. set: function (value) {
  33390. this._globalHue = value;
  33391. this._dirty = true;
  33392. },
  33393. enumerable: true,
  33394. configurable: true
  33395. });
  33396. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  33397. /**
  33398. * Gets the global Density value.
  33399. * 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.
  33400. * Values less than zero provide a filter of opposite hue.
  33401. */
  33402. get: function () {
  33403. return this._globalDensity;
  33404. },
  33405. /**
  33406. * Sets the global Density value.
  33407. * 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.
  33408. * Values less than zero provide a filter of opposite hue.
  33409. */
  33410. set: function (value) {
  33411. this._globalDensity = value;
  33412. this._dirty = true;
  33413. },
  33414. enumerable: true,
  33415. configurable: true
  33416. });
  33417. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  33418. /**
  33419. * Gets the global Saturation value.
  33420. * 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.
  33421. */
  33422. get: function () {
  33423. return this._globalSaturation;
  33424. },
  33425. /**
  33426. * Sets the global Saturation value.
  33427. * 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.
  33428. */
  33429. set: function (value) {
  33430. this._globalSaturation = value;
  33431. this._dirty = true;
  33432. },
  33433. enumerable: true,
  33434. configurable: true
  33435. });
  33436. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  33437. /**
  33438. * Gets the highlights Hue value.
  33439. * 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).
  33440. */
  33441. get: function () {
  33442. return this._highlightsHue;
  33443. },
  33444. /**
  33445. * Sets the highlights Hue value.
  33446. * 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).
  33447. */
  33448. set: function (value) {
  33449. this._highlightsHue = value;
  33450. this._dirty = true;
  33451. },
  33452. enumerable: true,
  33453. configurable: true
  33454. });
  33455. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  33456. /**
  33457. * Gets the highlights Density value.
  33458. * 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.
  33459. * Values less than zero provide a filter of opposite hue.
  33460. */
  33461. get: function () {
  33462. return this._highlightsDensity;
  33463. },
  33464. /**
  33465. * Sets the highlights Density value.
  33466. * 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.
  33467. * Values less than zero provide a filter of opposite hue.
  33468. */
  33469. set: function (value) {
  33470. this._highlightsDensity = value;
  33471. this._dirty = true;
  33472. },
  33473. enumerable: true,
  33474. configurable: true
  33475. });
  33476. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  33477. /**
  33478. * Gets the highlights Saturation value.
  33479. * 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.
  33480. */
  33481. get: function () {
  33482. return this._highlightsSaturation;
  33483. },
  33484. /**
  33485. * Sets the highlights Saturation value.
  33486. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  33487. */
  33488. set: function (value) {
  33489. this._highlightsSaturation = value;
  33490. this._dirty = true;
  33491. },
  33492. enumerable: true,
  33493. configurable: true
  33494. });
  33495. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  33496. /**
  33497. * Gets the highlights Exposure value.
  33498. * 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.
  33499. */
  33500. get: function () {
  33501. return this._highlightsExposure;
  33502. },
  33503. /**
  33504. * Sets the highlights Exposure value.
  33505. * 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.
  33506. */
  33507. set: function (value) {
  33508. this._highlightsExposure = value;
  33509. this._dirty = true;
  33510. },
  33511. enumerable: true,
  33512. configurable: true
  33513. });
  33514. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  33515. /**
  33516. * Gets the midtones Hue value.
  33517. * 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).
  33518. */
  33519. get: function () {
  33520. return this._midtonesHue;
  33521. },
  33522. /**
  33523. * Sets the midtones Hue value.
  33524. * 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).
  33525. */
  33526. set: function (value) {
  33527. this._midtonesHue = value;
  33528. this._dirty = true;
  33529. },
  33530. enumerable: true,
  33531. configurable: true
  33532. });
  33533. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  33534. /**
  33535. * Gets the midtones Density value.
  33536. * 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.
  33537. * Values less than zero provide a filter of opposite hue.
  33538. */
  33539. get: function () {
  33540. return this._midtonesDensity;
  33541. },
  33542. /**
  33543. * Sets the midtones Density value.
  33544. * 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.
  33545. * Values less than zero provide a filter of opposite hue.
  33546. */
  33547. set: function (value) {
  33548. this._midtonesDensity = value;
  33549. this._dirty = true;
  33550. },
  33551. enumerable: true,
  33552. configurable: true
  33553. });
  33554. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  33555. /**
  33556. * Gets the midtones Saturation value.
  33557. * 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.
  33558. */
  33559. get: function () {
  33560. return this._midtonesSaturation;
  33561. },
  33562. /**
  33563. * Sets the midtones Saturation value.
  33564. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  33565. */
  33566. set: function (value) {
  33567. this._midtonesSaturation = value;
  33568. this._dirty = true;
  33569. },
  33570. enumerable: true,
  33571. configurable: true
  33572. });
  33573. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  33574. /**
  33575. * Gets the midtones Exposure value.
  33576. * 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.
  33577. */
  33578. get: function () {
  33579. return this._midtonesExposure;
  33580. },
  33581. /**
  33582. * Sets the midtones Exposure value.
  33583. * 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.
  33584. */
  33585. set: function (value) {
  33586. this._midtonesExposure = value;
  33587. this._dirty = true;
  33588. },
  33589. enumerable: true,
  33590. configurable: true
  33591. });
  33592. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  33593. /**
  33594. * Gets the shadows Hue value.
  33595. * 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).
  33596. */
  33597. get: function () {
  33598. return this._shadowsHue;
  33599. },
  33600. /**
  33601. * Sets the shadows Hue value.
  33602. * 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).
  33603. */
  33604. set: function (value) {
  33605. this._shadowsHue = value;
  33606. this._dirty = true;
  33607. },
  33608. enumerable: true,
  33609. configurable: true
  33610. });
  33611. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  33612. /**
  33613. * Gets the shadows Density value.
  33614. * 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.
  33615. * Values less than zero provide a filter of opposite hue.
  33616. */
  33617. get: function () {
  33618. return this._shadowsDensity;
  33619. },
  33620. /**
  33621. * Sets the shadows Density value.
  33622. * 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.
  33623. * Values less than zero provide a filter of opposite hue.
  33624. */
  33625. set: function (value) {
  33626. this._shadowsDensity = value;
  33627. this._dirty = true;
  33628. },
  33629. enumerable: true,
  33630. configurable: true
  33631. });
  33632. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  33633. /**
  33634. * Gets the shadows Saturation value.
  33635. * 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.
  33636. */
  33637. get: function () {
  33638. return this._shadowsSaturation;
  33639. },
  33640. /**
  33641. * Sets the shadows Saturation value.
  33642. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  33643. */
  33644. set: function (value) {
  33645. this._shadowsSaturation = value;
  33646. this._dirty = true;
  33647. },
  33648. enumerable: true,
  33649. configurable: true
  33650. });
  33651. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  33652. /**
  33653. * Gets the shadows Exposure value.
  33654. * 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.
  33655. */
  33656. get: function () {
  33657. return this._shadowsExposure;
  33658. },
  33659. /**
  33660. * Sets the shadows Exposure value.
  33661. * 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.
  33662. */
  33663. set: function (value) {
  33664. this._shadowsExposure = value;
  33665. this._dirty = true;
  33666. },
  33667. enumerable: true,
  33668. configurable: true
  33669. });
  33670. ColorCurves.prototype.getClassName = function () {
  33671. return "ColorCurves";
  33672. };
  33673. /**
  33674. * Binds the color curves to the shader.
  33675. * @param colorCurves The color curve to bind
  33676. * @param effect The effect to bind to
  33677. */
  33678. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  33679. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  33680. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  33681. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  33682. if (colorCurves._dirty) {
  33683. colorCurves._dirty = false;
  33684. // Fill in global info.
  33685. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  33686. // Compute highlights info.
  33687. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  33688. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  33689. // Compute midtones info.
  33690. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  33691. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  33692. // Compute shadows info.
  33693. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  33694. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  33695. // Compute deltas (neutral is midtones).
  33696. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  33697. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  33698. }
  33699. if (effect) {
  33700. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  33701. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  33702. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  33703. }
  33704. };
  33705. /**
  33706. * Prepare the list of uniforms associated with the ColorCurves effects.
  33707. * @param uniformsList The list of uniforms used in the effect
  33708. */
  33709. ColorCurves.PrepareUniforms = function (uniformsList) {
  33710. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  33711. };
  33712. /**
  33713. * Returns color grading data based on a hue, density, saturation and exposure value.
  33714. * @param filterHue The hue of the color filter.
  33715. * @param filterDensity The density of the color filter.
  33716. * @param saturation The saturation.
  33717. * @param exposure The exposure.
  33718. * @param result The result data container.
  33719. */
  33720. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  33721. if (hue == null) {
  33722. return;
  33723. }
  33724. hue = ColorCurves.clamp(hue, 0, 360);
  33725. density = ColorCurves.clamp(density, -100, 100);
  33726. saturation = ColorCurves.clamp(saturation, -100, 100);
  33727. exposure = ColorCurves.clamp(exposure, -100, 100);
  33728. // Remap the slider/config filter density with non-linear mapping and also scale by half
  33729. // so that the maximum filter density is only 50% control. This provides fine control
  33730. // for small values and reasonable range.
  33731. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  33732. density *= 0.5;
  33733. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  33734. if (density < 0) {
  33735. density *= -1;
  33736. hue = (hue + 180) % 360;
  33737. }
  33738. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  33739. result.scaleToRef(2, result);
  33740. result.a = 1 + 0.01 * saturation;
  33741. };
  33742. /**
  33743. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  33744. * @param value The input slider value in range [-100,100].
  33745. * @returns Adjusted value.
  33746. */
  33747. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  33748. value /= 100;
  33749. var x = Math.abs(value);
  33750. x = Math.pow(x, 2);
  33751. if (value < 0) {
  33752. x *= -1;
  33753. }
  33754. x *= 100;
  33755. return x;
  33756. };
  33757. /**
  33758. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  33759. * @param hue The hue (H) input.
  33760. * @param saturation The saturation (S) input.
  33761. * @param brightness The brightness (B) input.
  33762. * @result An RGBA color represented as Vector4.
  33763. */
  33764. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  33765. var h = ColorCurves.clamp(hue, 0, 360);
  33766. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  33767. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  33768. if (s === 0) {
  33769. result.r = v;
  33770. result.g = v;
  33771. result.b = v;
  33772. }
  33773. else {
  33774. // sector 0 to 5
  33775. h /= 60;
  33776. var i = Math.floor(h);
  33777. // fractional part of h
  33778. var f = h - i;
  33779. var p = v * (1 - s);
  33780. var q = v * (1 - s * f);
  33781. var t = v * (1 - s * (1 - f));
  33782. switch (i) {
  33783. case 0:
  33784. result.r = v;
  33785. result.g = t;
  33786. result.b = p;
  33787. break;
  33788. case 1:
  33789. result.r = q;
  33790. result.g = v;
  33791. result.b = p;
  33792. break;
  33793. case 2:
  33794. result.r = p;
  33795. result.g = v;
  33796. result.b = t;
  33797. break;
  33798. case 3:
  33799. result.r = p;
  33800. result.g = q;
  33801. result.b = v;
  33802. break;
  33803. case 4:
  33804. result.r = t;
  33805. result.g = p;
  33806. result.b = v;
  33807. break;
  33808. default:// case 5:
  33809. result.r = v;
  33810. result.g = p;
  33811. result.b = q;
  33812. break;
  33813. }
  33814. }
  33815. result.a = 1;
  33816. };
  33817. /**
  33818. * Returns a value clamped between min and max
  33819. * @param value The value to clamp
  33820. * @param min The minimum of value
  33821. * @param max The maximum of value
  33822. * @returns The clamped value.
  33823. */
  33824. ColorCurves.clamp = function (value, min, max) {
  33825. return Math.min(Math.max(value, min), max);
  33826. };
  33827. /**
  33828. * Clones the current color curve instance.
  33829. * @return The cloned curves
  33830. */
  33831. ColorCurves.prototype.clone = function () {
  33832. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  33833. };
  33834. /**
  33835. * Serializes the current color curve instance to a json representation.
  33836. * @return a JSON representation
  33837. */
  33838. ColorCurves.prototype.serialize = function () {
  33839. return BABYLON.SerializationHelper.Serialize(this);
  33840. };
  33841. /**
  33842. * Parses the color curve from a json representation.
  33843. * @param source the JSON source to parse
  33844. * @return The parsed curves
  33845. */
  33846. ColorCurves.Parse = function (source) {
  33847. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  33848. };
  33849. __decorate([
  33850. BABYLON.serialize()
  33851. ], ColorCurves.prototype, "_globalHue", void 0);
  33852. __decorate([
  33853. BABYLON.serialize()
  33854. ], ColorCurves.prototype, "_globalDensity", void 0);
  33855. __decorate([
  33856. BABYLON.serialize()
  33857. ], ColorCurves.prototype, "_globalSaturation", void 0);
  33858. __decorate([
  33859. BABYLON.serialize()
  33860. ], ColorCurves.prototype, "_globalExposure", void 0);
  33861. __decorate([
  33862. BABYLON.serialize()
  33863. ], ColorCurves.prototype, "_highlightsHue", void 0);
  33864. __decorate([
  33865. BABYLON.serialize()
  33866. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  33867. __decorate([
  33868. BABYLON.serialize()
  33869. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  33870. __decorate([
  33871. BABYLON.serialize()
  33872. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  33873. __decorate([
  33874. BABYLON.serialize()
  33875. ], ColorCurves.prototype, "_midtonesHue", void 0);
  33876. __decorate([
  33877. BABYLON.serialize()
  33878. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  33879. __decorate([
  33880. BABYLON.serialize()
  33881. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  33882. __decorate([
  33883. BABYLON.serialize()
  33884. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  33885. return ColorCurves;
  33886. }());
  33887. BABYLON.ColorCurves = ColorCurves;
  33888. })(BABYLON || (BABYLON = {}));
  33889. //# sourceMappingURL=babylon.colorCurves.js.map
  33890. var BABYLON;
  33891. (function (BABYLON) {
  33892. var MaterialHelper = /** @class */ (function () {
  33893. function MaterialHelper() {
  33894. }
  33895. MaterialHelper.BindEyePosition = function (effect, scene) {
  33896. if (scene._forcedViewPosition) {
  33897. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  33898. return;
  33899. }
  33900. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  33901. };
  33902. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  33903. defines._needUVs = true;
  33904. defines[key] = true;
  33905. if (texture.getTextureMatrix().isIdentity(true)) {
  33906. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  33907. if (texture.coordinatesIndex === 0) {
  33908. defines["MAINUV1"] = true;
  33909. }
  33910. else {
  33911. defines["MAINUV2"] = true;
  33912. }
  33913. }
  33914. else {
  33915. defines[key + "DIRECTUV"] = 0;
  33916. }
  33917. };
  33918. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  33919. var matrix = texture.getTextureMatrix();
  33920. if (!matrix.isIdentity(true)) {
  33921. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  33922. }
  33923. };
  33924. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  33925. if (defines._areMiscDirty) {
  33926. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  33927. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  33928. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  33929. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  33930. }
  33931. };
  33932. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  33933. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  33934. var changed = false;
  33935. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  33936. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  33937. changed = true;
  33938. }
  33939. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  33940. defines["ALPHATEST"] = !defines["ALPHATEST"];
  33941. changed = true;
  33942. }
  33943. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  33944. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  33945. changed = true;
  33946. }
  33947. if (defines["INSTANCES"] !== useInstances) {
  33948. defines["INSTANCES"] = useInstances;
  33949. changed = true;
  33950. }
  33951. if (changed) {
  33952. defines.markAsUnprocessed();
  33953. }
  33954. };
  33955. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  33956. if (useMorphTargets === void 0) { useMorphTargets = false; }
  33957. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  33958. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  33959. return false;
  33960. }
  33961. defines._normals = defines._needNormals;
  33962. defines._uvs = defines._needUVs;
  33963. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  33964. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  33965. defines["TANGENT"] = true;
  33966. }
  33967. if (defines._needUVs) {
  33968. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  33969. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  33970. }
  33971. else {
  33972. defines["UV1"] = false;
  33973. defines["UV2"] = false;
  33974. }
  33975. if (useVertexColor) {
  33976. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  33977. defines["VERTEXCOLOR"] = hasVertexColors;
  33978. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  33979. }
  33980. if (useBones) {
  33981. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  33982. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  33983. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  33984. }
  33985. else {
  33986. defines["NUM_BONE_INFLUENCERS"] = 0;
  33987. defines["BonesPerMesh"] = 0;
  33988. }
  33989. }
  33990. if (useMorphTargets) {
  33991. var manager = mesh.morphTargetManager;
  33992. if (manager) {
  33993. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  33994. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  33995. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  33996. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  33997. }
  33998. else {
  33999. defines["MORPHTARGETS_TANGENT"] = false;
  34000. defines["MORPHTARGETS_NORMAL"] = false;
  34001. defines["MORPHTARGETS"] = false;
  34002. defines["NUM_MORPH_INFLUENCERS"] = 0;
  34003. }
  34004. }
  34005. return true;
  34006. };
  34007. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  34008. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34009. if (disableLighting === void 0) { disableLighting = false; }
  34010. if (!defines._areLightsDirty) {
  34011. return defines._needNormals;
  34012. }
  34013. var lightIndex = 0;
  34014. var needNormals = false;
  34015. var needRebuild = false;
  34016. var lightmapMode = false;
  34017. var shadowEnabled = false;
  34018. var specularEnabled = false;
  34019. if (scene.lightsEnabled && !disableLighting) {
  34020. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  34021. var light = _a[_i];
  34022. needNormals = true;
  34023. if (defines["LIGHT" + lightIndex] === undefined) {
  34024. needRebuild = true;
  34025. }
  34026. defines["LIGHT" + lightIndex] = true;
  34027. defines["SPOTLIGHT" + lightIndex] = false;
  34028. defines["HEMILIGHT" + lightIndex] = false;
  34029. defines["POINTLIGHT" + lightIndex] = false;
  34030. defines["DIRLIGHT" + lightIndex] = false;
  34031. var type;
  34032. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  34033. type = "SPOTLIGHT" + lightIndex;
  34034. }
  34035. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  34036. type = "HEMILIGHT" + lightIndex;
  34037. }
  34038. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  34039. type = "POINTLIGHT" + lightIndex;
  34040. }
  34041. else {
  34042. type = "DIRLIGHT" + lightIndex;
  34043. }
  34044. defines[type] = true;
  34045. // Specular
  34046. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  34047. specularEnabled = true;
  34048. }
  34049. // Shadows
  34050. defines["SHADOW" + lightIndex] = false;
  34051. defines["SHADOWPCF" + lightIndex] = false;
  34052. defines["SHADOWESM" + lightIndex] = false;
  34053. defines["SHADOWCUBE" + lightIndex] = false;
  34054. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  34055. var shadowGenerator = light.getShadowGenerator();
  34056. if (shadowGenerator) {
  34057. shadowEnabled = true;
  34058. shadowGenerator.prepareDefines(defines, lightIndex);
  34059. }
  34060. }
  34061. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  34062. lightmapMode = true;
  34063. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  34064. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  34065. }
  34066. else {
  34067. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  34068. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  34069. }
  34070. lightIndex++;
  34071. if (lightIndex === maxSimultaneousLights)
  34072. break;
  34073. }
  34074. }
  34075. defines["SPECULARTERM"] = specularEnabled;
  34076. defines["SHADOWS"] = shadowEnabled;
  34077. // Resetting all other lights if any
  34078. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  34079. if (defines["LIGHT" + index] !== undefined) {
  34080. defines["LIGHT" + index] = false;
  34081. defines["HEMILIGHT" + lightIndex] = false;
  34082. defines["POINTLIGHT" + lightIndex] = false;
  34083. defines["DIRLIGHT" + lightIndex] = false;
  34084. defines["SPOTLIGHT" + lightIndex] = false;
  34085. defines["SHADOW" + lightIndex] = false;
  34086. }
  34087. }
  34088. var caps = scene.getEngine().getCaps();
  34089. if (defines["SHADOWFLOAT"] === undefined) {
  34090. needRebuild = true;
  34091. }
  34092. defines["SHADOWFLOAT"] = shadowEnabled &&
  34093. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  34094. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  34095. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  34096. if (needRebuild) {
  34097. defines.rebuild();
  34098. }
  34099. return needNormals;
  34100. };
  34101. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  34102. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34103. var uniformsList;
  34104. var uniformBuffersList = null;
  34105. if (uniformsListOrOptions.uniformsNames) {
  34106. var options = uniformsListOrOptions;
  34107. uniformsList = options.uniformsNames;
  34108. uniformBuffersList = options.uniformBuffersNames;
  34109. samplersList = options.samplers;
  34110. defines = options.defines;
  34111. maxSimultaneousLights = options.maxSimultaneousLights;
  34112. }
  34113. else {
  34114. uniformsList = uniformsListOrOptions;
  34115. if (!samplersList) {
  34116. samplersList = [];
  34117. }
  34118. }
  34119. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  34120. if (!defines["LIGHT" + lightIndex]) {
  34121. break;
  34122. }
  34123. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  34124. if (uniformBuffersList) {
  34125. uniformBuffersList.push("Light" + lightIndex);
  34126. }
  34127. samplersList.push("shadowSampler" + lightIndex);
  34128. }
  34129. if (defines["NUM_MORPH_INFLUENCERS"]) {
  34130. uniformsList.push("morphTargetInfluences");
  34131. }
  34132. };
  34133. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  34134. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34135. if (rank === void 0) { rank = 0; }
  34136. var lightFallbackRank = 0;
  34137. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  34138. if (!defines["LIGHT" + lightIndex]) {
  34139. break;
  34140. }
  34141. if (lightIndex > 0) {
  34142. lightFallbackRank = rank + lightIndex;
  34143. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  34144. }
  34145. if (!defines["SHADOWS"]) {
  34146. if (defines["SHADOW" + lightIndex]) {
  34147. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  34148. }
  34149. if (defines["SHADOWPCF" + lightIndex]) {
  34150. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  34151. }
  34152. if (defines["SHADOWESM" + lightIndex]) {
  34153. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  34154. }
  34155. }
  34156. }
  34157. return lightFallbackRank++;
  34158. };
  34159. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  34160. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  34161. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  34162. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  34163. var manager = mesh.morphTargetManager;
  34164. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  34165. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  34166. for (var index = 0; index < influencers; index++) {
  34167. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  34168. if (normal) {
  34169. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  34170. }
  34171. if (tangent) {
  34172. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  34173. }
  34174. if (attribs.length > maxAttributesCount) {
  34175. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  34176. }
  34177. }
  34178. }
  34179. };
  34180. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  34181. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  34182. fallbacks.addCPUSkinningFallback(0, mesh);
  34183. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34184. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34185. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  34186. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34187. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  34188. }
  34189. }
  34190. };
  34191. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  34192. if (defines["INSTANCES"]) {
  34193. attribs.push("world0");
  34194. attribs.push("world1");
  34195. attribs.push("world2");
  34196. attribs.push("world3");
  34197. }
  34198. };
  34199. // Bindings
  34200. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  34201. if (light.shadowEnabled && mesh.receiveShadows) {
  34202. var shadowGenerator = light.getShadowGenerator();
  34203. if (shadowGenerator) {
  34204. shadowGenerator.bindShadowLight(lightIndex, effect);
  34205. }
  34206. }
  34207. };
  34208. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  34209. light.transferToEffect(effect, lightIndex + "");
  34210. };
  34211. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  34212. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34213. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  34214. var lightIndex = 0;
  34215. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  34216. var light = _a[_i];
  34217. var scaledIntensity = light.getScaledIntensity();
  34218. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  34219. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  34220. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  34221. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  34222. if (defines["SPECULARTERM"]) {
  34223. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  34224. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  34225. }
  34226. // Shadows
  34227. if (scene.shadowsEnabled) {
  34228. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  34229. }
  34230. light._uniformBuffer.update();
  34231. lightIndex++;
  34232. if (lightIndex === maxSimultaneousLights)
  34233. break;
  34234. }
  34235. };
  34236. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  34237. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  34238. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  34239. effect.setColor3("vFogColor", scene.fogColor);
  34240. }
  34241. };
  34242. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  34243. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  34244. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  34245. if (matrices && effect) {
  34246. effect.setMatrices("mBones", matrices);
  34247. }
  34248. }
  34249. };
  34250. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  34251. var manager = abstractMesh.morphTargetManager;
  34252. if (!abstractMesh || !manager) {
  34253. return;
  34254. }
  34255. effect.setFloatArray("morphTargetInfluences", manager.influences);
  34256. };
  34257. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  34258. if (defines["LOGARITHMICDEPTH"]) {
  34259. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  34260. }
  34261. };
  34262. MaterialHelper.BindClipPlane = function (effect, scene) {
  34263. if (scene.clipPlane) {
  34264. var clipPlane = scene.clipPlane;
  34265. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  34266. }
  34267. };
  34268. return MaterialHelper;
  34269. }());
  34270. BABYLON.MaterialHelper = MaterialHelper;
  34271. })(BABYLON || (BABYLON = {}));
  34272. //# sourceMappingURL=babylon.materialHelper.js.map
  34273. var BABYLON;
  34274. (function (BABYLON) {
  34275. var PushMaterial = /** @class */ (function (_super) {
  34276. __extends(PushMaterial, _super);
  34277. function PushMaterial(name, scene) {
  34278. var _this = _super.call(this, name, scene) || this;
  34279. _this.storeEffectOnSubMeshes = true;
  34280. return _this;
  34281. }
  34282. PushMaterial.prototype.getEffect = function () {
  34283. return this._activeEffect;
  34284. };
  34285. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  34286. if (!mesh) {
  34287. return false;
  34288. }
  34289. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  34290. return true;
  34291. }
  34292. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  34293. };
  34294. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  34295. this._activeEffect.setMatrix("world", world);
  34296. };
  34297. PushMaterial.prototype.bind = function (world, mesh) {
  34298. if (!mesh) {
  34299. return;
  34300. }
  34301. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  34302. };
  34303. PushMaterial.prototype._afterBind = function (mesh, effect) {
  34304. if (effect === void 0) { effect = null; }
  34305. _super.prototype._afterBind.call(this, mesh);
  34306. this.getScene()._cachedEffect = effect;
  34307. };
  34308. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  34309. if (visibility === void 0) { visibility = 1; }
  34310. return scene.isCachedMaterialInvalid(this, effect, visibility);
  34311. };
  34312. return PushMaterial;
  34313. }(BABYLON.Material));
  34314. BABYLON.PushMaterial = PushMaterial;
  34315. })(BABYLON || (BABYLON = {}));
  34316. //# sourceMappingURL=babylon.pushMaterial.js.map
  34317. var BABYLON;
  34318. (function (BABYLON) {
  34319. var StandardMaterialDefines = /** @class */ (function (_super) {
  34320. __extends(StandardMaterialDefines, _super);
  34321. function StandardMaterialDefines() {
  34322. var _this = _super.call(this) || this;
  34323. _this.MAINUV1 = false;
  34324. _this.MAINUV2 = false;
  34325. _this.DIFFUSE = false;
  34326. _this.DIFFUSEDIRECTUV = 0;
  34327. _this.AMBIENT = false;
  34328. _this.AMBIENTDIRECTUV = 0;
  34329. _this.OPACITY = false;
  34330. _this.OPACITYDIRECTUV = 0;
  34331. _this.OPACITYRGB = false;
  34332. _this.REFLECTION = false;
  34333. _this.EMISSIVE = false;
  34334. _this.EMISSIVEDIRECTUV = 0;
  34335. _this.SPECULAR = false;
  34336. _this.SPECULARDIRECTUV = 0;
  34337. _this.BUMP = false;
  34338. _this.BUMPDIRECTUV = 0;
  34339. _this.PARALLAX = false;
  34340. _this.PARALLAXOCCLUSION = false;
  34341. _this.SPECULAROVERALPHA = false;
  34342. _this.CLIPPLANE = false;
  34343. _this.ALPHATEST = false;
  34344. _this.DEPTHPREPASS = false;
  34345. _this.ALPHAFROMDIFFUSE = false;
  34346. _this.POINTSIZE = false;
  34347. _this.FOG = false;
  34348. _this.SPECULARTERM = false;
  34349. _this.DIFFUSEFRESNEL = false;
  34350. _this.OPACITYFRESNEL = false;
  34351. _this.REFLECTIONFRESNEL = false;
  34352. _this.REFRACTIONFRESNEL = false;
  34353. _this.EMISSIVEFRESNEL = false;
  34354. _this.FRESNEL = false;
  34355. _this.NORMAL = false;
  34356. _this.UV1 = false;
  34357. _this.UV2 = false;
  34358. _this.VERTEXCOLOR = false;
  34359. _this.VERTEXALPHA = false;
  34360. _this.NUM_BONE_INFLUENCERS = 0;
  34361. _this.BonesPerMesh = 0;
  34362. _this.INSTANCES = false;
  34363. _this.GLOSSINESS = false;
  34364. _this.ROUGHNESS = false;
  34365. _this.EMISSIVEASILLUMINATION = false;
  34366. _this.LINKEMISSIVEWITHDIFFUSE = false;
  34367. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  34368. _this.LIGHTMAP = false;
  34369. _this.LIGHTMAPDIRECTUV = 0;
  34370. _this.USELIGHTMAPASSHADOWMAP = false;
  34371. _this.REFLECTIONMAP_3D = false;
  34372. _this.REFLECTIONMAP_SPHERICAL = false;
  34373. _this.REFLECTIONMAP_PLANAR = false;
  34374. _this.REFLECTIONMAP_CUBIC = false;
  34375. _this.REFLECTIONMAP_PROJECTION = false;
  34376. _this.REFLECTIONMAP_SKYBOX = false;
  34377. _this.REFLECTIONMAP_EXPLICIT = false;
  34378. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34379. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34380. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34381. _this.INVERTCUBICMAP = false;
  34382. _this.LOGARITHMICDEPTH = false;
  34383. _this.REFRACTION = false;
  34384. _this.REFRACTIONMAP_3D = false;
  34385. _this.REFLECTIONOVERALPHA = false;
  34386. _this.TWOSIDEDLIGHTING = false;
  34387. _this.SHADOWFLOAT = false;
  34388. _this.MORPHTARGETS = false;
  34389. _this.MORPHTARGETS_NORMAL = false;
  34390. _this.MORPHTARGETS_TANGENT = false;
  34391. _this.NUM_MORPH_INFLUENCERS = 0;
  34392. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  34393. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  34394. _this.IMAGEPROCESSING = false;
  34395. _this.VIGNETTE = false;
  34396. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  34397. _this.VIGNETTEBLENDMODEOPAQUE = false;
  34398. _this.TONEMAPPING = false;
  34399. _this.CONTRAST = false;
  34400. _this.COLORCURVES = false;
  34401. _this.COLORGRADING = false;
  34402. _this.COLORGRADING3D = false;
  34403. _this.SAMPLER3DGREENDEPTH = false;
  34404. _this.SAMPLER3DBGRMAP = false;
  34405. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  34406. _this.EXPOSURE = false;
  34407. _this.rebuild();
  34408. return _this;
  34409. }
  34410. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  34411. var modes = [
  34412. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  34413. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  34414. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  34415. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  34416. ];
  34417. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  34418. var mode = modes_1[_i];
  34419. this[mode] = (mode === modeToEnable);
  34420. }
  34421. };
  34422. return StandardMaterialDefines;
  34423. }(BABYLON.MaterialDefines));
  34424. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  34425. var StandardMaterial = /** @class */ (function (_super) {
  34426. __extends(StandardMaterial, _super);
  34427. function StandardMaterial(name, scene) {
  34428. var _this = _super.call(this, name, scene) || this;
  34429. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  34430. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  34431. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  34432. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  34433. _this.specularPower = 64;
  34434. _this._useAlphaFromDiffuseTexture = false;
  34435. _this._useEmissiveAsIllumination = false;
  34436. _this._linkEmissiveWithDiffuse = false;
  34437. _this._useSpecularOverAlpha = false;
  34438. _this._useReflectionOverAlpha = false;
  34439. _this._disableLighting = false;
  34440. _this._useParallax = false;
  34441. _this._useParallaxOcclusion = false;
  34442. _this.parallaxScaleBias = 0.05;
  34443. _this._roughness = 0;
  34444. _this.indexOfRefraction = 0.98;
  34445. _this.invertRefractionY = true;
  34446. _this._useLightmapAsShadowmap = false;
  34447. _this._useReflectionFresnelFromSpecular = false;
  34448. _this._useGlossinessFromSpecularMapAlpha = false;
  34449. _this._maxSimultaneousLights = 4;
  34450. /**
  34451. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  34452. */
  34453. _this._invertNormalMapX = false;
  34454. /**
  34455. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  34456. */
  34457. _this._invertNormalMapY = false;
  34458. /**
  34459. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34460. */
  34461. _this._twoSidedLighting = false;
  34462. _this._renderTargets = new BABYLON.SmartArray(16);
  34463. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  34464. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34465. // Setup the default processing configuration to the scene.
  34466. _this._attachImageProcessingConfiguration(null);
  34467. _this.getRenderTargetTextures = function () {
  34468. _this._renderTargets.reset();
  34469. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  34470. _this._renderTargets.push(_this._reflectionTexture);
  34471. }
  34472. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  34473. _this._renderTargets.push(_this._refractionTexture);
  34474. }
  34475. return _this._renderTargets;
  34476. };
  34477. return _this;
  34478. }
  34479. ;
  34480. ;
  34481. ;
  34482. ;
  34483. ;
  34484. ;
  34485. ;
  34486. ;
  34487. ;
  34488. ;
  34489. ;
  34490. ;
  34491. ;
  34492. ;
  34493. ;
  34494. ;
  34495. ;
  34496. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  34497. /**
  34498. * Gets the image processing configuration used either in this material.
  34499. */
  34500. get: function () {
  34501. return this._imageProcessingConfiguration;
  34502. },
  34503. /**
  34504. * Sets the Default image processing configuration used either in the this material.
  34505. *
  34506. * If sets to null, the scene one is in use.
  34507. */
  34508. set: function (value) {
  34509. this._attachImageProcessingConfiguration(value);
  34510. // Ensure the effect will be rebuilt.
  34511. this._markAllSubMeshesAsTexturesDirty();
  34512. },
  34513. enumerable: true,
  34514. configurable: true
  34515. });
  34516. /**
  34517. * Attaches a new image processing configuration to the Standard Material.
  34518. * @param configuration
  34519. */
  34520. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  34521. var _this = this;
  34522. if (configuration === this._imageProcessingConfiguration) {
  34523. return;
  34524. }
  34525. // Detaches observer.
  34526. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34527. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34528. }
  34529. // Pick the scene configuration if needed.
  34530. if (!configuration) {
  34531. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  34532. }
  34533. else {
  34534. this._imageProcessingConfiguration = configuration;
  34535. }
  34536. // Attaches observer.
  34537. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  34538. _this._markAllSubMeshesAsImageProcessingDirty();
  34539. });
  34540. };
  34541. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  34542. /**
  34543. * Gets wether the color curves effect is enabled.
  34544. */
  34545. get: function () {
  34546. return this.imageProcessingConfiguration.colorCurvesEnabled;
  34547. },
  34548. /**
  34549. * Sets wether the color curves effect is enabled.
  34550. */
  34551. set: function (value) {
  34552. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  34553. },
  34554. enumerable: true,
  34555. configurable: true
  34556. });
  34557. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  34558. /**
  34559. * Gets wether the color grading effect is enabled.
  34560. */
  34561. get: function () {
  34562. return this.imageProcessingConfiguration.colorGradingEnabled;
  34563. },
  34564. /**
  34565. * Gets wether the color grading effect is enabled.
  34566. */
  34567. set: function (value) {
  34568. this.imageProcessingConfiguration.colorGradingEnabled = value;
  34569. },
  34570. enumerable: true,
  34571. configurable: true
  34572. });
  34573. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  34574. /**
  34575. * Gets wether tonemapping is enabled or not.
  34576. */
  34577. get: function () {
  34578. return this._imageProcessingConfiguration.toneMappingEnabled;
  34579. },
  34580. /**
  34581. * Sets wether tonemapping is enabled or not
  34582. */
  34583. set: function (value) {
  34584. this._imageProcessingConfiguration.toneMappingEnabled = value;
  34585. },
  34586. enumerable: true,
  34587. configurable: true
  34588. });
  34589. ;
  34590. ;
  34591. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  34592. /**
  34593. * The camera exposure used on this material.
  34594. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  34595. * This corresponds to a photographic exposure.
  34596. */
  34597. get: function () {
  34598. return this._imageProcessingConfiguration.exposure;
  34599. },
  34600. /**
  34601. * The camera exposure used on this material.
  34602. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  34603. * This corresponds to a photographic exposure.
  34604. */
  34605. set: function (value) {
  34606. this._imageProcessingConfiguration.exposure = value;
  34607. },
  34608. enumerable: true,
  34609. configurable: true
  34610. });
  34611. ;
  34612. ;
  34613. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  34614. /**
  34615. * Gets The camera contrast used on this material.
  34616. */
  34617. get: function () {
  34618. return this._imageProcessingConfiguration.contrast;
  34619. },
  34620. /**
  34621. * Sets The camera contrast used on this material.
  34622. */
  34623. set: function (value) {
  34624. this._imageProcessingConfiguration.contrast = value;
  34625. },
  34626. enumerable: true,
  34627. configurable: true
  34628. });
  34629. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  34630. /**
  34631. * Gets the Color Grading 2D Lookup Texture.
  34632. */
  34633. get: function () {
  34634. return this._imageProcessingConfiguration.colorGradingTexture;
  34635. },
  34636. /**
  34637. * Sets the Color Grading 2D Lookup Texture.
  34638. */
  34639. set: function (value) {
  34640. this._imageProcessingConfiguration.colorGradingTexture = value;
  34641. },
  34642. enumerable: true,
  34643. configurable: true
  34644. });
  34645. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  34646. /**
  34647. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34648. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34649. * 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;
  34650. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34651. */
  34652. get: function () {
  34653. return this._imageProcessingConfiguration.colorCurves;
  34654. },
  34655. /**
  34656. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34657. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34658. * 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;
  34659. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34660. */
  34661. set: function (value) {
  34662. this._imageProcessingConfiguration.colorCurves = value;
  34663. },
  34664. enumerable: true,
  34665. configurable: true
  34666. });
  34667. StandardMaterial.prototype.getClassName = function () {
  34668. return "StandardMaterial";
  34669. };
  34670. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  34671. get: function () {
  34672. return this._useLogarithmicDepth;
  34673. },
  34674. set: function (value) {
  34675. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  34676. this._markAllSubMeshesAsMiscDirty();
  34677. },
  34678. enumerable: true,
  34679. configurable: true
  34680. });
  34681. StandardMaterial.prototype.needAlphaBlending = function () {
  34682. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  34683. };
  34684. StandardMaterial.prototype.needAlphaTesting = function () {
  34685. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  34686. };
  34687. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  34688. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  34689. };
  34690. StandardMaterial.prototype.getAlphaTestTexture = function () {
  34691. return this._diffuseTexture;
  34692. };
  34693. /**
  34694. * Child classes can use it to update shaders
  34695. */
  34696. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34697. if (useInstances === void 0) { useInstances = false; }
  34698. if (subMesh.effect && this.isFrozen) {
  34699. if (this._wasPreviouslyReady && subMesh.effect) {
  34700. return true;
  34701. }
  34702. }
  34703. if (!subMesh._materialDefines) {
  34704. subMesh._materialDefines = new StandardMaterialDefines();
  34705. }
  34706. var scene = this.getScene();
  34707. var defines = subMesh._materialDefines;
  34708. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  34709. if (defines._renderId === scene.getRenderId()) {
  34710. return true;
  34711. }
  34712. }
  34713. var engine = scene.getEngine();
  34714. // Lights
  34715. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  34716. // Textures
  34717. if (defines._areTexturesDirty) {
  34718. defines._needUVs = false;
  34719. defines.MAINUV1 = false;
  34720. defines.MAINUV2 = false;
  34721. if (scene.texturesEnabled) {
  34722. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34723. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  34724. return false;
  34725. }
  34726. else {
  34727. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  34728. }
  34729. }
  34730. else {
  34731. defines.DIFFUSE = false;
  34732. }
  34733. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34734. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  34735. return false;
  34736. }
  34737. else {
  34738. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  34739. }
  34740. }
  34741. else {
  34742. defines.AMBIENT = false;
  34743. }
  34744. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34745. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  34746. return false;
  34747. }
  34748. else {
  34749. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  34750. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  34751. }
  34752. }
  34753. else {
  34754. defines.OPACITY = false;
  34755. }
  34756. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34757. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  34758. return false;
  34759. }
  34760. else {
  34761. defines._needNormals = true;
  34762. defines.REFLECTION = true;
  34763. defines.ROUGHNESS = (this._roughness > 0);
  34764. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  34765. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  34766. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  34767. switch (this._reflectionTexture.coordinatesMode) {
  34768. case BABYLON.Texture.CUBIC_MODE:
  34769. case BABYLON.Texture.INVCUBIC_MODE:
  34770. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  34771. break;
  34772. case BABYLON.Texture.EXPLICIT_MODE:
  34773. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  34774. break;
  34775. case BABYLON.Texture.PLANAR_MODE:
  34776. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  34777. break;
  34778. case BABYLON.Texture.PROJECTION_MODE:
  34779. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  34780. break;
  34781. case BABYLON.Texture.SKYBOX_MODE:
  34782. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  34783. break;
  34784. case BABYLON.Texture.SPHERICAL_MODE:
  34785. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  34786. break;
  34787. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  34788. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  34789. break;
  34790. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  34791. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  34792. break;
  34793. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  34794. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  34795. break;
  34796. }
  34797. }
  34798. }
  34799. else {
  34800. defines.REFLECTION = false;
  34801. }
  34802. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34803. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  34804. return false;
  34805. }
  34806. else {
  34807. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  34808. }
  34809. }
  34810. else {
  34811. defines.EMISSIVE = false;
  34812. }
  34813. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34814. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  34815. return false;
  34816. }
  34817. else {
  34818. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  34819. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  34820. }
  34821. }
  34822. else {
  34823. defines.LIGHTMAP = false;
  34824. }
  34825. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34826. if (!this._specularTexture.isReadyOrNotBlocking()) {
  34827. return false;
  34828. }
  34829. else {
  34830. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  34831. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  34832. }
  34833. }
  34834. else {
  34835. defines.SPECULAR = false;
  34836. }
  34837. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  34838. // Bump texure can not be not blocking.
  34839. if (!this._bumpTexture.isReady()) {
  34840. return false;
  34841. }
  34842. else {
  34843. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  34844. defines.PARALLAX = this._useParallax;
  34845. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  34846. }
  34847. }
  34848. else {
  34849. defines.BUMP = false;
  34850. }
  34851. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34852. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  34853. return false;
  34854. }
  34855. else {
  34856. defines._needUVs = true;
  34857. defines.REFRACTION = true;
  34858. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  34859. }
  34860. }
  34861. else {
  34862. defines.REFRACTION = false;
  34863. }
  34864. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  34865. }
  34866. else {
  34867. defines.DIFFUSE = false;
  34868. defines.AMBIENT = false;
  34869. defines.OPACITY = false;
  34870. defines.REFLECTION = false;
  34871. defines.EMISSIVE = false;
  34872. defines.LIGHTMAP = false;
  34873. defines.BUMP = false;
  34874. defines.REFRACTION = false;
  34875. }
  34876. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  34877. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  34878. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  34879. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  34880. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  34881. }
  34882. if (defines._areImageProcessingDirty) {
  34883. if (!this._imageProcessingConfiguration.isReady()) {
  34884. return false;
  34885. }
  34886. this._imageProcessingConfiguration.prepareDefines(defines);
  34887. }
  34888. if (defines._areFresnelDirty) {
  34889. if (StandardMaterial.FresnelEnabled) {
  34890. // Fresnel
  34891. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  34892. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  34893. this._reflectionFresnelParameters) {
  34894. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  34895. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  34896. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  34897. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  34898. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  34899. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  34900. defines._needNormals = true;
  34901. defines.FRESNEL = true;
  34902. }
  34903. }
  34904. else {
  34905. defines.FRESNEL = false;
  34906. }
  34907. }
  34908. // Misc.
  34909. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  34910. // Attribs
  34911. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  34912. // Values that need to be evaluated on every frame
  34913. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  34914. // Get correct effect
  34915. if (defines.isDirty) {
  34916. defines.markAsProcessed();
  34917. scene.resetCachedMaterial();
  34918. // Fallbacks
  34919. var fallbacks = new BABYLON.EffectFallbacks();
  34920. if (defines.REFLECTION) {
  34921. fallbacks.addFallback(0, "REFLECTION");
  34922. }
  34923. if (defines.SPECULAR) {
  34924. fallbacks.addFallback(0, "SPECULAR");
  34925. }
  34926. if (defines.BUMP) {
  34927. fallbacks.addFallback(0, "BUMP");
  34928. }
  34929. if (defines.PARALLAX) {
  34930. fallbacks.addFallback(1, "PARALLAX");
  34931. }
  34932. if (defines.PARALLAXOCCLUSION) {
  34933. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  34934. }
  34935. if (defines.SPECULAROVERALPHA) {
  34936. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  34937. }
  34938. if (defines.FOG) {
  34939. fallbacks.addFallback(1, "FOG");
  34940. }
  34941. if (defines.POINTSIZE) {
  34942. fallbacks.addFallback(0, "POINTSIZE");
  34943. }
  34944. if (defines.LOGARITHMICDEPTH) {
  34945. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  34946. }
  34947. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  34948. if (defines.SPECULARTERM) {
  34949. fallbacks.addFallback(0, "SPECULARTERM");
  34950. }
  34951. if (defines.DIFFUSEFRESNEL) {
  34952. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  34953. }
  34954. if (defines.OPACITYFRESNEL) {
  34955. fallbacks.addFallback(2, "OPACITYFRESNEL");
  34956. }
  34957. if (defines.REFLECTIONFRESNEL) {
  34958. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  34959. }
  34960. if (defines.EMISSIVEFRESNEL) {
  34961. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  34962. }
  34963. if (defines.FRESNEL) {
  34964. fallbacks.addFallback(4, "FRESNEL");
  34965. }
  34966. //Attributes
  34967. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34968. if (defines.NORMAL) {
  34969. attribs.push(BABYLON.VertexBuffer.NormalKind);
  34970. }
  34971. if (defines.UV1) {
  34972. attribs.push(BABYLON.VertexBuffer.UVKind);
  34973. }
  34974. if (defines.UV2) {
  34975. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34976. }
  34977. if (defines.VERTEXCOLOR) {
  34978. attribs.push(BABYLON.VertexBuffer.ColorKind);
  34979. }
  34980. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  34981. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  34982. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  34983. var shaderName = "default";
  34984. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  34985. "vFogInfos", "vFogColor", "pointSize",
  34986. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  34987. "mBones",
  34988. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  34989. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  34990. "logarithmicDepthConstant", "vTangentSpaceParams"
  34991. ];
  34992. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  34993. var uniformBuffers = ["Material", "Scene"];
  34994. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  34995. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  34996. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  34997. uniformsNames: uniforms,
  34998. uniformBuffersNames: uniformBuffers,
  34999. samplers: samplers,
  35000. defines: defines,
  35001. maxSimultaneousLights: this._maxSimultaneousLights
  35002. });
  35003. if (this.customShaderNameResolve) {
  35004. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  35005. }
  35006. var join = defines.toString();
  35007. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  35008. attributes: attribs,
  35009. uniformsNames: uniforms,
  35010. uniformBuffersNames: uniformBuffers,
  35011. samplers: samplers,
  35012. defines: join,
  35013. fallbacks: fallbacks,
  35014. onCompiled: this.onCompiled,
  35015. onError: this.onError,
  35016. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35017. }, engine), defines);
  35018. this.buildUniformLayout();
  35019. }
  35020. if (!subMesh.effect || !subMesh.effect.isReady()) {
  35021. return false;
  35022. }
  35023. defines._renderId = scene.getRenderId();
  35024. this._wasPreviouslyReady = true;
  35025. return true;
  35026. };
  35027. StandardMaterial.prototype.buildUniformLayout = function () {
  35028. // Order is important !
  35029. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  35030. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  35031. this._uniformBuffer.addUniform("opacityParts", 4);
  35032. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  35033. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  35034. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  35035. this._uniformBuffer.addUniform("refractionRightColor", 4);
  35036. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  35037. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  35038. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  35039. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  35040. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35041. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35042. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35043. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35044. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  35045. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35046. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  35047. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35048. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35049. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35050. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35051. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35052. this._uniformBuffer.addUniform("specularMatrix", 16);
  35053. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35054. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  35055. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35056. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35057. this._uniformBuffer.addUniform("vSpecularColor", 4);
  35058. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35059. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  35060. this._uniformBuffer.addUniform("pointSize", 1);
  35061. this._uniformBuffer.create();
  35062. };
  35063. StandardMaterial.prototype.unbind = function () {
  35064. if (this._activeEffect) {
  35065. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35066. this._activeEffect.setTexture("reflection2DSampler", null);
  35067. }
  35068. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35069. this._activeEffect.setTexture("refraction2DSampler", null);
  35070. }
  35071. }
  35072. _super.prototype.unbind.call(this);
  35073. };
  35074. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35075. var scene = this.getScene();
  35076. var defines = subMesh._materialDefines;
  35077. if (!defines) {
  35078. return;
  35079. }
  35080. var effect = subMesh.effect;
  35081. if (!effect) {
  35082. return;
  35083. }
  35084. this._activeEffect = effect;
  35085. // Matrices
  35086. this.bindOnlyWorldMatrix(world);
  35087. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  35088. // Bones
  35089. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  35090. if (mustRebind) {
  35091. this._uniformBuffer.bindToEffect(effect, "Material");
  35092. this.bindViewProjection(effect);
  35093. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35094. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  35095. // Fresnel
  35096. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  35097. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  35098. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  35099. }
  35100. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  35101. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  35102. }
  35103. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  35104. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  35105. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  35106. }
  35107. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  35108. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  35109. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  35110. }
  35111. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  35112. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  35113. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  35114. }
  35115. }
  35116. // Textures
  35117. if (scene.texturesEnabled) {
  35118. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35119. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  35120. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  35121. }
  35122. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35123. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  35124. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  35125. }
  35126. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35127. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35128. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  35129. }
  35130. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35131. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  35132. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  35133. }
  35134. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35135. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35136. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  35137. }
  35138. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35139. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35140. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  35141. }
  35142. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35143. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  35144. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  35145. }
  35146. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35147. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  35148. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  35149. if (scene._mirroredCameraPosition) {
  35150. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  35151. }
  35152. else {
  35153. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  35154. }
  35155. }
  35156. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35157. var depth = 1.0;
  35158. if (!this._refractionTexture.isCube) {
  35159. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  35160. if (this._refractionTexture.depth) {
  35161. depth = this._refractionTexture.depth;
  35162. }
  35163. }
  35164. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  35165. }
  35166. }
  35167. // Point size
  35168. if (this.pointsCloud) {
  35169. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35170. }
  35171. if (defines.SPECULARTERM) {
  35172. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  35173. }
  35174. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  35175. // Diffuse
  35176. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  35177. }
  35178. // Textures
  35179. if (scene.texturesEnabled) {
  35180. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35181. effect.setTexture("diffuseSampler", this._diffuseTexture);
  35182. }
  35183. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35184. effect.setTexture("ambientSampler", this._ambientTexture);
  35185. }
  35186. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35187. effect.setTexture("opacitySampler", this._opacityTexture);
  35188. }
  35189. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35190. if (this._reflectionTexture.isCube) {
  35191. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  35192. }
  35193. else {
  35194. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  35195. }
  35196. }
  35197. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35198. effect.setTexture("emissiveSampler", this._emissiveTexture);
  35199. }
  35200. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35201. effect.setTexture("lightmapSampler", this._lightmapTexture);
  35202. }
  35203. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35204. effect.setTexture("specularSampler", this._specularTexture);
  35205. }
  35206. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35207. effect.setTexture("bumpSampler", this._bumpTexture);
  35208. }
  35209. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35210. var depth = 1.0;
  35211. if (this._refractionTexture.isCube) {
  35212. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  35213. }
  35214. else {
  35215. effect.setTexture("refraction2DSampler", this._refractionTexture);
  35216. }
  35217. }
  35218. }
  35219. // Clip plane
  35220. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  35221. // Colors
  35222. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  35223. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  35224. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35225. }
  35226. if (mustRebind || !this.isFrozen) {
  35227. // Lights
  35228. if (scene.lightsEnabled && !this._disableLighting) {
  35229. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  35230. }
  35231. // View
  35232. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  35233. this.bindView(effect);
  35234. }
  35235. // Fog
  35236. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  35237. // Morph targets
  35238. if (defines.NUM_MORPH_INFLUENCERS) {
  35239. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  35240. }
  35241. // Log. depth
  35242. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  35243. // image processing
  35244. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  35245. this._imageProcessingConfiguration.bind(this._activeEffect);
  35246. }
  35247. }
  35248. this._uniformBuffer.update();
  35249. this._afterBind(mesh, this._activeEffect);
  35250. };
  35251. StandardMaterial.prototype.getAnimatables = function () {
  35252. var results = [];
  35253. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  35254. results.push(this._diffuseTexture);
  35255. }
  35256. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35257. results.push(this._ambientTexture);
  35258. }
  35259. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35260. results.push(this._opacityTexture);
  35261. }
  35262. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35263. results.push(this._reflectionTexture);
  35264. }
  35265. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35266. results.push(this._emissiveTexture);
  35267. }
  35268. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  35269. results.push(this._specularTexture);
  35270. }
  35271. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35272. results.push(this._bumpTexture);
  35273. }
  35274. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35275. results.push(this._lightmapTexture);
  35276. }
  35277. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35278. results.push(this._refractionTexture);
  35279. }
  35280. return results;
  35281. };
  35282. StandardMaterial.prototype.getActiveTextures = function () {
  35283. var activeTextures = _super.prototype.getActiveTextures.call(this);
  35284. if (this._diffuseTexture) {
  35285. activeTextures.push(this._diffuseTexture);
  35286. }
  35287. if (this._ambientTexture) {
  35288. activeTextures.push(this._ambientTexture);
  35289. }
  35290. if (this._opacityTexture) {
  35291. activeTextures.push(this._opacityTexture);
  35292. }
  35293. if (this._reflectionTexture) {
  35294. activeTextures.push(this._reflectionTexture);
  35295. }
  35296. if (this._emissiveTexture) {
  35297. activeTextures.push(this._emissiveTexture);
  35298. }
  35299. if (this._specularTexture) {
  35300. activeTextures.push(this._specularTexture);
  35301. }
  35302. if (this._bumpTexture) {
  35303. activeTextures.push(this._bumpTexture);
  35304. }
  35305. if (this._lightmapTexture) {
  35306. activeTextures.push(this._lightmapTexture);
  35307. }
  35308. if (this._refractionTexture) {
  35309. activeTextures.push(this._refractionTexture);
  35310. }
  35311. return activeTextures;
  35312. };
  35313. StandardMaterial.prototype.hasTexture = function (texture) {
  35314. if (_super.prototype.hasTexture.call(this, texture)) {
  35315. return true;
  35316. }
  35317. if (this._diffuseTexture === texture) {
  35318. return true;
  35319. }
  35320. if (this._ambientTexture === texture) {
  35321. return true;
  35322. }
  35323. if (this._opacityTexture === texture) {
  35324. return true;
  35325. }
  35326. if (this._reflectionTexture === texture) {
  35327. return true;
  35328. }
  35329. if (this._emissiveTexture === texture) {
  35330. return true;
  35331. }
  35332. if (this._specularTexture === texture) {
  35333. return true;
  35334. }
  35335. if (this._bumpTexture === texture) {
  35336. return true;
  35337. }
  35338. if (this._lightmapTexture === texture) {
  35339. return true;
  35340. }
  35341. if (this._refractionTexture === texture) {
  35342. return true;
  35343. }
  35344. return false;
  35345. };
  35346. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35347. if (forceDisposeTextures) {
  35348. if (this._diffuseTexture) {
  35349. this._diffuseTexture.dispose();
  35350. }
  35351. if (this._ambientTexture) {
  35352. this._ambientTexture.dispose();
  35353. }
  35354. if (this._opacityTexture) {
  35355. this._opacityTexture.dispose();
  35356. }
  35357. if (this._reflectionTexture) {
  35358. this._reflectionTexture.dispose();
  35359. }
  35360. if (this._emissiveTexture) {
  35361. this._emissiveTexture.dispose();
  35362. }
  35363. if (this._specularTexture) {
  35364. this._specularTexture.dispose();
  35365. }
  35366. if (this._bumpTexture) {
  35367. this._bumpTexture.dispose();
  35368. }
  35369. if (this._lightmapTexture) {
  35370. this._lightmapTexture.dispose();
  35371. }
  35372. if (this._refractionTexture) {
  35373. this._refractionTexture.dispose();
  35374. }
  35375. }
  35376. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35377. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35378. }
  35379. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35380. };
  35381. StandardMaterial.prototype.clone = function (name) {
  35382. var _this = this;
  35383. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  35384. result.name = name;
  35385. result.id = name;
  35386. return result;
  35387. };
  35388. StandardMaterial.prototype.serialize = function () {
  35389. return BABYLON.SerializationHelper.Serialize(this);
  35390. };
  35391. // Statics
  35392. StandardMaterial.Parse = function (source, scene, rootUrl) {
  35393. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  35394. };
  35395. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  35396. get: function () {
  35397. return StandardMaterial._DiffuseTextureEnabled;
  35398. },
  35399. set: function (value) {
  35400. if (StandardMaterial._DiffuseTextureEnabled === value) {
  35401. return;
  35402. }
  35403. StandardMaterial._DiffuseTextureEnabled = value;
  35404. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35405. },
  35406. enumerable: true,
  35407. configurable: true
  35408. });
  35409. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  35410. get: function () {
  35411. return StandardMaterial._AmbientTextureEnabled;
  35412. },
  35413. set: function (value) {
  35414. if (StandardMaterial._AmbientTextureEnabled === value) {
  35415. return;
  35416. }
  35417. StandardMaterial._AmbientTextureEnabled = value;
  35418. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35419. },
  35420. enumerable: true,
  35421. configurable: true
  35422. });
  35423. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  35424. get: function () {
  35425. return StandardMaterial._OpacityTextureEnabled;
  35426. },
  35427. set: function (value) {
  35428. if (StandardMaterial._OpacityTextureEnabled === value) {
  35429. return;
  35430. }
  35431. StandardMaterial._OpacityTextureEnabled = value;
  35432. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35433. },
  35434. enumerable: true,
  35435. configurable: true
  35436. });
  35437. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  35438. get: function () {
  35439. return StandardMaterial._ReflectionTextureEnabled;
  35440. },
  35441. set: function (value) {
  35442. if (StandardMaterial._ReflectionTextureEnabled === value) {
  35443. return;
  35444. }
  35445. StandardMaterial._ReflectionTextureEnabled = value;
  35446. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35447. },
  35448. enumerable: true,
  35449. configurable: true
  35450. });
  35451. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  35452. get: function () {
  35453. return StandardMaterial._EmissiveTextureEnabled;
  35454. },
  35455. set: function (value) {
  35456. if (StandardMaterial._EmissiveTextureEnabled === value) {
  35457. return;
  35458. }
  35459. StandardMaterial._EmissiveTextureEnabled = value;
  35460. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35461. },
  35462. enumerable: true,
  35463. configurable: true
  35464. });
  35465. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  35466. get: function () {
  35467. return StandardMaterial._SpecularTextureEnabled;
  35468. },
  35469. set: function (value) {
  35470. if (StandardMaterial._SpecularTextureEnabled === value) {
  35471. return;
  35472. }
  35473. StandardMaterial._SpecularTextureEnabled = value;
  35474. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35475. },
  35476. enumerable: true,
  35477. configurable: true
  35478. });
  35479. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  35480. get: function () {
  35481. return StandardMaterial._BumpTextureEnabled;
  35482. },
  35483. set: function (value) {
  35484. if (StandardMaterial._BumpTextureEnabled === value) {
  35485. return;
  35486. }
  35487. StandardMaterial._BumpTextureEnabled = value;
  35488. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35489. },
  35490. enumerable: true,
  35491. configurable: true
  35492. });
  35493. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  35494. get: function () {
  35495. return StandardMaterial._LightmapTextureEnabled;
  35496. },
  35497. set: function (value) {
  35498. if (StandardMaterial._LightmapTextureEnabled === value) {
  35499. return;
  35500. }
  35501. StandardMaterial._LightmapTextureEnabled = value;
  35502. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35503. },
  35504. enumerable: true,
  35505. configurable: true
  35506. });
  35507. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  35508. get: function () {
  35509. return StandardMaterial._RefractionTextureEnabled;
  35510. },
  35511. set: function (value) {
  35512. if (StandardMaterial._RefractionTextureEnabled === value) {
  35513. return;
  35514. }
  35515. StandardMaterial._RefractionTextureEnabled = value;
  35516. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35517. },
  35518. enumerable: true,
  35519. configurable: true
  35520. });
  35521. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  35522. get: function () {
  35523. return StandardMaterial._ColorGradingTextureEnabled;
  35524. },
  35525. set: function (value) {
  35526. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  35527. return;
  35528. }
  35529. StandardMaterial._ColorGradingTextureEnabled = value;
  35530. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35531. },
  35532. enumerable: true,
  35533. configurable: true
  35534. });
  35535. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  35536. get: function () {
  35537. return StandardMaterial._FresnelEnabled;
  35538. },
  35539. set: function (value) {
  35540. if (StandardMaterial._FresnelEnabled === value) {
  35541. return;
  35542. }
  35543. StandardMaterial._FresnelEnabled = value;
  35544. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  35545. },
  35546. enumerable: true,
  35547. configurable: true
  35548. });
  35549. // Flags used to enable or disable a type of texture for all Standard Materials
  35550. StandardMaterial._DiffuseTextureEnabled = true;
  35551. StandardMaterial._AmbientTextureEnabled = true;
  35552. StandardMaterial._OpacityTextureEnabled = true;
  35553. StandardMaterial._ReflectionTextureEnabled = true;
  35554. StandardMaterial._EmissiveTextureEnabled = true;
  35555. StandardMaterial._SpecularTextureEnabled = true;
  35556. StandardMaterial._BumpTextureEnabled = true;
  35557. StandardMaterial._LightmapTextureEnabled = true;
  35558. StandardMaterial._RefractionTextureEnabled = true;
  35559. StandardMaterial._ColorGradingTextureEnabled = true;
  35560. StandardMaterial._FresnelEnabled = true;
  35561. __decorate([
  35562. BABYLON.serializeAsTexture("diffuseTexture")
  35563. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  35564. __decorate([
  35565. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35566. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  35567. __decorate([
  35568. BABYLON.serializeAsTexture("ambientTexture")
  35569. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  35570. __decorate([
  35571. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35572. ], StandardMaterial.prototype, "ambientTexture", void 0);
  35573. __decorate([
  35574. BABYLON.serializeAsTexture("opacityTexture")
  35575. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  35576. __decorate([
  35577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35578. ], StandardMaterial.prototype, "opacityTexture", void 0);
  35579. __decorate([
  35580. BABYLON.serializeAsTexture("reflectionTexture")
  35581. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  35582. __decorate([
  35583. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35584. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  35585. __decorate([
  35586. BABYLON.serializeAsTexture("emissiveTexture")
  35587. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  35588. __decorate([
  35589. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35590. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  35591. __decorate([
  35592. BABYLON.serializeAsTexture("specularTexture")
  35593. ], StandardMaterial.prototype, "_specularTexture", void 0);
  35594. __decorate([
  35595. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35596. ], StandardMaterial.prototype, "specularTexture", void 0);
  35597. __decorate([
  35598. BABYLON.serializeAsTexture("bumpTexture")
  35599. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  35600. __decorate([
  35601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35602. ], StandardMaterial.prototype, "bumpTexture", void 0);
  35603. __decorate([
  35604. BABYLON.serializeAsTexture("lightmapTexture")
  35605. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  35606. __decorate([
  35607. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35608. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  35609. __decorate([
  35610. BABYLON.serializeAsTexture("refractionTexture")
  35611. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  35612. __decorate([
  35613. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35614. ], StandardMaterial.prototype, "refractionTexture", void 0);
  35615. __decorate([
  35616. BABYLON.serializeAsColor3("ambient")
  35617. ], StandardMaterial.prototype, "ambientColor", void 0);
  35618. __decorate([
  35619. BABYLON.serializeAsColor3("diffuse")
  35620. ], StandardMaterial.prototype, "diffuseColor", void 0);
  35621. __decorate([
  35622. BABYLON.serializeAsColor3("specular")
  35623. ], StandardMaterial.prototype, "specularColor", void 0);
  35624. __decorate([
  35625. BABYLON.serializeAsColor3("emissive")
  35626. ], StandardMaterial.prototype, "emissiveColor", void 0);
  35627. __decorate([
  35628. BABYLON.serialize()
  35629. ], StandardMaterial.prototype, "specularPower", void 0);
  35630. __decorate([
  35631. BABYLON.serialize("useAlphaFromDiffuseTexture")
  35632. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  35633. __decorate([
  35634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35635. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  35636. __decorate([
  35637. BABYLON.serialize("useEmissiveAsIllumination")
  35638. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  35639. __decorate([
  35640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35641. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  35642. __decorate([
  35643. BABYLON.serialize("linkEmissiveWithDiffuse")
  35644. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  35645. __decorate([
  35646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35647. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  35648. __decorate([
  35649. BABYLON.serialize("useSpecularOverAlpha")
  35650. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  35651. __decorate([
  35652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35653. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  35654. __decorate([
  35655. BABYLON.serialize("useReflectionOverAlpha")
  35656. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  35657. __decorate([
  35658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35659. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  35660. __decorate([
  35661. BABYLON.serialize("disableLighting")
  35662. ], StandardMaterial.prototype, "_disableLighting", void 0);
  35663. __decorate([
  35664. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35665. ], StandardMaterial.prototype, "disableLighting", void 0);
  35666. __decorate([
  35667. BABYLON.serialize("useParallax")
  35668. ], StandardMaterial.prototype, "_useParallax", void 0);
  35669. __decorate([
  35670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35671. ], StandardMaterial.prototype, "useParallax", void 0);
  35672. __decorate([
  35673. BABYLON.serialize("useParallaxOcclusion")
  35674. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  35675. __decorate([
  35676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35677. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  35678. __decorate([
  35679. BABYLON.serialize()
  35680. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  35681. __decorate([
  35682. BABYLON.serialize("roughness")
  35683. ], StandardMaterial.prototype, "_roughness", void 0);
  35684. __decorate([
  35685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35686. ], StandardMaterial.prototype, "roughness", void 0);
  35687. __decorate([
  35688. BABYLON.serialize()
  35689. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  35690. __decorate([
  35691. BABYLON.serialize()
  35692. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  35693. __decorate([
  35694. BABYLON.serialize("useLightmapAsShadowmap")
  35695. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  35696. __decorate([
  35697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35698. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  35699. __decorate([
  35700. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  35701. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  35702. __decorate([
  35703. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35704. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  35705. __decorate([
  35706. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  35707. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  35708. __decorate([
  35709. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35710. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  35711. __decorate([
  35712. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  35713. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  35714. __decorate([
  35715. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35716. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  35717. __decorate([
  35718. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  35719. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  35720. __decorate([
  35721. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35722. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  35723. __decorate([
  35724. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  35725. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  35726. __decorate([
  35727. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35728. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  35729. __decorate([
  35730. BABYLON.serialize("useReflectionFresnelFromSpecular")
  35731. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  35732. __decorate([
  35733. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35734. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  35735. __decorate([
  35736. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  35737. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  35738. __decorate([
  35739. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35740. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  35741. __decorate([
  35742. BABYLON.serialize("maxSimultaneousLights")
  35743. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  35744. __decorate([
  35745. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35746. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  35747. __decorate([
  35748. BABYLON.serialize("invertNormalMapX")
  35749. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  35750. __decorate([
  35751. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35752. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  35753. __decorate([
  35754. BABYLON.serialize("invertNormalMapY")
  35755. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  35756. __decorate([
  35757. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35758. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  35759. __decorate([
  35760. BABYLON.serialize("twoSidedLighting")
  35761. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  35762. __decorate([
  35763. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35764. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  35765. __decorate([
  35766. BABYLON.serialize()
  35767. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  35768. return StandardMaterial;
  35769. }(BABYLON.PushMaterial));
  35770. BABYLON.StandardMaterial = StandardMaterial;
  35771. })(BABYLON || (BABYLON = {}));
  35772. //# sourceMappingURL=babylon.standardMaterial.js.map
  35773. var BABYLON;
  35774. (function (BABYLON) {
  35775. var PBRMaterialDefines = /** @class */ (function (_super) {
  35776. __extends(PBRMaterialDefines, _super);
  35777. function PBRMaterialDefines() {
  35778. var _this = _super.call(this) || this;
  35779. _this.PBR = true;
  35780. _this.MAINUV1 = false;
  35781. _this.MAINUV2 = false;
  35782. _this.UV1 = false;
  35783. _this.UV2 = false;
  35784. _this.ALBEDO = false;
  35785. _this.ALBEDODIRECTUV = 0;
  35786. _this.VERTEXCOLOR = false;
  35787. _this.AMBIENT = false;
  35788. _this.AMBIENTDIRECTUV = 0;
  35789. _this.AMBIENTINGRAYSCALE = false;
  35790. _this.OPACITY = false;
  35791. _this.VERTEXALPHA = false;
  35792. _this.OPACITYDIRECTUV = 0;
  35793. _this.OPACITYRGB = false;
  35794. _this.ALPHATEST = false;
  35795. _this.DEPTHPREPASS = false;
  35796. _this.ALPHABLEND = false;
  35797. _this.ALPHAFROMALBEDO = false;
  35798. _this.ALPHATESTVALUE = 0.5;
  35799. _this.SPECULAROVERALPHA = false;
  35800. _this.RADIANCEOVERALPHA = false;
  35801. _this.ALPHAFRESNEL = false;
  35802. _this.LINEARALPHAFRESNEL = false;
  35803. _this.PREMULTIPLYALPHA = false;
  35804. _this.EMISSIVE = false;
  35805. _this.EMISSIVEDIRECTUV = 0;
  35806. _this.REFLECTIVITY = false;
  35807. _this.REFLECTIVITYDIRECTUV = 0;
  35808. _this.SPECULARTERM = false;
  35809. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  35810. _this.MICROSURFACEAUTOMATIC = false;
  35811. _this.LODBASEDMICROSFURACE = false;
  35812. _this.MICROSURFACEMAP = false;
  35813. _this.MICROSURFACEMAPDIRECTUV = 0;
  35814. _this.METALLICWORKFLOW = false;
  35815. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  35816. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  35817. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  35818. _this.AOSTOREINMETALMAPRED = false;
  35819. _this.ENVIRONMENTBRDF = false;
  35820. _this.NORMAL = false;
  35821. _this.TANGENT = false;
  35822. _this.BUMP = false;
  35823. _this.BUMPDIRECTUV = 0;
  35824. _this.PARALLAX = false;
  35825. _this.PARALLAXOCCLUSION = false;
  35826. _this.NORMALXYSCALE = true;
  35827. _this.LIGHTMAP = false;
  35828. _this.LIGHTMAPDIRECTUV = 0;
  35829. _this.USELIGHTMAPASSHADOWMAP = false;
  35830. _this.REFLECTION = false;
  35831. _this.REFLECTIONMAP_3D = false;
  35832. _this.REFLECTIONMAP_SPHERICAL = false;
  35833. _this.REFLECTIONMAP_PLANAR = false;
  35834. _this.REFLECTIONMAP_CUBIC = false;
  35835. _this.REFLECTIONMAP_PROJECTION = false;
  35836. _this.REFLECTIONMAP_SKYBOX = false;
  35837. _this.REFLECTIONMAP_EXPLICIT = false;
  35838. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  35839. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  35840. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  35841. _this.INVERTCUBICMAP = false;
  35842. _this.USESPHERICALFROMREFLECTIONMAP = false;
  35843. _this.USESPHERICALINVERTEX = false;
  35844. _this.REFLECTIONMAP_OPPOSITEZ = false;
  35845. _this.LODINREFLECTIONALPHA = false;
  35846. _this.GAMMAREFLECTION = false;
  35847. _this.RADIANCEOCCLUSION = false;
  35848. _this.HORIZONOCCLUSION = false;
  35849. _this.REFRACTION = false;
  35850. _this.REFRACTIONMAP_3D = false;
  35851. _this.REFRACTIONMAP_OPPOSITEZ = false;
  35852. _this.LODINREFRACTIONALPHA = false;
  35853. _this.GAMMAREFRACTION = false;
  35854. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  35855. _this.INSTANCES = false;
  35856. _this.NUM_BONE_INFLUENCERS = 0;
  35857. _this.BonesPerMesh = 0;
  35858. _this.NONUNIFORMSCALING = false;
  35859. _this.MORPHTARGETS = false;
  35860. _this.MORPHTARGETS_NORMAL = false;
  35861. _this.MORPHTARGETS_TANGENT = false;
  35862. _this.NUM_MORPH_INFLUENCERS = 0;
  35863. _this.IMAGEPROCESSING = false;
  35864. _this.VIGNETTE = false;
  35865. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  35866. _this.VIGNETTEBLENDMODEOPAQUE = false;
  35867. _this.TONEMAPPING = false;
  35868. _this.CONTRAST = false;
  35869. _this.COLORCURVES = false;
  35870. _this.COLORGRADING = false;
  35871. _this.COLORGRADING3D = false;
  35872. _this.SAMPLER3DGREENDEPTH = false;
  35873. _this.SAMPLER3DBGRMAP = false;
  35874. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  35875. _this.EXPOSURE = false;
  35876. _this.USEPHYSICALLIGHTFALLOFF = false;
  35877. _this.TWOSIDEDLIGHTING = false;
  35878. _this.SHADOWFLOAT = false;
  35879. _this.CLIPPLANE = false;
  35880. _this.POINTSIZE = false;
  35881. _this.FOG = false;
  35882. _this.LOGARITHMICDEPTH = false;
  35883. _this.FORCENORMALFORWARD = false;
  35884. _this.rebuild();
  35885. return _this;
  35886. }
  35887. PBRMaterialDefines.prototype.reset = function () {
  35888. _super.prototype.reset.call(this);
  35889. this.ALPHATESTVALUE = 0.5;
  35890. this.PBR = true;
  35891. };
  35892. return PBRMaterialDefines;
  35893. }(BABYLON.MaterialDefines));
  35894. /**
  35895. * The Physically based material base class of BJS.
  35896. *
  35897. * This offers the main features of a standard PBR material.
  35898. * For more information, please refer to the documentation :
  35899. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  35900. */
  35901. var PBRBaseMaterial = /** @class */ (function (_super) {
  35902. __extends(PBRBaseMaterial, _super);
  35903. /**
  35904. * Instantiates a new PBRMaterial instance.
  35905. *
  35906. * @param name The material name
  35907. * @param scene The scene the material will be use in.
  35908. */
  35909. function PBRBaseMaterial(name, scene) {
  35910. var _this = _super.call(this, name, scene) || this;
  35911. /**
  35912. * Intensity of the direct lights e.g. the four lights available in your scene.
  35913. * This impacts both the direct diffuse and specular highlights.
  35914. */
  35915. _this._directIntensity = 1.0;
  35916. /**
  35917. * Intensity of the emissive part of the material.
  35918. * This helps controlling the emissive effect without modifying the emissive color.
  35919. */
  35920. _this._emissiveIntensity = 1.0;
  35921. /**
  35922. * Intensity of the environment e.g. how much the environment will light the object
  35923. * either through harmonics for rough material or through the refelction for shiny ones.
  35924. */
  35925. _this._environmentIntensity = 1.0;
  35926. /**
  35927. * This is a special control allowing the reduction of the specular highlights coming from the
  35928. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  35929. */
  35930. _this._specularIntensity = 1.0;
  35931. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  35932. /**
  35933. * Debug Control allowing disabling the bump map on this material.
  35934. */
  35935. _this._disableBumpMap = false;
  35936. /**
  35937. * AKA Occlusion Texture Intensity in other nomenclature.
  35938. */
  35939. _this._ambientTextureStrength = 1.0;
  35940. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  35941. /**
  35942. * AKA Diffuse Color in other nomenclature.
  35943. */
  35944. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  35945. /**
  35946. * AKA Specular Color in other nomenclature.
  35947. */
  35948. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  35949. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  35950. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  35951. /**
  35952. * AKA Glossiness in other nomenclature.
  35953. */
  35954. _this._microSurface = 0.9;
  35955. /**
  35956. * source material index of refraction (IOR)' / 'destination material IOR.
  35957. */
  35958. _this._indexOfRefraction = 0.66;
  35959. /**
  35960. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  35961. */
  35962. _this._invertRefractionY = false;
  35963. /**
  35964. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  35965. * Materials half opaque for instance using refraction could benefit from this control.
  35966. */
  35967. _this._linkRefractionWithTransparency = false;
  35968. _this._useLightmapAsShadowmap = false;
  35969. /**
  35970. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  35971. * makes the reflect vector face the model (under horizon).
  35972. */
  35973. _this._useHorizonOcclusion = true;
  35974. /**
  35975. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  35976. * too much the area relying on ambient texture to define their ambient occlusion.
  35977. */
  35978. _this._useRadianceOcclusion = true;
  35979. /**
  35980. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  35981. */
  35982. _this._useAlphaFromAlbedoTexture = false;
  35983. /**
  35984. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  35985. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  35986. */
  35987. _this._useSpecularOverAlpha = true;
  35988. /**
  35989. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  35990. */
  35991. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  35992. /**
  35993. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  35994. */
  35995. _this._useRoughnessFromMetallicTextureAlpha = true;
  35996. /**
  35997. * Specifies if the metallic texture contains the roughness information in its green channel.
  35998. */
  35999. _this._useRoughnessFromMetallicTextureGreen = false;
  36000. /**
  36001. * Specifies if the metallic texture contains the metallness information in its blue channel.
  36002. */
  36003. _this._useMetallnessFromMetallicTextureBlue = false;
  36004. /**
  36005. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  36006. */
  36007. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  36008. /**
  36009. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  36010. */
  36011. _this._useAmbientInGrayScale = false;
  36012. /**
  36013. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  36014. * The material will try to infer what glossiness each pixel should be.
  36015. */
  36016. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  36017. /**
  36018. * BJS is using an harcoded light falloff based on a manually sets up range.
  36019. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  36020. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  36021. */
  36022. _this._usePhysicalLightFalloff = true;
  36023. /**
  36024. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  36025. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  36026. */
  36027. _this._useRadianceOverAlpha = true;
  36028. /**
  36029. * Allows using the bump map in parallax mode.
  36030. */
  36031. _this._useParallax = false;
  36032. /**
  36033. * Allows using the bump map in parallax occlusion mode.
  36034. */
  36035. _this._useParallaxOcclusion = false;
  36036. /**
  36037. * Controls the scale bias of the parallax mode.
  36038. */
  36039. _this._parallaxScaleBias = 0.05;
  36040. /**
  36041. * If sets to true, disables all the lights affecting the material.
  36042. */
  36043. _this._disableLighting = false;
  36044. /**
  36045. * Number of Simultaneous lights allowed on the material.
  36046. */
  36047. _this._maxSimultaneousLights = 4;
  36048. /**
  36049. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  36050. */
  36051. _this._invertNormalMapX = false;
  36052. /**
  36053. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  36054. */
  36055. _this._invertNormalMapY = false;
  36056. /**
  36057. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36058. */
  36059. _this._twoSidedLighting = false;
  36060. /**
  36061. * Defines the alpha limits in alpha test mode.
  36062. */
  36063. _this._alphaCutOff = 0.4;
  36064. /**
  36065. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  36066. */
  36067. _this._forceAlphaTest = false;
  36068. /**
  36069. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36070. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  36071. */
  36072. _this._useAlphaFresnel = false;
  36073. /**
  36074. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36075. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  36076. */
  36077. _this._useLinearAlphaFresnel = false;
  36078. /**
  36079. * The transparency mode of the material.
  36080. */
  36081. _this._transparencyMode = null;
  36082. /**
  36083. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  36084. * from cos thetav and roughness:
  36085. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  36086. */
  36087. _this._environmentBRDFTexture = null;
  36088. /**
  36089. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  36090. */
  36091. _this._forceIrradianceInFragment = false;
  36092. /**
  36093. * Force normal to face away from face.
  36094. */
  36095. _this._forceNormalForward = false;
  36096. _this._renderTargets = new BABYLON.SmartArray(16);
  36097. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  36098. // Setup the default processing configuration to the scene.
  36099. _this._attachImageProcessingConfiguration(null);
  36100. _this.getRenderTargetTextures = function () {
  36101. _this._renderTargets.reset();
  36102. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  36103. _this._renderTargets.push(_this._reflectionTexture);
  36104. }
  36105. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  36106. _this._renderTargets.push(_this._refractionTexture);
  36107. }
  36108. return _this._renderTargets;
  36109. };
  36110. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  36111. return _this;
  36112. }
  36113. /**
  36114. * Attaches a new image processing configuration to the PBR Material.
  36115. * @param configuration
  36116. */
  36117. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  36118. var _this = this;
  36119. if (configuration === this._imageProcessingConfiguration) {
  36120. return;
  36121. }
  36122. // Detaches observer.
  36123. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36124. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36125. }
  36126. // Pick the scene configuration if needed.
  36127. if (!configuration) {
  36128. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  36129. }
  36130. else {
  36131. this._imageProcessingConfiguration = configuration;
  36132. }
  36133. // Attaches observer.
  36134. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  36135. _this._markAllSubMeshesAsImageProcessingDirty();
  36136. });
  36137. };
  36138. PBRBaseMaterial.prototype.getClassName = function () {
  36139. return "PBRBaseMaterial";
  36140. };
  36141. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  36142. get: function () {
  36143. return this._useLogarithmicDepth;
  36144. },
  36145. set: function (value) {
  36146. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  36147. },
  36148. enumerable: true,
  36149. configurable: true
  36150. });
  36151. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  36152. /**
  36153. * Gets the current transparency mode.
  36154. */
  36155. get: function () {
  36156. return this._transparencyMode;
  36157. },
  36158. /**
  36159. * Sets the transparency mode of the material.
  36160. */
  36161. set: function (value) {
  36162. if (this._transparencyMode === value) {
  36163. return;
  36164. }
  36165. this._transparencyMode = value;
  36166. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  36167. this._markAllSubMeshesAsTexturesDirty();
  36168. },
  36169. enumerable: true,
  36170. configurable: true
  36171. });
  36172. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  36173. /**
  36174. * Returns true if alpha blending should be disabled.
  36175. */
  36176. get: function () {
  36177. return (this._linkRefractionWithTransparency ||
  36178. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  36179. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  36180. },
  36181. enumerable: true,
  36182. configurable: true
  36183. });
  36184. /**
  36185. * Specifies whether or not this material should be rendered in alpha blend mode.
  36186. */
  36187. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  36188. if (this._disableAlphaBlending) {
  36189. return false;
  36190. }
  36191. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  36192. };
  36193. /**
  36194. * Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
  36195. */
  36196. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  36197. if (this._disableAlphaBlending) {
  36198. return false;
  36199. }
  36200. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  36201. };
  36202. /**
  36203. * Specifies whether or not this material should be rendered in alpha test mode.
  36204. */
  36205. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  36206. if (this._forceAlphaTest) {
  36207. return true;
  36208. }
  36209. if (this._linkRefractionWithTransparency) {
  36210. return false;
  36211. }
  36212. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  36213. };
  36214. /**
  36215. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  36216. */
  36217. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  36218. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  36219. };
  36220. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  36221. return this._albedoTexture;
  36222. };
  36223. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36224. var _this = this;
  36225. if (subMesh.effect && this.isFrozen) {
  36226. if (this._wasPreviouslyReady) {
  36227. return true;
  36228. }
  36229. }
  36230. if (!subMesh._materialDefines) {
  36231. subMesh._materialDefines = new PBRMaterialDefines();
  36232. }
  36233. var scene = this.getScene();
  36234. var defines = subMesh._materialDefines;
  36235. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  36236. if (defines._renderId === scene.getRenderId()) {
  36237. return true;
  36238. }
  36239. }
  36240. var engine = scene.getEngine();
  36241. // Lights
  36242. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  36243. defines._needNormals = true;
  36244. // Textures
  36245. if (defines._areTexturesDirty) {
  36246. defines._needUVs = false;
  36247. if (scene.texturesEnabled) {
  36248. if (scene.getEngine().getCaps().textureLOD) {
  36249. defines.LODBASEDMICROSFURACE = true;
  36250. }
  36251. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36252. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  36253. return false;
  36254. }
  36255. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  36256. }
  36257. else {
  36258. defines.ALBEDO = false;
  36259. }
  36260. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  36261. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  36262. return false;
  36263. }
  36264. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  36265. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  36266. }
  36267. else {
  36268. defines.AMBIENT = false;
  36269. }
  36270. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  36271. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  36272. return false;
  36273. }
  36274. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  36275. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  36276. }
  36277. else {
  36278. defines.OPACITY = false;
  36279. }
  36280. var reflectionTexture = this._getReflectionTexture();
  36281. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36282. if (!reflectionTexture.isReadyOrNotBlocking()) {
  36283. return false;
  36284. }
  36285. defines.REFLECTION = true;
  36286. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  36287. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  36288. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  36289. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  36290. defines.INVERTCUBICMAP = true;
  36291. }
  36292. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  36293. switch (reflectionTexture.coordinatesMode) {
  36294. case BABYLON.Texture.CUBIC_MODE:
  36295. case BABYLON.Texture.INVCUBIC_MODE:
  36296. defines.REFLECTIONMAP_CUBIC = true;
  36297. break;
  36298. case BABYLON.Texture.EXPLICIT_MODE:
  36299. defines.REFLECTIONMAP_EXPLICIT = true;
  36300. break;
  36301. case BABYLON.Texture.PLANAR_MODE:
  36302. defines.REFLECTIONMAP_PLANAR = true;
  36303. break;
  36304. case BABYLON.Texture.PROJECTION_MODE:
  36305. defines.REFLECTIONMAP_PROJECTION = true;
  36306. break;
  36307. case BABYLON.Texture.SKYBOX_MODE:
  36308. defines.REFLECTIONMAP_SKYBOX = true;
  36309. break;
  36310. case BABYLON.Texture.SPHERICAL_MODE:
  36311. defines.REFLECTIONMAP_SPHERICAL = true;
  36312. break;
  36313. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  36314. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  36315. break;
  36316. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  36317. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  36318. break;
  36319. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  36320. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  36321. break;
  36322. }
  36323. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  36324. if (reflectionTexture.sphericalPolynomial) {
  36325. defines.USESPHERICALFROMREFLECTIONMAP = true;
  36326. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  36327. defines.USESPHERICALINVERTEX = false;
  36328. }
  36329. else {
  36330. defines.USESPHERICALINVERTEX = true;
  36331. }
  36332. }
  36333. }
  36334. }
  36335. else {
  36336. defines.REFLECTION = false;
  36337. defines.REFLECTIONMAP_3D = false;
  36338. defines.REFLECTIONMAP_SPHERICAL = false;
  36339. defines.REFLECTIONMAP_PLANAR = false;
  36340. defines.REFLECTIONMAP_CUBIC = false;
  36341. defines.REFLECTIONMAP_PROJECTION = false;
  36342. defines.REFLECTIONMAP_SKYBOX = false;
  36343. defines.REFLECTIONMAP_EXPLICIT = false;
  36344. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36345. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36346. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36347. defines.INVERTCUBICMAP = false;
  36348. defines.USESPHERICALFROMREFLECTIONMAP = false;
  36349. defines.USESPHERICALINVERTEX = false;
  36350. defines.REFLECTIONMAP_OPPOSITEZ = false;
  36351. defines.LODINREFLECTIONALPHA = false;
  36352. defines.GAMMAREFLECTION = false;
  36353. }
  36354. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  36355. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  36356. return false;
  36357. }
  36358. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  36359. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  36360. }
  36361. else {
  36362. defines.LIGHTMAP = false;
  36363. }
  36364. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  36365. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  36366. return false;
  36367. }
  36368. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  36369. }
  36370. else {
  36371. defines.EMISSIVE = false;
  36372. }
  36373. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  36374. if (this._metallicTexture) {
  36375. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  36376. return false;
  36377. }
  36378. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  36379. defines.METALLICWORKFLOW = true;
  36380. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  36381. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  36382. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  36383. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  36384. }
  36385. else if (this._reflectivityTexture) {
  36386. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  36387. return false;
  36388. }
  36389. defines.METALLICWORKFLOW = false;
  36390. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  36391. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  36392. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  36393. }
  36394. else {
  36395. defines.METALLICWORKFLOW = false;
  36396. defines.REFLECTIVITY = false;
  36397. }
  36398. if (this._microSurfaceTexture) {
  36399. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  36400. return false;
  36401. }
  36402. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  36403. }
  36404. else {
  36405. defines.MICROSURFACEMAP = false;
  36406. }
  36407. }
  36408. else {
  36409. defines.REFLECTIVITY = false;
  36410. defines.MICROSURFACEMAP = false;
  36411. }
  36412. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  36413. // Bump texure can not be none blocking.
  36414. if (!this._bumpTexture.isReady()) {
  36415. return false;
  36416. }
  36417. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  36418. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36419. defines.PARALLAX = true;
  36420. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  36421. }
  36422. else {
  36423. defines.PARALLAX = false;
  36424. }
  36425. }
  36426. else {
  36427. defines.BUMP = false;
  36428. }
  36429. var refractionTexture = this._getRefractionTexture();
  36430. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  36431. if (!refractionTexture.isReadyOrNotBlocking()) {
  36432. return false;
  36433. }
  36434. defines.REFRACTION = true;
  36435. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  36436. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  36437. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  36438. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  36439. if (this._linkRefractionWithTransparency) {
  36440. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  36441. }
  36442. }
  36443. else {
  36444. defines.REFRACTION = false;
  36445. }
  36446. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36447. // This is blocking.
  36448. if (!this._environmentBRDFTexture.isReady()) {
  36449. return false;
  36450. }
  36451. defines.ENVIRONMENTBRDF = true;
  36452. }
  36453. else {
  36454. defines.ENVIRONMENTBRDF = false;
  36455. }
  36456. if (this._shouldUseAlphaFromAlbedoTexture()) {
  36457. defines.ALPHAFROMALBEDO = true;
  36458. }
  36459. else {
  36460. defines.ALPHAFROMALBEDO = false;
  36461. }
  36462. }
  36463. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  36464. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  36465. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  36466. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  36467. defines.METALLICWORKFLOW = true;
  36468. }
  36469. else {
  36470. defines.METALLICWORKFLOW = false;
  36471. }
  36472. if (!this.backFaceCulling && this._twoSidedLighting) {
  36473. defines.TWOSIDEDLIGHTING = true;
  36474. }
  36475. else {
  36476. defines.TWOSIDEDLIGHTING = false;
  36477. }
  36478. defines.ALPHATESTVALUE = this._alphaCutOff;
  36479. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  36480. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  36481. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  36482. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  36483. }
  36484. if (defines._areImageProcessingDirty) {
  36485. if (!this._imageProcessingConfiguration.isReady()) {
  36486. return false;
  36487. }
  36488. this._imageProcessingConfiguration.prepareDefines(defines);
  36489. }
  36490. defines.FORCENORMALFORWARD = this._forceNormalForward;
  36491. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  36492. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  36493. // Misc.
  36494. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  36495. // Values that need to be evaluated on every frame
  36496. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._forceAlphaTest);
  36497. // Attribs
  36498. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE) && mesh) {
  36499. var bufferMesh = null;
  36500. if (mesh instanceof BABYLON.InstancedMesh) {
  36501. bufferMesh = mesh.sourceMesh;
  36502. }
  36503. else if (mesh instanceof BABYLON.Mesh) {
  36504. bufferMesh = mesh;
  36505. }
  36506. if (bufferMesh) {
  36507. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36508. // If the first normal's components is the zero vector in one of the submeshes, we have invalid normals
  36509. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  36510. var normals = normalVertexBuffer.getData();
  36511. var vertexBufferOffset = normalVertexBuffer.getOffset();
  36512. var strideSize = normalVertexBuffer.getStrideSize();
  36513. var offset = vertexBufferOffset + subMesh.indexStart * strideSize;
  36514. if (normals[offset] === 0 && normals[offset + 1] === 0 && normals[offset + 2] === 0) {
  36515. defines.NORMAL = false;
  36516. }
  36517. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36518. // If the first tangent's components is the zero vector in one of the submeshes, we have invalid tangents
  36519. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  36520. var tangents = tangentVertexBuffer.getData();
  36521. var vertexBufferOffset_1 = tangentVertexBuffer.getOffset();
  36522. var strideSize_1 = tangentVertexBuffer.getStrideSize();
  36523. var offset_1 = vertexBufferOffset_1 + subMesh.indexStart * strideSize_1;
  36524. if (tangents[offset_1] === 0 && tangents[offset_1 + 1] === 0 && tangents[offset_1 + 2] === 0) {
  36525. defines.TANGENT = false;
  36526. }
  36527. }
  36528. }
  36529. else {
  36530. if (!scene.getEngine().getCaps().standardDerivatives) {
  36531. bufferMesh.createNormals(true);
  36532. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  36533. }
  36534. }
  36535. }
  36536. }
  36537. // Get correct effect
  36538. if (defines.isDirty) {
  36539. defines.markAsProcessed();
  36540. scene.resetCachedMaterial();
  36541. // Fallbacks
  36542. var fallbacks = new BABYLON.EffectFallbacks();
  36543. var fallbackRank = 0;
  36544. if (defines.USESPHERICALINVERTEX) {
  36545. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  36546. }
  36547. if (defines.FOG) {
  36548. fallbacks.addFallback(fallbackRank, "FOG");
  36549. }
  36550. if (defines.POINTSIZE) {
  36551. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  36552. }
  36553. if (defines.LOGARITHMICDEPTH) {
  36554. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  36555. }
  36556. if (defines.PARALLAX) {
  36557. fallbacks.addFallback(fallbackRank, "PARALLAX");
  36558. }
  36559. if (defines.PARALLAXOCCLUSION) {
  36560. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  36561. }
  36562. if (defines.ENVIRONMENTBRDF) {
  36563. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  36564. }
  36565. if (defines.TANGENT) {
  36566. fallbacks.addFallback(fallbackRank++, "TANGENT");
  36567. }
  36568. if (defines.BUMP) {
  36569. fallbacks.addFallback(fallbackRank++, "BUMP");
  36570. }
  36571. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  36572. if (defines.SPECULARTERM) {
  36573. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  36574. }
  36575. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  36576. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  36577. }
  36578. if (defines.LIGHTMAP) {
  36579. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  36580. }
  36581. if (defines.NORMAL) {
  36582. fallbacks.addFallback(fallbackRank++, "NORMAL");
  36583. }
  36584. if (defines.AMBIENT) {
  36585. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  36586. }
  36587. if (defines.EMISSIVE) {
  36588. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  36589. }
  36590. if (defines.VERTEXCOLOR) {
  36591. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  36592. }
  36593. if (defines.NUM_BONE_INFLUENCERS > 0) {
  36594. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  36595. }
  36596. if (defines.MORPHTARGETS) {
  36597. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  36598. }
  36599. //Attributes
  36600. var attribs = [BABYLON.VertexBuffer.PositionKind];
  36601. if (defines.NORMAL) {
  36602. attribs.push(BABYLON.VertexBuffer.NormalKind);
  36603. }
  36604. if (defines.TANGENT) {
  36605. attribs.push(BABYLON.VertexBuffer.TangentKind);
  36606. }
  36607. if (defines.UV1) {
  36608. attribs.push(BABYLON.VertexBuffer.UVKind);
  36609. }
  36610. if (defines.UV2) {
  36611. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  36612. }
  36613. if (defines.VERTEXCOLOR) {
  36614. attribs.push(BABYLON.VertexBuffer.ColorKind);
  36615. }
  36616. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  36617. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  36618. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  36619. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  36620. "vFogInfos", "vFogColor", "pointSize",
  36621. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  36622. "mBones",
  36623. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  36624. "vLightingIntensity",
  36625. "logarithmicDepthConstant",
  36626. "vSphericalX", "vSphericalY", "vSphericalZ",
  36627. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  36628. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  36629. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  36630. "vTangentSpaceParams"
  36631. ];
  36632. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  36633. "bumpSampler", "lightmapSampler", "opacitySampler",
  36634. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  36635. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  36636. "microSurfaceSampler", "environmentBrdfSampler"];
  36637. var uniformBuffers = ["Material", "Scene"];
  36638. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  36639. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  36640. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  36641. uniformsNames: uniforms,
  36642. uniformBuffersNames: uniformBuffers,
  36643. samplers: samplers,
  36644. defines: defines,
  36645. maxSimultaneousLights: this._maxSimultaneousLights
  36646. });
  36647. var onCompiled = function (effect) {
  36648. if (_this.onCompiled) {
  36649. _this.onCompiled(effect);
  36650. }
  36651. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  36652. };
  36653. var join = defines.toString();
  36654. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  36655. attributes: attribs,
  36656. uniformsNames: uniforms,
  36657. uniformBuffersNames: uniformBuffers,
  36658. samplers: samplers,
  36659. defines: join,
  36660. fallbacks: fallbacks,
  36661. onCompiled: onCompiled,
  36662. onError: this.onError,
  36663. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  36664. }, engine), defines);
  36665. this.buildUniformLayout();
  36666. }
  36667. if (!subMesh.effect || !subMesh.effect.isReady()) {
  36668. return false;
  36669. }
  36670. defines._renderId = scene.getRenderId();
  36671. this._wasPreviouslyReady = true;
  36672. return true;
  36673. };
  36674. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  36675. // Order is important !
  36676. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  36677. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  36678. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  36679. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  36680. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  36681. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  36682. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  36683. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  36684. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  36685. this._uniformBuffer.addUniform("vBumpInfos", 3);
  36686. this._uniformBuffer.addUniform("albedoMatrix", 16);
  36687. this._uniformBuffer.addUniform("ambientMatrix", 16);
  36688. this._uniformBuffer.addUniform("opacityMatrix", 16);
  36689. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  36690. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  36691. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  36692. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  36693. this._uniformBuffer.addUniform("bumpMatrix", 16);
  36694. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  36695. this._uniformBuffer.addUniform("refractionMatrix", 16);
  36696. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  36697. this._uniformBuffer.addUniform("vReflectionColor", 3);
  36698. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  36699. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  36700. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  36701. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  36702. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  36703. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  36704. this._uniformBuffer.addUniform("pointSize", 1);
  36705. this._uniformBuffer.create();
  36706. };
  36707. PBRBaseMaterial.prototype.unbind = function () {
  36708. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  36709. this._uniformBuffer.setTexture("reflectionSampler", null);
  36710. }
  36711. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  36712. this._uniformBuffer.setTexture("refractionSampler", null);
  36713. }
  36714. _super.prototype.unbind.call(this);
  36715. };
  36716. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  36717. this._activeEffect.setMatrix("world", world);
  36718. };
  36719. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  36720. var scene = this.getScene();
  36721. var defines = subMesh._materialDefines;
  36722. if (!defines) {
  36723. return;
  36724. }
  36725. var effect = subMesh.effect;
  36726. if (!effect) {
  36727. return;
  36728. }
  36729. this._activeEffect = effect;
  36730. // Matrices
  36731. this.bindOnlyWorldMatrix(world);
  36732. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  36733. // Bones
  36734. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  36735. var reflectionTexture = null;
  36736. if (mustRebind) {
  36737. this._uniformBuffer.bindToEffect(effect, "Material");
  36738. this.bindViewProjection(effect);
  36739. reflectionTexture = this._getReflectionTexture();
  36740. var refractionTexture = this._getRefractionTexture();
  36741. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  36742. // Texture uniforms
  36743. if (scene.texturesEnabled) {
  36744. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36745. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  36746. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  36747. }
  36748. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  36749. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  36750. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  36751. }
  36752. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  36753. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  36754. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  36755. }
  36756. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36757. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  36758. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  36759. var polynomials = reflectionTexture.sphericalPolynomial;
  36760. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  36761. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  36762. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  36763. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  36764. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  36765. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  36766. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  36767. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  36768. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  36769. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  36770. }
  36771. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  36772. }
  36773. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  36774. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  36775. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  36776. }
  36777. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  36778. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  36779. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  36780. }
  36781. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  36782. if (this._metallicTexture) {
  36783. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  36784. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  36785. }
  36786. else if (this._reflectivityTexture) {
  36787. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  36788. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  36789. }
  36790. if (this._microSurfaceTexture) {
  36791. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  36792. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  36793. }
  36794. }
  36795. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  36796. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  36797. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  36798. if (scene._mirroredCameraPosition) {
  36799. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  36800. }
  36801. else {
  36802. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  36803. }
  36804. }
  36805. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  36806. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  36807. var depth = 1.0;
  36808. if (!refractionTexture.isCube) {
  36809. if (refractionTexture.depth) {
  36810. depth = refractionTexture.depth;
  36811. }
  36812. }
  36813. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  36814. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  36815. }
  36816. }
  36817. // Point size
  36818. if (this.pointsCloud) {
  36819. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  36820. }
  36821. // Colors
  36822. if (defines.METALLICWORKFLOW) {
  36823. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  36824. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  36825. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  36826. }
  36827. else {
  36828. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  36829. }
  36830. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  36831. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  36832. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  36833. // Misc
  36834. this._lightingInfos.x = this._directIntensity;
  36835. this._lightingInfos.y = this._emissiveIntensity;
  36836. this._lightingInfos.z = this._environmentIntensity;
  36837. this._lightingInfos.w = this._specularIntensity;
  36838. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  36839. }
  36840. // Textures
  36841. if (scene.texturesEnabled) {
  36842. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36843. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  36844. }
  36845. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  36846. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  36847. }
  36848. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  36849. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  36850. }
  36851. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36852. if (defines.LODBASEDMICROSFURACE) {
  36853. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  36854. }
  36855. else {
  36856. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  36857. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  36858. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  36859. }
  36860. }
  36861. if (defines.ENVIRONMENTBRDF) {
  36862. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  36863. }
  36864. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  36865. if (defines.LODBASEDMICROSFURACE) {
  36866. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  36867. }
  36868. else {
  36869. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  36870. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  36871. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  36872. }
  36873. }
  36874. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  36875. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  36876. }
  36877. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  36878. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  36879. }
  36880. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  36881. if (this._metallicTexture) {
  36882. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  36883. }
  36884. else if (this._reflectivityTexture) {
  36885. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  36886. }
  36887. if (this._microSurfaceTexture) {
  36888. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  36889. }
  36890. }
  36891. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  36892. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  36893. }
  36894. }
  36895. // Clip plane
  36896. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  36897. // Colors
  36898. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  36899. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  36900. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  36901. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  36902. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  36903. }
  36904. if (mustRebind || !this.isFrozen) {
  36905. // Lights
  36906. if (scene.lightsEnabled && !this._disableLighting) {
  36907. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  36908. }
  36909. // View
  36910. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  36911. this.bindView(effect);
  36912. }
  36913. // Fog
  36914. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  36915. // Morph targets
  36916. if (defines.NUM_MORPH_INFLUENCERS) {
  36917. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  36918. }
  36919. // image processing
  36920. this._imageProcessingConfiguration.bind(this._activeEffect);
  36921. // Log. depth
  36922. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  36923. }
  36924. this._uniformBuffer.update();
  36925. this._afterBind(mesh);
  36926. };
  36927. PBRBaseMaterial.prototype.getAnimatables = function () {
  36928. var results = [];
  36929. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  36930. results.push(this._albedoTexture);
  36931. }
  36932. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  36933. results.push(this._ambientTexture);
  36934. }
  36935. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  36936. results.push(this._opacityTexture);
  36937. }
  36938. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  36939. results.push(this._reflectionTexture);
  36940. }
  36941. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  36942. results.push(this._emissiveTexture);
  36943. }
  36944. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  36945. results.push(this._metallicTexture);
  36946. }
  36947. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  36948. results.push(this._reflectivityTexture);
  36949. }
  36950. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  36951. results.push(this._bumpTexture);
  36952. }
  36953. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  36954. results.push(this._lightmapTexture);
  36955. }
  36956. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  36957. results.push(this._refractionTexture);
  36958. }
  36959. return results;
  36960. };
  36961. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  36962. if (this._reflectionTexture) {
  36963. return this._reflectionTexture;
  36964. }
  36965. return this.getScene().environmentTexture;
  36966. };
  36967. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  36968. if (this._refractionTexture) {
  36969. return this._refractionTexture;
  36970. }
  36971. if (this._linkRefractionWithTransparency) {
  36972. return this.getScene().environmentTexture;
  36973. }
  36974. return null;
  36975. };
  36976. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36977. if (forceDisposeTextures) {
  36978. if (this._albedoTexture) {
  36979. this._albedoTexture.dispose();
  36980. }
  36981. if (this._ambientTexture) {
  36982. this._ambientTexture.dispose();
  36983. }
  36984. if (this._opacityTexture) {
  36985. this._opacityTexture.dispose();
  36986. }
  36987. if (this._reflectionTexture) {
  36988. this._reflectionTexture.dispose();
  36989. }
  36990. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  36991. this._environmentBRDFTexture.dispose();
  36992. }
  36993. if (this._emissiveTexture) {
  36994. this._emissiveTexture.dispose();
  36995. }
  36996. if (this._metallicTexture) {
  36997. this._metallicTexture.dispose();
  36998. }
  36999. if (this._reflectivityTexture) {
  37000. this._reflectivityTexture.dispose();
  37001. }
  37002. if (this._bumpTexture) {
  37003. this._bumpTexture.dispose();
  37004. }
  37005. if (this._lightmapTexture) {
  37006. this._lightmapTexture.dispose();
  37007. }
  37008. if (this._refractionTexture) {
  37009. this._refractionTexture.dispose();
  37010. }
  37011. }
  37012. this._renderTargets.dispose();
  37013. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37014. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37015. }
  37016. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  37017. };
  37018. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  37019. __decorate([
  37020. BABYLON.serializeAsImageProcessingConfiguration()
  37021. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  37022. __decorate([
  37023. BABYLON.serialize()
  37024. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  37025. __decorate([
  37026. BABYLON.serialize()
  37027. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  37028. return PBRBaseMaterial;
  37029. }(BABYLON.PushMaterial));
  37030. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  37031. })(BABYLON || (BABYLON = {}));
  37032. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  37033. var BABYLON;
  37034. (function (BABYLON) {
  37035. var Internals;
  37036. (function (Internals) {
  37037. /**
  37038. * The Physically based simple base material of BJS.
  37039. *
  37040. * This enables better naming and convention enforcements on top of the pbrMaterial.
  37041. * It is used as the base class for both the specGloss and metalRough conventions.
  37042. */
  37043. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  37044. __extends(PBRBaseSimpleMaterial, _super);
  37045. /**
  37046. * Instantiates a new PBRMaterial instance.
  37047. *
  37048. * @param name The material name
  37049. * @param scene The scene the material will be use in.
  37050. */
  37051. function PBRBaseSimpleMaterial(name, scene) {
  37052. var _this = _super.call(this, name, scene) || this;
  37053. /**
  37054. * Number of Simultaneous lights allowed on the material.
  37055. */
  37056. _this.maxSimultaneousLights = 4;
  37057. /**
  37058. * If sets to true, disables all the lights affecting the material.
  37059. */
  37060. _this.disableLighting = false;
  37061. /**
  37062. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  37063. */
  37064. _this.invertNormalMapX = false;
  37065. /**
  37066. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  37067. */
  37068. _this.invertNormalMapY = false;
  37069. /**
  37070. * Emissivie color used to self-illuminate the model.
  37071. */
  37072. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  37073. /**
  37074. * Occlusion Channel Strenght.
  37075. */
  37076. _this.occlusionStrength = 1.0;
  37077. _this.useLightmapAsShadowmap = false;
  37078. _this._useAlphaFromAlbedoTexture = true;
  37079. _this._useAmbientInGrayScale = true;
  37080. return _this;
  37081. }
  37082. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  37083. /**
  37084. * Gets the current double sided mode.
  37085. */
  37086. get: function () {
  37087. return this._twoSidedLighting;
  37088. },
  37089. /**
  37090. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37091. */
  37092. set: function (value) {
  37093. if (this._twoSidedLighting === value) {
  37094. return;
  37095. }
  37096. this._twoSidedLighting = value;
  37097. this.backFaceCulling = !value;
  37098. this._markAllSubMeshesAsTexturesDirty();
  37099. },
  37100. enumerable: true,
  37101. configurable: true
  37102. });
  37103. /**
  37104. * Return the active textures of the material.
  37105. */
  37106. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  37107. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37108. if (this.environmentTexture) {
  37109. activeTextures.push(this.environmentTexture);
  37110. }
  37111. if (this.normalTexture) {
  37112. activeTextures.push(this.normalTexture);
  37113. }
  37114. if (this.emissiveTexture) {
  37115. activeTextures.push(this.emissiveTexture);
  37116. }
  37117. if (this.occlusionTexture) {
  37118. activeTextures.push(this.occlusionTexture);
  37119. }
  37120. if (this.lightmapTexture) {
  37121. activeTextures.push(this.lightmapTexture);
  37122. }
  37123. return activeTextures;
  37124. };
  37125. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  37126. if (_super.prototype.hasTexture.call(this, texture)) {
  37127. return true;
  37128. }
  37129. if (this.lightmapTexture === texture) {
  37130. return true;
  37131. }
  37132. return false;
  37133. };
  37134. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  37135. return "PBRBaseSimpleMaterial";
  37136. };
  37137. __decorate([
  37138. BABYLON.serialize(),
  37139. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37140. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  37141. __decorate([
  37142. BABYLON.serialize(),
  37143. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37144. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  37145. __decorate([
  37146. BABYLON.serializeAsTexture(),
  37147. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  37148. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  37149. __decorate([
  37150. BABYLON.serialize(),
  37151. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37152. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  37153. __decorate([
  37154. BABYLON.serialize(),
  37155. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37156. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  37157. __decorate([
  37158. BABYLON.serializeAsTexture(),
  37159. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  37160. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  37161. __decorate([
  37162. BABYLON.serializeAsColor3("emissive"),
  37163. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37164. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  37165. __decorate([
  37166. BABYLON.serializeAsTexture(),
  37167. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37168. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  37169. __decorate([
  37170. BABYLON.serialize(),
  37171. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  37172. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  37173. __decorate([
  37174. BABYLON.serializeAsTexture(),
  37175. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  37176. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  37177. __decorate([
  37178. BABYLON.serialize(),
  37179. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  37180. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  37181. __decorate([
  37182. BABYLON.serialize()
  37183. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  37184. __decorate([
  37185. BABYLON.serializeAsTexture(),
  37186. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  37187. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  37188. __decorate([
  37189. BABYLON.serialize(),
  37190. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37191. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  37192. return PBRBaseSimpleMaterial;
  37193. }(BABYLON.PBRBaseMaterial));
  37194. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  37195. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  37196. })(BABYLON || (BABYLON = {}));
  37197. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  37198. var BABYLON;
  37199. (function (BABYLON) {
  37200. /**
  37201. * The Physically based material of BJS.
  37202. *
  37203. * This offers the main features of a standard PBR material.
  37204. * For more information, please refer to the documentation :
  37205. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  37206. */
  37207. var PBRMaterial = /** @class */ (function (_super) {
  37208. __extends(PBRMaterial, _super);
  37209. /**
  37210. * Instantiates a new PBRMaterial instance.
  37211. *
  37212. * @param name The material name
  37213. * @param scene The scene the material will be use in.
  37214. */
  37215. function PBRMaterial(name, scene) {
  37216. var _this = _super.call(this, name, scene) || this;
  37217. /**
  37218. * Intensity of the direct lights e.g. the four lights available in your scene.
  37219. * This impacts both the direct diffuse and specular highlights.
  37220. */
  37221. _this.directIntensity = 1.0;
  37222. /**
  37223. * Intensity of the emissive part of the material.
  37224. * This helps controlling the emissive effect without modifying the emissive color.
  37225. */
  37226. _this.emissiveIntensity = 1.0;
  37227. /**
  37228. * Intensity of the environment e.g. how much the environment will light the object
  37229. * either through harmonics for rough material or through the refelction for shiny ones.
  37230. */
  37231. _this.environmentIntensity = 1.0;
  37232. /**
  37233. * This is a special control allowing the reduction of the specular highlights coming from the
  37234. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  37235. */
  37236. _this.specularIntensity = 1.0;
  37237. /**
  37238. * Debug Control allowing disabling the bump map on this material.
  37239. */
  37240. _this.disableBumpMap = false;
  37241. /**
  37242. * AKA Occlusion Texture Intensity in other nomenclature.
  37243. */
  37244. _this.ambientTextureStrength = 1.0;
  37245. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  37246. /**
  37247. * AKA Diffuse Color in other nomenclature.
  37248. */
  37249. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  37250. /**
  37251. * AKA Specular Color in other nomenclature.
  37252. */
  37253. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  37254. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  37255. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  37256. /**
  37257. * AKA Glossiness in other nomenclature.
  37258. */
  37259. _this.microSurface = 1.0;
  37260. /**
  37261. * source material index of refraction (IOR)' / 'destination material IOR.
  37262. */
  37263. _this.indexOfRefraction = 0.66;
  37264. /**
  37265. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  37266. */
  37267. _this.invertRefractionY = false;
  37268. /**
  37269. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  37270. * Materials half opaque for instance using refraction could benefit from this control.
  37271. */
  37272. _this.linkRefractionWithTransparency = false;
  37273. _this.useLightmapAsShadowmap = false;
  37274. /**
  37275. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  37276. */
  37277. _this.useAlphaFromAlbedoTexture = false;
  37278. /**
  37279. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  37280. */
  37281. _this.forceAlphaTest = false;
  37282. /**
  37283. * Defines the alpha limits in alpha test mode.
  37284. */
  37285. _this.alphaCutOff = 0.4;
  37286. /**
  37287. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  37288. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  37289. */
  37290. _this.useSpecularOverAlpha = true;
  37291. /**
  37292. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  37293. */
  37294. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  37295. /**
  37296. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  37297. */
  37298. _this.useRoughnessFromMetallicTextureAlpha = true;
  37299. /**
  37300. * Specifies if the metallic texture contains the roughness information in its green channel.
  37301. */
  37302. _this.useRoughnessFromMetallicTextureGreen = false;
  37303. /**
  37304. * Specifies if the metallic texture contains the metallness information in its blue channel.
  37305. */
  37306. _this.useMetallnessFromMetallicTextureBlue = false;
  37307. /**
  37308. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  37309. */
  37310. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  37311. /**
  37312. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  37313. */
  37314. _this.useAmbientInGrayScale = false;
  37315. /**
  37316. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  37317. * The material will try to infer what glossiness each pixel should be.
  37318. */
  37319. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  37320. /**
  37321. * BJS is using an harcoded light falloff based on a manually sets up range.
  37322. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  37323. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  37324. */
  37325. _this.usePhysicalLightFalloff = true;
  37326. /**
  37327. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  37328. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  37329. */
  37330. _this.useRadianceOverAlpha = true;
  37331. /**
  37332. * Allows using the bump map in parallax mode.
  37333. */
  37334. _this.useParallax = false;
  37335. /**
  37336. * Allows using the bump map in parallax occlusion mode.
  37337. */
  37338. _this.useParallaxOcclusion = false;
  37339. /**
  37340. * Controls the scale bias of the parallax mode.
  37341. */
  37342. _this.parallaxScaleBias = 0.05;
  37343. /**
  37344. * If sets to true, disables all the lights affecting the material.
  37345. */
  37346. _this.disableLighting = false;
  37347. /**
  37348. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  37349. */
  37350. _this.forceIrradianceInFragment = false;
  37351. /**
  37352. * Number of Simultaneous lights allowed on the material.
  37353. */
  37354. _this.maxSimultaneousLights = 4;
  37355. /**
  37356. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  37357. */
  37358. _this.invertNormalMapX = false;
  37359. /**
  37360. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  37361. */
  37362. _this.invertNormalMapY = false;
  37363. /**
  37364. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37365. */
  37366. _this.twoSidedLighting = false;
  37367. /**
  37368. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37369. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  37370. */
  37371. _this.useAlphaFresnel = false;
  37372. /**
  37373. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37374. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  37375. */
  37376. _this.useLinearAlphaFresnel = false;
  37377. /**
  37378. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37379. * And/Or occlude the blended part.
  37380. */
  37381. _this.environmentBRDFTexture = null;
  37382. /**
  37383. * Force normal to face away from face.
  37384. */
  37385. _this.forceNormalForward = false;
  37386. /**
  37387. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  37388. * makes the reflect vector face the model (under horizon).
  37389. */
  37390. _this.useHorizonOcclusion = true;
  37391. /**
  37392. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  37393. * too much the area relying on ambient texture to define their ambient occlusion.
  37394. */
  37395. _this.useRadianceOcclusion = true;
  37396. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  37397. return _this;
  37398. }
  37399. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  37400. /**
  37401. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  37402. */
  37403. get: function () {
  37404. return this._PBRMATERIAL_OPAQUE;
  37405. },
  37406. enumerable: true,
  37407. configurable: true
  37408. });
  37409. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  37410. /**
  37411. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  37412. */
  37413. get: function () {
  37414. return this._PBRMATERIAL_ALPHATEST;
  37415. },
  37416. enumerable: true,
  37417. configurable: true
  37418. });
  37419. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  37420. /**
  37421. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  37422. */
  37423. get: function () {
  37424. return this._PBRMATERIAL_ALPHABLEND;
  37425. },
  37426. enumerable: true,
  37427. configurable: true
  37428. });
  37429. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  37430. /**
  37431. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  37432. * They are also discarded below the alpha cutoff threshold to improve performances.
  37433. */
  37434. get: function () {
  37435. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  37436. },
  37437. enumerable: true,
  37438. configurable: true
  37439. });
  37440. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  37441. /**
  37442. * Gets the image processing configuration used either in this material.
  37443. */
  37444. get: function () {
  37445. return this._imageProcessingConfiguration;
  37446. },
  37447. /**
  37448. * Sets the Default image processing configuration used either in the this material.
  37449. *
  37450. * If sets to null, the scene one is in use.
  37451. */
  37452. set: function (value) {
  37453. this._attachImageProcessingConfiguration(value);
  37454. // Ensure the effect will be rebuilt.
  37455. this._markAllSubMeshesAsTexturesDirty();
  37456. },
  37457. enumerable: true,
  37458. configurable: true
  37459. });
  37460. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  37461. /**
  37462. * Gets wether the color curves effect is enabled.
  37463. */
  37464. get: function () {
  37465. return this.imageProcessingConfiguration.colorCurvesEnabled;
  37466. },
  37467. /**
  37468. * Sets wether the color curves effect is enabled.
  37469. */
  37470. set: function (value) {
  37471. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  37472. },
  37473. enumerable: true,
  37474. configurable: true
  37475. });
  37476. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  37477. /**
  37478. * Gets wether the color grading effect is enabled.
  37479. */
  37480. get: function () {
  37481. return this.imageProcessingConfiguration.colorGradingEnabled;
  37482. },
  37483. /**
  37484. * Gets wether the color grading effect is enabled.
  37485. */
  37486. set: function (value) {
  37487. this.imageProcessingConfiguration.colorGradingEnabled = value;
  37488. },
  37489. enumerable: true,
  37490. configurable: true
  37491. });
  37492. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  37493. /**
  37494. * Gets wether tonemapping is enabled or not.
  37495. */
  37496. get: function () {
  37497. return this._imageProcessingConfiguration.toneMappingEnabled;
  37498. },
  37499. /**
  37500. * Sets wether tonemapping is enabled or not
  37501. */
  37502. set: function (value) {
  37503. this._imageProcessingConfiguration.toneMappingEnabled = value;
  37504. },
  37505. enumerable: true,
  37506. configurable: true
  37507. });
  37508. ;
  37509. ;
  37510. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  37511. /**
  37512. * The camera exposure used on this material.
  37513. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  37514. * This corresponds to a photographic exposure.
  37515. */
  37516. get: function () {
  37517. return this._imageProcessingConfiguration.exposure;
  37518. },
  37519. /**
  37520. * The camera exposure used on this material.
  37521. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  37522. * This corresponds to a photographic exposure.
  37523. */
  37524. set: function (value) {
  37525. this._imageProcessingConfiguration.exposure = value;
  37526. },
  37527. enumerable: true,
  37528. configurable: true
  37529. });
  37530. ;
  37531. ;
  37532. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  37533. /**
  37534. * Gets The camera contrast used on this material.
  37535. */
  37536. get: function () {
  37537. return this._imageProcessingConfiguration.contrast;
  37538. },
  37539. /**
  37540. * Sets The camera contrast used on this material.
  37541. */
  37542. set: function (value) {
  37543. this._imageProcessingConfiguration.contrast = value;
  37544. },
  37545. enumerable: true,
  37546. configurable: true
  37547. });
  37548. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  37549. /**
  37550. * Gets the Color Grading 2D Lookup Texture.
  37551. */
  37552. get: function () {
  37553. return this._imageProcessingConfiguration.colorGradingTexture;
  37554. },
  37555. /**
  37556. * Sets the Color Grading 2D Lookup Texture.
  37557. */
  37558. set: function (value) {
  37559. this._imageProcessingConfiguration.colorGradingTexture = value;
  37560. },
  37561. enumerable: true,
  37562. configurable: true
  37563. });
  37564. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  37565. /**
  37566. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37567. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37568. * 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;
  37569. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37570. */
  37571. get: function () {
  37572. return this._imageProcessingConfiguration.colorCurves;
  37573. },
  37574. /**
  37575. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37576. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37577. * 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;
  37578. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37579. */
  37580. set: function (value) {
  37581. this._imageProcessingConfiguration.colorCurves = value;
  37582. },
  37583. enumerable: true,
  37584. configurable: true
  37585. });
  37586. PBRMaterial.prototype.getClassName = function () {
  37587. return "PBRMaterial";
  37588. };
  37589. PBRMaterial.prototype.getActiveTextures = function () {
  37590. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37591. if (this._albedoTexture) {
  37592. activeTextures.push(this._albedoTexture);
  37593. }
  37594. if (this._ambientTexture) {
  37595. activeTextures.push(this._ambientTexture);
  37596. }
  37597. if (this._opacityTexture) {
  37598. activeTextures.push(this._opacityTexture);
  37599. }
  37600. if (this._reflectionTexture) {
  37601. activeTextures.push(this._reflectionTexture);
  37602. }
  37603. if (this._emissiveTexture) {
  37604. activeTextures.push(this._emissiveTexture);
  37605. }
  37606. if (this._reflectivityTexture) {
  37607. activeTextures.push(this._reflectivityTexture);
  37608. }
  37609. if (this._metallicTexture) {
  37610. activeTextures.push(this._metallicTexture);
  37611. }
  37612. if (this._microSurfaceTexture) {
  37613. activeTextures.push(this._microSurfaceTexture);
  37614. }
  37615. if (this._bumpTexture) {
  37616. activeTextures.push(this._bumpTexture);
  37617. }
  37618. if (this._lightmapTexture) {
  37619. activeTextures.push(this._lightmapTexture);
  37620. }
  37621. if (this._refractionTexture) {
  37622. activeTextures.push(this._refractionTexture);
  37623. }
  37624. return activeTextures;
  37625. };
  37626. PBRMaterial.prototype.hasTexture = function (texture) {
  37627. if (_super.prototype.hasTexture.call(this, texture)) {
  37628. return true;
  37629. }
  37630. if (this._albedoTexture === texture) {
  37631. return true;
  37632. }
  37633. if (this._ambientTexture === texture) {
  37634. return true;
  37635. }
  37636. if (this._opacityTexture === texture) {
  37637. return true;
  37638. }
  37639. if (this._reflectionTexture === texture) {
  37640. return true;
  37641. }
  37642. if (this._reflectivityTexture === texture) {
  37643. return true;
  37644. }
  37645. if (this._metallicTexture === texture) {
  37646. return true;
  37647. }
  37648. if (this._microSurfaceTexture === texture) {
  37649. return true;
  37650. }
  37651. if (this._bumpTexture === texture) {
  37652. return true;
  37653. }
  37654. if (this._lightmapTexture === texture) {
  37655. return true;
  37656. }
  37657. if (this._refractionTexture === texture) {
  37658. return true;
  37659. }
  37660. return false;
  37661. };
  37662. PBRMaterial.prototype.clone = function (name) {
  37663. var _this = this;
  37664. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  37665. clone.id = name;
  37666. clone.name = name;
  37667. return clone;
  37668. };
  37669. PBRMaterial.prototype.serialize = function () {
  37670. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  37671. serializationObject.customType = "BABYLON.PBRMaterial";
  37672. return serializationObject;
  37673. };
  37674. // Statics
  37675. PBRMaterial.Parse = function (source, scene, rootUrl) {
  37676. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  37677. };
  37678. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  37679. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  37680. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  37681. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  37682. __decorate([
  37683. BABYLON.serialize(),
  37684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37685. ], PBRMaterial.prototype, "directIntensity", void 0);
  37686. __decorate([
  37687. BABYLON.serialize(),
  37688. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37689. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  37690. __decorate([
  37691. BABYLON.serialize(),
  37692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37693. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  37694. __decorate([
  37695. BABYLON.serialize(),
  37696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37697. ], PBRMaterial.prototype, "specularIntensity", void 0);
  37698. __decorate([
  37699. BABYLON.serialize(),
  37700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37701. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  37702. __decorate([
  37703. BABYLON.serializeAsTexture(),
  37704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37705. ], PBRMaterial.prototype, "albedoTexture", void 0);
  37706. __decorate([
  37707. BABYLON.serializeAsTexture(),
  37708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37709. ], PBRMaterial.prototype, "ambientTexture", void 0);
  37710. __decorate([
  37711. BABYLON.serialize(),
  37712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37713. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  37714. __decorate([
  37715. BABYLON.serializeAsTexture(),
  37716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37717. ], PBRMaterial.prototype, "opacityTexture", void 0);
  37718. __decorate([
  37719. BABYLON.serializeAsTexture(),
  37720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37721. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  37722. __decorate([
  37723. BABYLON.serializeAsTexture(),
  37724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37725. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  37726. __decorate([
  37727. BABYLON.serializeAsTexture(),
  37728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37729. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  37730. __decorate([
  37731. BABYLON.serializeAsTexture(),
  37732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37733. ], PBRMaterial.prototype, "metallicTexture", void 0);
  37734. __decorate([
  37735. BABYLON.serialize(),
  37736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37737. ], PBRMaterial.prototype, "metallic", void 0);
  37738. __decorate([
  37739. BABYLON.serialize(),
  37740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37741. ], PBRMaterial.prototype, "roughness", void 0);
  37742. __decorate([
  37743. BABYLON.serializeAsTexture(),
  37744. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37745. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  37746. __decorate([
  37747. BABYLON.serializeAsTexture(),
  37748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37749. ], PBRMaterial.prototype, "bumpTexture", void 0);
  37750. __decorate([
  37751. BABYLON.serializeAsTexture(),
  37752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  37753. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  37754. __decorate([
  37755. BABYLON.serializeAsTexture(),
  37756. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37757. ], PBRMaterial.prototype, "refractionTexture", void 0);
  37758. __decorate([
  37759. BABYLON.serializeAsColor3("ambient"),
  37760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37761. ], PBRMaterial.prototype, "ambientColor", void 0);
  37762. __decorate([
  37763. BABYLON.serializeAsColor3("albedo"),
  37764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37765. ], PBRMaterial.prototype, "albedoColor", void 0);
  37766. __decorate([
  37767. BABYLON.serializeAsColor3("reflectivity"),
  37768. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37769. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  37770. __decorate([
  37771. BABYLON.serializeAsColor3("reflection"),
  37772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37773. ], PBRMaterial.prototype, "reflectionColor", void 0);
  37774. __decorate([
  37775. BABYLON.serializeAsColor3("emissive"),
  37776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37777. ], PBRMaterial.prototype, "emissiveColor", void 0);
  37778. __decorate([
  37779. BABYLON.serialize(),
  37780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37781. ], PBRMaterial.prototype, "microSurface", void 0);
  37782. __decorate([
  37783. BABYLON.serialize(),
  37784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37785. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  37786. __decorate([
  37787. BABYLON.serialize(),
  37788. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37789. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  37790. __decorate([
  37791. BABYLON.serialize(),
  37792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37793. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  37794. __decorate([
  37795. BABYLON.serialize(),
  37796. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37797. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  37798. __decorate([
  37799. BABYLON.serialize(),
  37800. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37801. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  37802. __decorate([
  37803. BABYLON.serialize(),
  37804. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37805. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  37806. __decorate([
  37807. BABYLON.serialize(),
  37808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37809. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  37810. __decorate([
  37811. BABYLON.serialize(),
  37812. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37813. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  37814. __decorate([
  37815. BABYLON.serialize(),
  37816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37817. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  37818. __decorate([
  37819. BABYLON.serialize(),
  37820. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37821. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  37822. __decorate([
  37823. BABYLON.serialize(),
  37824. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37825. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  37826. __decorate([
  37827. BABYLON.serialize(),
  37828. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37829. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  37830. __decorate([
  37831. BABYLON.serialize(),
  37832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37833. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  37834. __decorate([
  37835. BABYLON.serialize(),
  37836. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37837. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  37838. __decorate([
  37839. BABYLON.serialize(),
  37840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37841. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  37842. __decorate([
  37843. BABYLON.serialize(),
  37844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37845. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  37846. __decorate([
  37847. BABYLON.serialize(),
  37848. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37849. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  37850. __decorate([
  37851. BABYLON.serialize(),
  37852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37853. ], PBRMaterial.prototype, "useParallax", void 0);
  37854. __decorate([
  37855. BABYLON.serialize(),
  37856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37857. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  37858. __decorate([
  37859. BABYLON.serialize(),
  37860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37861. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  37862. __decorate([
  37863. BABYLON.serialize(),
  37864. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37865. ], PBRMaterial.prototype, "disableLighting", void 0);
  37866. __decorate([
  37867. BABYLON.serialize(),
  37868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37869. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  37870. __decorate([
  37871. BABYLON.serialize(),
  37872. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37873. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  37874. __decorate([
  37875. BABYLON.serialize(),
  37876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37877. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  37878. __decorate([
  37879. BABYLON.serialize(),
  37880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37881. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  37882. __decorate([
  37883. BABYLON.serialize(),
  37884. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37885. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  37886. __decorate([
  37887. BABYLON.serialize(),
  37888. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37889. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  37890. __decorate([
  37891. BABYLON.serialize(),
  37892. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37893. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  37894. __decorate([
  37895. BABYLON.serializeAsTexture(),
  37896. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37897. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  37898. __decorate([
  37899. BABYLON.serialize(),
  37900. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37901. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  37902. __decorate([
  37903. BABYLON.serialize(),
  37904. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37905. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  37906. __decorate([
  37907. BABYLON.serialize(),
  37908. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37909. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  37910. return PBRMaterial;
  37911. }(BABYLON.PBRBaseMaterial));
  37912. BABYLON.PBRMaterial = PBRMaterial;
  37913. })(BABYLON || (BABYLON = {}));
  37914. //# sourceMappingURL=babylon.pbrMaterial.js.map
  37915. var BABYLON;
  37916. (function (BABYLON) {
  37917. /**
  37918. * The PBR material of BJS following the metal roughness convention.
  37919. *
  37920. * This fits to the PBR convention in the GLTF definition:
  37921. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  37922. */
  37923. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  37924. __extends(PBRMetallicRoughnessMaterial, _super);
  37925. /**
  37926. * Instantiates a new PBRMetalRoughnessMaterial instance.
  37927. *
  37928. * @param name The material name
  37929. * @param scene The scene the material will be use in.
  37930. */
  37931. function PBRMetallicRoughnessMaterial(name, scene) {
  37932. var _this = _super.call(this, name, scene) || this;
  37933. _this._useRoughnessFromMetallicTextureAlpha = false;
  37934. _this._useRoughnessFromMetallicTextureGreen = true;
  37935. _this._useMetallnessFromMetallicTextureBlue = true;
  37936. return _this;
  37937. }
  37938. /**
  37939. * Return the currrent class name of the material.
  37940. */
  37941. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  37942. return "PBRMetallicRoughnessMaterial";
  37943. };
  37944. /**
  37945. * Return the active textures of the material.
  37946. */
  37947. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  37948. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37949. if (this.baseTexture) {
  37950. activeTextures.push(this.baseTexture);
  37951. }
  37952. if (this.metallicRoughnessTexture) {
  37953. activeTextures.push(this.metallicRoughnessTexture);
  37954. }
  37955. return activeTextures;
  37956. };
  37957. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  37958. if (_super.prototype.hasTexture.call(this, texture)) {
  37959. return true;
  37960. }
  37961. if (this.baseTexture === texture) {
  37962. return true;
  37963. }
  37964. if (this.metallicRoughnessTexture === texture) {
  37965. return true;
  37966. }
  37967. return false;
  37968. };
  37969. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  37970. var _this = this;
  37971. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  37972. clone.id = name;
  37973. clone.name = name;
  37974. return clone;
  37975. };
  37976. /**
  37977. * Serialize the material to a parsable JSON object.
  37978. */
  37979. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  37980. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  37981. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  37982. return serializationObject;
  37983. };
  37984. /**
  37985. * Parses a JSON object correponding to the serialize function.
  37986. */
  37987. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  37988. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  37989. };
  37990. __decorate([
  37991. BABYLON.serializeAsColor3(),
  37992. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  37993. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  37994. __decorate([
  37995. BABYLON.serializeAsTexture(),
  37996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  37997. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  37998. __decorate([
  37999. BABYLON.serialize(),
  38000. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38001. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  38002. __decorate([
  38003. BABYLON.serialize(),
  38004. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38005. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  38006. __decorate([
  38007. BABYLON.serializeAsTexture(),
  38008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  38009. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  38010. return PBRMetallicRoughnessMaterial;
  38011. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  38012. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  38013. })(BABYLON || (BABYLON = {}));
  38014. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  38015. var BABYLON;
  38016. (function (BABYLON) {
  38017. /**
  38018. * The PBR material of BJS following the specular glossiness convention.
  38019. *
  38020. * This fits to the PBR convention in the GLTF definition:
  38021. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  38022. */
  38023. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  38024. __extends(PBRSpecularGlossinessMaterial, _super);
  38025. /**
  38026. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  38027. *
  38028. * @param name The material name
  38029. * @param scene The scene the material will be use in.
  38030. */
  38031. function PBRSpecularGlossinessMaterial(name, scene) {
  38032. var _this = _super.call(this, name, scene) || this;
  38033. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  38034. return _this;
  38035. }
  38036. /**
  38037. * Return the currrent class name of the material.
  38038. */
  38039. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  38040. return "PBRSpecularGlossinessMaterial";
  38041. };
  38042. /**
  38043. * Return the active textures of the material.
  38044. */
  38045. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  38046. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38047. if (this.diffuseTexture) {
  38048. activeTextures.push(this.diffuseTexture);
  38049. }
  38050. if (this.specularGlossinessTexture) {
  38051. activeTextures.push(this.specularGlossinessTexture);
  38052. }
  38053. return activeTextures;
  38054. };
  38055. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  38056. if (_super.prototype.hasTexture.call(this, texture)) {
  38057. return true;
  38058. }
  38059. if (this.diffuseTexture === texture) {
  38060. return true;
  38061. }
  38062. if (this.specularGlossinessTexture === texture) {
  38063. return true;
  38064. }
  38065. return false;
  38066. };
  38067. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  38068. var _this = this;
  38069. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  38070. clone.id = name;
  38071. clone.name = name;
  38072. return clone;
  38073. };
  38074. /**
  38075. * Serialize the material to a parsable JSON object.
  38076. */
  38077. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  38078. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38079. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  38080. return serializationObject;
  38081. };
  38082. /**
  38083. * Parses a JSON object correponding to the serialize function.
  38084. */
  38085. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  38086. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  38087. };
  38088. __decorate([
  38089. BABYLON.serializeAsColor3("diffuse"),
  38090. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  38091. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  38092. __decorate([
  38093. BABYLON.serializeAsTexture(),
  38094. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  38095. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  38096. __decorate([
  38097. BABYLON.serializeAsColor3("specular"),
  38098. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  38099. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  38100. __decorate([
  38101. BABYLON.serialize(),
  38102. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  38103. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  38104. __decorate([
  38105. BABYLON.serializeAsTexture(),
  38106. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  38107. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  38108. return PBRSpecularGlossinessMaterial;
  38109. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  38110. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  38111. })(BABYLON || (BABYLON = {}));
  38112. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  38113. var BABYLON;
  38114. (function (BABYLON) {
  38115. BABYLON.CameraInputTypes = {};
  38116. var CameraInputsManager = /** @class */ (function () {
  38117. function CameraInputsManager(camera) {
  38118. this.attached = {};
  38119. this.camera = camera;
  38120. this.checkInputs = function () { };
  38121. }
  38122. CameraInputsManager.prototype.add = function (input) {
  38123. var type = input.getSimpleName();
  38124. if (this.attached[type]) {
  38125. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  38126. return;
  38127. }
  38128. this.attached[type] = input;
  38129. input.camera = this.camera;
  38130. //for checkInputs, we are dynamically creating a function
  38131. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  38132. if (input.checkInputs) {
  38133. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  38134. }
  38135. if (this.attachedElement) {
  38136. input.attachControl(this.attachedElement);
  38137. }
  38138. };
  38139. CameraInputsManager.prototype.remove = function (inputToRemove) {
  38140. for (var cam in this.attached) {
  38141. var input = this.attached[cam];
  38142. if (input === inputToRemove) {
  38143. input.detachControl(this.attachedElement);
  38144. input.camera = null;
  38145. delete this.attached[cam];
  38146. this.rebuildInputCheck();
  38147. }
  38148. }
  38149. };
  38150. CameraInputsManager.prototype.removeByType = function (inputType) {
  38151. for (var cam in this.attached) {
  38152. var input = this.attached[cam];
  38153. if (input.getClassName() === inputType) {
  38154. input.detachControl(this.attachedElement);
  38155. input.camera = null;
  38156. delete this.attached[cam];
  38157. this.rebuildInputCheck();
  38158. }
  38159. }
  38160. };
  38161. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  38162. var current = this.checkInputs;
  38163. return function () {
  38164. current();
  38165. fn();
  38166. };
  38167. };
  38168. CameraInputsManager.prototype.attachInput = function (input) {
  38169. if (this.attachedElement) {
  38170. input.attachControl(this.attachedElement, this.noPreventDefault);
  38171. }
  38172. };
  38173. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  38174. if (noPreventDefault === void 0) { noPreventDefault = false; }
  38175. if (this.attachedElement) {
  38176. return;
  38177. }
  38178. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  38179. this.attachedElement = element;
  38180. this.noPreventDefault = noPreventDefault;
  38181. for (var cam in this.attached) {
  38182. this.attached[cam].attachControl(element, noPreventDefault);
  38183. }
  38184. };
  38185. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  38186. if (disconnect === void 0) { disconnect = false; }
  38187. if (this.attachedElement !== element) {
  38188. return;
  38189. }
  38190. for (var cam in this.attached) {
  38191. this.attached[cam].detachControl(element);
  38192. if (disconnect) {
  38193. this.attached[cam].camera = null;
  38194. }
  38195. }
  38196. this.attachedElement = null;
  38197. };
  38198. CameraInputsManager.prototype.rebuildInputCheck = function () {
  38199. this.checkInputs = function () { };
  38200. for (var cam in this.attached) {
  38201. var input = this.attached[cam];
  38202. if (input.checkInputs) {
  38203. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  38204. }
  38205. }
  38206. };
  38207. CameraInputsManager.prototype.clear = function () {
  38208. if (this.attachedElement) {
  38209. this.detachElement(this.attachedElement, true);
  38210. }
  38211. this.attached = {};
  38212. this.attachedElement = null;
  38213. this.checkInputs = function () { };
  38214. };
  38215. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  38216. var inputs = {};
  38217. for (var cam in this.attached) {
  38218. var input = this.attached[cam];
  38219. var res = BABYLON.SerializationHelper.Serialize(input);
  38220. inputs[input.getClassName()] = res;
  38221. }
  38222. serializedCamera.inputsmgr = inputs;
  38223. };
  38224. CameraInputsManager.prototype.parse = function (parsedCamera) {
  38225. var parsedInputs = parsedCamera.inputsmgr;
  38226. if (parsedInputs) {
  38227. this.clear();
  38228. for (var n in parsedInputs) {
  38229. var construct = BABYLON.CameraInputTypes[n];
  38230. if (construct) {
  38231. var parsedinput = parsedInputs[n];
  38232. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  38233. this.add(input);
  38234. }
  38235. }
  38236. }
  38237. else {
  38238. //2016-03-08 this part is for managing backward compatibility
  38239. for (var n in this.attached) {
  38240. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  38241. if (construct) {
  38242. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  38243. this.remove(this.attached[n]);
  38244. this.add(input);
  38245. }
  38246. }
  38247. }
  38248. };
  38249. return CameraInputsManager;
  38250. }());
  38251. BABYLON.CameraInputsManager = CameraInputsManager;
  38252. })(BABYLON || (BABYLON = {}));
  38253. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  38254. var BABYLON;
  38255. (function (BABYLON) {
  38256. var FreeCameraMouseInput = /** @class */ (function () {
  38257. function FreeCameraMouseInput(touchEnabled) {
  38258. if (touchEnabled === void 0) { touchEnabled = true; }
  38259. this.touchEnabled = touchEnabled;
  38260. this.buttons = [0, 1, 2];
  38261. this.angularSensibility = 2000.0;
  38262. this.previousPosition = null;
  38263. }
  38264. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  38265. var _this = this;
  38266. var engine = this.camera.getEngine();
  38267. if (!this._pointerInput) {
  38268. this._pointerInput = function (p, s) {
  38269. var evt = p.event;
  38270. if (engine.isInVRExclusivePointerMode) {
  38271. return;
  38272. }
  38273. if (!_this.touchEnabled && evt.pointerType === "touch") {
  38274. return;
  38275. }
  38276. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  38277. return;
  38278. }
  38279. var srcElement = (evt.srcElement || evt.target);
  38280. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  38281. try {
  38282. srcElement.setPointerCapture(evt.pointerId);
  38283. }
  38284. catch (e) {
  38285. //Nothing to do with the error. Execution will continue.
  38286. }
  38287. _this.previousPosition = {
  38288. x: evt.clientX,
  38289. y: evt.clientY
  38290. };
  38291. if (!noPreventDefault) {
  38292. evt.preventDefault();
  38293. element.focus();
  38294. }
  38295. }
  38296. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  38297. try {
  38298. srcElement.releasePointerCapture(evt.pointerId);
  38299. }
  38300. catch (e) {
  38301. //Nothing to do with the error.
  38302. }
  38303. _this.previousPosition = null;
  38304. if (!noPreventDefault) {
  38305. evt.preventDefault();
  38306. }
  38307. }
  38308. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  38309. if (!_this.previousPosition || engine.isPointerLock) {
  38310. return;
  38311. }
  38312. var offsetX = evt.clientX - _this.previousPosition.x;
  38313. var offsetY = evt.clientY - _this.previousPosition.y;
  38314. if (_this.camera.getScene().useRightHandedSystem) {
  38315. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  38316. }
  38317. else {
  38318. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  38319. }
  38320. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  38321. _this.previousPosition = {
  38322. x: evt.clientX,
  38323. y: evt.clientY
  38324. };
  38325. if (!noPreventDefault) {
  38326. evt.preventDefault();
  38327. }
  38328. }
  38329. };
  38330. }
  38331. this._onMouseMove = function (evt) {
  38332. if (!engine.isPointerLock) {
  38333. return;
  38334. }
  38335. if (engine.isInVRExclusivePointerMode) {
  38336. return;
  38337. }
  38338. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  38339. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  38340. if (_this.camera.getScene().useRightHandedSystem) {
  38341. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  38342. }
  38343. else {
  38344. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  38345. }
  38346. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  38347. _this.previousPosition = null;
  38348. if (!noPreventDefault) {
  38349. evt.preventDefault();
  38350. }
  38351. };
  38352. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  38353. element.addEventListener("mousemove", this._onMouseMove, false);
  38354. };
  38355. FreeCameraMouseInput.prototype.detachControl = function (element) {
  38356. if (this._observer && element) {
  38357. this.camera.getScene().onPointerObservable.remove(this._observer);
  38358. if (this._onMouseMove) {
  38359. element.removeEventListener("mousemove", this._onMouseMove);
  38360. }
  38361. this._observer = null;
  38362. this._onMouseMove = null;
  38363. this.previousPosition = null;
  38364. }
  38365. };
  38366. FreeCameraMouseInput.prototype.getClassName = function () {
  38367. return "FreeCameraMouseInput";
  38368. };
  38369. FreeCameraMouseInput.prototype.getSimpleName = function () {
  38370. return "mouse";
  38371. };
  38372. __decorate([
  38373. BABYLON.serialize()
  38374. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  38375. __decorate([
  38376. BABYLON.serialize()
  38377. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  38378. return FreeCameraMouseInput;
  38379. }());
  38380. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  38381. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  38382. })(BABYLON || (BABYLON = {}));
  38383. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  38384. var BABYLON;
  38385. (function (BABYLON) {
  38386. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  38387. function FreeCameraKeyboardMoveInput() {
  38388. this._keys = new Array();
  38389. this.keysUp = [38];
  38390. this.keysDown = [40];
  38391. this.keysLeft = [37];
  38392. this.keysRight = [39];
  38393. }
  38394. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  38395. var _this = this;
  38396. if (this._onCanvasBlurObserver) {
  38397. return;
  38398. }
  38399. this._scene = this.camera.getScene();
  38400. this._engine = this._scene.getEngine();
  38401. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  38402. _this._keys = [];
  38403. });
  38404. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  38405. var evt = info.event;
  38406. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  38407. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  38408. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  38409. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  38410. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  38411. var index = _this._keys.indexOf(evt.keyCode);
  38412. if (index === -1) {
  38413. _this._keys.push(evt.keyCode);
  38414. }
  38415. if (!noPreventDefault) {
  38416. evt.preventDefault();
  38417. }
  38418. }
  38419. }
  38420. else {
  38421. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  38422. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  38423. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  38424. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  38425. var index = _this._keys.indexOf(evt.keyCode);
  38426. if (index >= 0) {
  38427. _this._keys.splice(index, 1);
  38428. }
  38429. if (!noPreventDefault) {
  38430. evt.preventDefault();
  38431. }
  38432. }
  38433. }
  38434. });
  38435. };
  38436. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  38437. if (this._scene) {
  38438. if (this._onKeyboardObserver) {
  38439. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  38440. }
  38441. if (this._onCanvasBlurObserver) {
  38442. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  38443. }
  38444. this._onKeyboardObserver = null;
  38445. this._onCanvasBlurObserver = null;
  38446. }
  38447. this._keys = [];
  38448. };
  38449. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  38450. if (this._onKeyboardObserver) {
  38451. var camera = this.camera;
  38452. // Keyboard
  38453. for (var index = 0; index < this._keys.length; index++) {
  38454. var keyCode = this._keys[index];
  38455. var speed = camera._computeLocalCameraSpeed();
  38456. if (this.keysLeft.indexOf(keyCode) !== -1) {
  38457. camera._localDirection.copyFromFloats(-speed, 0, 0);
  38458. }
  38459. else if (this.keysUp.indexOf(keyCode) !== -1) {
  38460. camera._localDirection.copyFromFloats(0, 0, speed);
  38461. }
  38462. else if (this.keysRight.indexOf(keyCode) !== -1) {
  38463. camera._localDirection.copyFromFloats(speed, 0, 0);
  38464. }
  38465. else if (this.keysDown.indexOf(keyCode) !== -1) {
  38466. camera._localDirection.copyFromFloats(0, 0, -speed);
  38467. }
  38468. if (camera.getScene().useRightHandedSystem) {
  38469. camera._localDirection.z *= -1;
  38470. }
  38471. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  38472. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  38473. camera.cameraDirection.addInPlace(camera._transformedDirection);
  38474. }
  38475. }
  38476. };
  38477. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  38478. return "FreeCameraKeyboardMoveInput";
  38479. };
  38480. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  38481. this._keys = [];
  38482. };
  38483. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  38484. return "keyboard";
  38485. };
  38486. __decorate([
  38487. BABYLON.serialize()
  38488. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  38489. __decorate([
  38490. BABYLON.serialize()
  38491. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  38492. __decorate([
  38493. BABYLON.serialize()
  38494. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  38495. __decorate([
  38496. BABYLON.serialize()
  38497. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  38498. return FreeCameraKeyboardMoveInput;
  38499. }());
  38500. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  38501. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  38502. })(BABYLON || (BABYLON = {}));
  38503. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  38504. var BABYLON;
  38505. (function (BABYLON) {
  38506. var FreeCameraInputsManager = /** @class */ (function (_super) {
  38507. __extends(FreeCameraInputsManager, _super);
  38508. function FreeCameraInputsManager(camera) {
  38509. return _super.call(this, camera) || this;
  38510. }
  38511. FreeCameraInputsManager.prototype.addKeyboard = function () {
  38512. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  38513. return this;
  38514. };
  38515. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  38516. if (touchEnabled === void 0) { touchEnabled = true; }
  38517. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  38518. return this;
  38519. };
  38520. FreeCameraInputsManager.prototype.addGamepad = function () {
  38521. this.add(new BABYLON.FreeCameraGamepadInput());
  38522. return this;
  38523. };
  38524. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  38525. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  38526. return this;
  38527. };
  38528. FreeCameraInputsManager.prototype.addTouch = function () {
  38529. this.add(new BABYLON.FreeCameraTouchInput());
  38530. return this;
  38531. };
  38532. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  38533. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  38534. return this;
  38535. };
  38536. return FreeCameraInputsManager;
  38537. }(BABYLON.CameraInputsManager));
  38538. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  38539. })(BABYLON || (BABYLON = {}));
  38540. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  38541. var BABYLON;
  38542. (function (BABYLON) {
  38543. var TargetCamera = /** @class */ (function (_super) {
  38544. __extends(TargetCamera, _super);
  38545. function TargetCamera(name, position, scene) {
  38546. var _this = _super.call(this, name, position, scene) || this;
  38547. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  38548. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  38549. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  38550. _this.speed = 2.0;
  38551. _this.noRotationConstraint = false;
  38552. _this.lockedTarget = null;
  38553. _this._currentTarget = BABYLON.Vector3.Zero();
  38554. _this._viewMatrix = BABYLON.Matrix.Zero();
  38555. _this._camMatrix = BABYLON.Matrix.Zero();
  38556. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  38557. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  38558. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  38559. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  38560. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  38561. _this._lookAtTemp = BABYLON.Matrix.Zero();
  38562. _this._tempMatrix = BABYLON.Matrix.Zero();
  38563. return _this;
  38564. }
  38565. TargetCamera.prototype.getFrontPosition = function (distance) {
  38566. var direction = this.getTarget().subtract(this.position);
  38567. direction.normalize();
  38568. direction.scaleInPlace(distance);
  38569. return this.globalPosition.add(direction);
  38570. };
  38571. TargetCamera.prototype._getLockedTargetPosition = function () {
  38572. if (!this.lockedTarget) {
  38573. return null;
  38574. }
  38575. if (this.lockedTarget.absolutePosition) {
  38576. this.lockedTarget.computeWorldMatrix();
  38577. }
  38578. return this.lockedTarget.absolutePosition || this.lockedTarget;
  38579. };
  38580. TargetCamera.prototype.storeState = function () {
  38581. this._storedPosition = this.position.clone();
  38582. this._storedRotation = this.rotation.clone();
  38583. if (this.rotationQuaternion) {
  38584. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  38585. }
  38586. return _super.prototype.storeState.call(this);
  38587. };
  38588. /**
  38589. * Restored camera state. You must call storeState() first
  38590. */
  38591. TargetCamera.prototype._restoreStateValues = function () {
  38592. if (!_super.prototype._restoreStateValues.call(this)) {
  38593. return false;
  38594. }
  38595. this.position = this._storedPosition.clone();
  38596. this.rotation = this._storedRotation.clone();
  38597. if (this.rotationQuaternion) {
  38598. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  38599. }
  38600. this.cameraDirection.copyFromFloats(0, 0, 0);
  38601. this.cameraRotation.copyFromFloats(0, 0);
  38602. return true;
  38603. };
  38604. // Cache
  38605. TargetCamera.prototype._initCache = function () {
  38606. _super.prototype._initCache.call(this);
  38607. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38608. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38609. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38610. };
  38611. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  38612. if (!ignoreParentClass) {
  38613. _super.prototype._updateCache.call(this);
  38614. }
  38615. var lockedTargetPosition = this._getLockedTargetPosition();
  38616. if (!lockedTargetPosition) {
  38617. this._cache.lockedTarget = null;
  38618. }
  38619. else {
  38620. if (!this._cache.lockedTarget) {
  38621. this._cache.lockedTarget = lockedTargetPosition.clone();
  38622. }
  38623. else {
  38624. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  38625. }
  38626. }
  38627. this._cache.rotation.copyFrom(this.rotation);
  38628. if (this.rotationQuaternion)
  38629. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  38630. };
  38631. // Synchronized
  38632. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  38633. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  38634. return false;
  38635. }
  38636. var lockedTargetPosition = this._getLockedTargetPosition();
  38637. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  38638. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  38639. };
  38640. // Methods
  38641. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  38642. var engine = this.getEngine();
  38643. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  38644. };
  38645. // Target
  38646. TargetCamera.prototype.setTarget = function (target) {
  38647. this.upVector.normalize();
  38648. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  38649. this._camMatrix.invert();
  38650. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  38651. var vDir = target.subtract(this.position);
  38652. if (vDir.x >= 0.0) {
  38653. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  38654. }
  38655. else {
  38656. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  38657. }
  38658. this.rotation.z = 0;
  38659. if (isNaN(this.rotation.x)) {
  38660. this.rotation.x = 0;
  38661. }
  38662. if (isNaN(this.rotation.y)) {
  38663. this.rotation.y = 0;
  38664. }
  38665. if (isNaN(this.rotation.z)) {
  38666. this.rotation.z = 0;
  38667. }
  38668. if (this.rotationQuaternion) {
  38669. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  38670. }
  38671. };
  38672. /**
  38673. * Return the current target position of the camera. This value is expressed in local space.
  38674. */
  38675. TargetCamera.prototype.getTarget = function () {
  38676. return this._currentTarget;
  38677. };
  38678. TargetCamera.prototype._decideIfNeedsToMove = function () {
  38679. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  38680. };
  38681. TargetCamera.prototype._updatePosition = function () {
  38682. if (this.parent) {
  38683. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  38684. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  38685. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  38686. return;
  38687. }
  38688. this.position.addInPlace(this.cameraDirection);
  38689. };
  38690. TargetCamera.prototype._checkInputs = function () {
  38691. var needToMove = this._decideIfNeedsToMove();
  38692. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  38693. // Move
  38694. if (needToMove) {
  38695. this._updatePosition();
  38696. }
  38697. // Rotate
  38698. if (needToRotate) {
  38699. this.rotation.x += this.cameraRotation.x;
  38700. this.rotation.y += this.cameraRotation.y;
  38701. //rotate, if quaternion is set and rotation was used
  38702. if (this.rotationQuaternion) {
  38703. var len = this.rotation.lengthSquared();
  38704. if (len) {
  38705. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  38706. }
  38707. }
  38708. if (!this.noRotationConstraint) {
  38709. var limit = (Math.PI / 2) * 0.95;
  38710. if (this.rotation.x > limit)
  38711. this.rotation.x = limit;
  38712. if (this.rotation.x < -limit)
  38713. this.rotation.x = -limit;
  38714. }
  38715. }
  38716. // Inertia
  38717. if (needToMove) {
  38718. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  38719. this.cameraDirection.x = 0;
  38720. }
  38721. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  38722. this.cameraDirection.y = 0;
  38723. }
  38724. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  38725. this.cameraDirection.z = 0;
  38726. }
  38727. this.cameraDirection.scaleInPlace(this.inertia);
  38728. }
  38729. if (needToRotate) {
  38730. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  38731. this.cameraRotation.x = 0;
  38732. }
  38733. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  38734. this.cameraRotation.y = 0;
  38735. }
  38736. this.cameraRotation.scaleInPlace(this.inertia);
  38737. }
  38738. _super.prototype._checkInputs.call(this);
  38739. };
  38740. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  38741. if (this.rotationQuaternion) {
  38742. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  38743. }
  38744. else {
  38745. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  38746. }
  38747. //update the up vector!
  38748. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  38749. };
  38750. TargetCamera.prototype._getViewMatrix = function () {
  38751. if (this.lockedTarget) {
  38752. this.setTarget(this._getLockedTargetPosition());
  38753. }
  38754. // Compute
  38755. this._updateCameraRotationMatrix();
  38756. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  38757. // Computing target and final matrix
  38758. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  38759. if (this.getScene().useRightHandedSystem) {
  38760. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  38761. }
  38762. else {
  38763. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  38764. }
  38765. return this._viewMatrix;
  38766. };
  38767. /**
  38768. * @override
  38769. * Override Camera.createRigCamera
  38770. */
  38771. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  38772. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  38773. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  38774. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  38775. if (!this.rotationQuaternion) {
  38776. this.rotationQuaternion = new BABYLON.Quaternion();
  38777. }
  38778. rigCamera._cameraRigParams = {};
  38779. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  38780. }
  38781. return rigCamera;
  38782. }
  38783. return null;
  38784. };
  38785. /**
  38786. * @override
  38787. * Override Camera._updateRigCameras
  38788. */
  38789. TargetCamera.prototype._updateRigCameras = function () {
  38790. var camLeft = this._rigCameras[0];
  38791. var camRight = this._rigCameras[1];
  38792. switch (this.cameraRigMode) {
  38793. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  38794. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  38795. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  38796. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  38797. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  38798. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  38799. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  38800. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  38801. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  38802. camLeft.setTarget(this.getTarget());
  38803. camRight.setTarget(this.getTarget());
  38804. break;
  38805. case BABYLON.Camera.RIG_MODE_VR:
  38806. if (camLeft.rotationQuaternion) {
  38807. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  38808. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  38809. }
  38810. else {
  38811. camLeft.rotation.copyFrom(this.rotation);
  38812. camRight.rotation.copyFrom(this.rotation);
  38813. }
  38814. camLeft.position.copyFrom(this.position);
  38815. camRight.position.copyFrom(this.position);
  38816. break;
  38817. }
  38818. _super.prototype._updateRigCameras.call(this);
  38819. };
  38820. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  38821. if (!this._rigCamTransformMatrix) {
  38822. this._rigCamTransformMatrix = new BABYLON.Matrix();
  38823. }
  38824. var target = this.getTarget();
  38825. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  38826. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  38827. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  38828. };
  38829. TargetCamera.prototype.getClassName = function () {
  38830. return "TargetCamera";
  38831. };
  38832. __decorate([
  38833. BABYLON.serializeAsVector3()
  38834. ], TargetCamera.prototype, "rotation", void 0);
  38835. __decorate([
  38836. BABYLON.serialize()
  38837. ], TargetCamera.prototype, "speed", void 0);
  38838. __decorate([
  38839. BABYLON.serializeAsMeshReference("lockedTargetId")
  38840. ], TargetCamera.prototype, "lockedTarget", void 0);
  38841. return TargetCamera;
  38842. }(BABYLON.Camera));
  38843. BABYLON.TargetCamera = TargetCamera;
  38844. })(BABYLON || (BABYLON = {}));
  38845. //# sourceMappingURL=babylon.targetCamera.js.map
  38846. var BABYLON;
  38847. (function (BABYLON) {
  38848. var FreeCamera = /** @class */ (function (_super) {
  38849. __extends(FreeCamera, _super);
  38850. function FreeCamera(name, position, scene) {
  38851. var _this = _super.call(this, name, position, scene) || this;
  38852. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  38853. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  38854. _this.checkCollisions = false;
  38855. _this.applyGravity = false;
  38856. _this._needMoveForGravity = false;
  38857. _this._oldPosition = BABYLON.Vector3.Zero();
  38858. _this._diffPosition = BABYLON.Vector3.Zero();
  38859. _this._newPosition = BABYLON.Vector3.Zero();
  38860. // Collisions
  38861. _this._collisionMask = -1;
  38862. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  38863. if (collidedMesh === void 0) { collidedMesh = null; }
  38864. //TODO move this to the collision coordinator!
  38865. if (_this.getScene().workerCollisions)
  38866. newPosition.multiplyInPlace(_this._collider._radius);
  38867. var updatePosition = function (newPos) {
  38868. _this._newPosition.copyFrom(newPos);
  38869. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  38870. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  38871. _this.position.addInPlace(_this._diffPosition);
  38872. if (_this.onCollide && collidedMesh) {
  38873. _this.onCollide(collidedMesh);
  38874. }
  38875. }
  38876. };
  38877. updatePosition(newPosition);
  38878. };
  38879. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  38880. _this.inputs.addKeyboard().addMouse();
  38881. return _this;
  38882. }
  38883. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  38884. //-- begin properties for backward compatibility for inputs
  38885. get: function () {
  38886. var mouse = this.inputs.attached["mouse"];
  38887. if (mouse)
  38888. return mouse.angularSensibility;
  38889. return 0;
  38890. },
  38891. set: function (value) {
  38892. var mouse = this.inputs.attached["mouse"];
  38893. if (mouse)
  38894. mouse.angularSensibility = value;
  38895. },
  38896. enumerable: true,
  38897. configurable: true
  38898. });
  38899. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  38900. get: function () {
  38901. var keyboard = this.inputs.attached["keyboard"];
  38902. if (keyboard)
  38903. return keyboard.keysUp;
  38904. return [];
  38905. },
  38906. set: function (value) {
  38907. var keyboard = this.inputs.attached["keyboard"];
  38908. if (keyboard)
  38909. keyboard.keysUp = value;
  38910. },
  38911. enumerable: true,
  38912. configurable: true
  38913. });
  38914. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  38915. get: function () {
  38916. var keyboard = this.inputs.attached["keyboard"];
  38917. if (keyboard)
  38918. return keyboard.keysDown;
  38919. return [];
  38920. },
  38921. set: function (value) {
  38922. var keyboard = this.inputs.attached["keyboard"];
  38923. if (keyboard)
  38924. keyboard.keysDown = value;
  38925. },
  38926. enumerable: true,
  38927. configurable: true
  38928. });
  38929. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  38930. get: function () {
  38931. var keyboard = this.inputs.attached["keyboard"];
  38932. if (keyboard)
  38933. return keyboard.keysLeft;
  38934. return [];
  38935. },
  38936. set: function (value) {
  38937. var keyboard = this.inputs.attached["keyboard"];
  38938. if (keyboard)
  38939. keyboard.keysLeft = value;
  38940. },
  38941. enumerable: true,
  38942. configurable: true
  38943. });
  38944. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  38945. get: function () {
  38946. var keyboard = this.inputs.attached["keyboard"];
  38947. if (keyboard)
  38948. return keyboard.keysRight;
  38949. return [];
  38950. },
  38951. set: function (value) {
  38952. var keyboard = this.inputs.attached["keyboard"];
  38953. if (keyboard)
  38954. keyboard.keysRight = value;
  38955. },
  38956. enumerable: true,
  38957. configurable: true
  38958. });
  38959. // Controls
  38960. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  38961. this.inputs.attachElement(element, noPreventDefault);
  38962. };
  38963. FreeCamera.prototype.detachControl = function (element) {
  38964. this.inputs.detachElement(element);
  38965. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  38966. this.cameraRotation = new BABYLON.Vector2(0, 0);
  38967. };
  38968. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  38969. get: function () {
  38970. return this._collisionMask;
  38971. },
  38972. set: function (mask) {
  38973. this._collisionMask = !isNaN(mask) ? mask : -1;
  38974. },
  38975. enumerable: true,
  38976. configurable: true
  38977. });
  38978. FreeCamera.prototype._collideWithWorld = function (displacement) {
  38979. var globalPosition;
  38980. if (this.parent) {
  38981. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  38982. }
  38983. else {
  38984. globalPosition = this.position;
  38985. }
  38986. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  38987. this._oldPosition.addInPlace(this.ellipsoidOffset);
  38988. if (!this._collider) {
  38989. this._collider = new BABYLON.Collider();
  38990. }
  38991. this._collider._radius = this.ellipsoid;
  38992. this._collider.collisionMask = this._collisionMask;
  38993. //no need for clone, as long as gravity is not on.
  38994. var actualDisplacement = displacement;
  38995. //add gravity to the direction to prevent the dual-collision checking
  38996. if (this.applyGravity) {
  38997. //this prevents mending with cameraDirection, a global variable of the free camera class.
  38998. actualDisplacement = displacement.add(this.getScene().gravity);
  38999. }
  39000. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  39001. };
  39002. FreeCamera.prototype._checkInputs = function () {
  39003. if (!this._localDirection) {
  39004. this._localDirection = BABYLON.Vector3.Zero();
  39005. this._transformedDirection = BABYLON.Vector3.Zero();
  39006. }
  39007. this.inputs.checkInputs();
  39008. _super.prototype._checkInputs.call(this);
  39009. };
  39010. FreeCamera.prototype._decideIfNeedsToMove = function () {
  39011. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  39012. };
  39013. FreeCamera.prototype._updatePosition = function () {
  39014. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  39015. this._collideWithWorld(this.cameraDirection);
  39016. }
  39017. else {
  39018. _super.prototype._updatePosition.call(this);
  39019. }
  39020. };
  39021. FreeCamera.prototype.dispose = function () {
  39022. this.inputs.clear();
  39023. _super.prototype.dispose.call(this);
  39024. };
  39025. FreeCamera.prototype.getClassName = function () {
  39026. return "FreeCamera";
  39027. };
  39028. __decorate([
  39029. BABYLON.serializeAsVector3()
  39030. ], FreeCamera.prototype, "ellipsoid", void 0);
  39031. __decorate([
  39032. BABYLON.serializeAsVector3()
  39033. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  39034. __decorate([
  39035. BABYLON.serialize()
  39036. ], FreeCamera.prototype, "checkCollisions", void 0);
  39037. __decorate([
  39038. BABYLON.serialize()
  39039. ], FreeCamera.prototype, "applyGravity", void 0);
  39040. return FreeCamera;
  39041. }(BABYLON.TargetCamera));
  39042. BABYLON.FreeCamera = FreeCamera;
  39043. })(BABYLON || (BABYLON = {}));
  39044. //# sourceMappingURL=babylon.freeCamera.js.map
  39045. var BABYLON;
  39046. (function (BABYLON) {
  39047. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  39048. function ArcRotateCameraKeyboardMoveInput() {
  39049. this._keys = new Array();
  39050. this.keysUp = [38];
  39051. this.keysDown = [40];
  39052. this.keysLeft = [37];
  39053. this.keysRight = [39];
  39054. this.keysReset = [220];
  39055. this.panningSensibility = 50.0;
  39056. this.zoomingSensibility = 25.0;
  39057. this.useAltToZoom = true;
  39058. }
  39059. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  39060. var _this = this;
  39061. if (this._onCanvasBlurObserver) {
  39062. return;
  39063. }
  39064. this._scene = this.camera.getScene();
  39065. this._engine = this._scene.getEngine();
  39066. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  39067. _this._keys = [];
  39068. });
  39069. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  39070. var evt = info.event;
  39071. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  39072. _this._ctrlPressed = evt.ctrlKey;
  39073. _this._altPressed = evt.altKey;
  39074. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39075. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39076. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39077. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  39078. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  39079. var index = _this._keys.indexOf(evt.keyCode);
  39080. if (index === -1) {
  39081. _this._keys.push(evt.keyCode);
  39082. }
  39083. if (evt.preventDefault) {
  39084. if (!noPreventDefault) {
  39085. evt.preventDefault();
  39086. }
  39087. }
  39088. }
  39089. }
  39090. else {
  39091. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39092. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39093. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39094. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  39095. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  39096. var index = _this._keys.indexOf(evt.keyCode);
  39097. if (index >= 0) {
  39098. _this._keys.splice(index, 1);
  39099. }
  39100. if (evt.preventDefault) {
  39101. if (!noPreventDefault) {
  39102. evt.preventDefault();
  39103. }
  39104. }
  39105. }
  39106. }
  39107. });
  39108. };
  39109. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  39110. if (this._scene) {
  39111. if (this._onKeyboardObserver) {
  39112. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  39113. }
  39114. if (this._onCanvasBlurObserver) {
  39115. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  39116. }
  39117. this._onKeyboardObserver = null;
  39118. this._onCanvasBlurObserver = null;
  39119. }
  39120. this._keys = [];
  39121. };
  39122. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  39123. if (this._onKeyboardObserver) {
  39124. var camera = this.camera;
  39125. for (var index = 0; index < this._keys.length; index++) {
  39126. var keyCode = this._keys[index];
  39127. if (this.keysLeft.indexOf(keyCode) !== -1) {
  39128. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39129. camera.inertialPanningX -= 1 / this.panningSensibility;
  39130. }
  39131. else {
  39132. camera.inertialAlphaOffset -= 0.01;
  39133. }
  39134. }
  39135. else if (this.keysUp.indexOf(keyCode) !== -1) {
  39136. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39137. camera.inertialPanningY += 1 / this.panningSensibility;
  39138. }
  39139. else if (this._altPressed && this.useAltToZoom) {
  39140. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  39141. }
  39142. else {
  39143. camera.inertialBetaOffset -= 0.01;
  39144. }
  39145. }
  39146. else if (this.keysRight.indexOf(keyCode) !== -1) {
  39147. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39148. camera.inertialPanningX += 1 / this.panningSensibility;
  39149. }
  39150. else {
  39151. camera.inertialAlphaOffset += 0.01;
  39152. }
  39153. }
  39154. else if (this.keysDown.indexOf(keyCode) !== -1) {
  39155. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39156. camera.inertialPanningY -= 1 / this.panningSensibility;
  39157. }
  39158. else if (this._altPressed && this.useAltToZoom) {
  39159. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  39160. }
  39161. else {
  39162. camera.inertialBetaOffset += 0.01;
  39163. }
  39164. }
  39165. else if (this.keysReset.indexOf(keyCode) !== -1) {
  39166. camera.restoreState();
  39167. }
  39168. }
  39169. }
  39170. };
  39171. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  39172. return "ArcRotateCameraKeyboardMoveInput";
  39173. };
  39174. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  39175. return "keyboard";
  39176. };
  39177. __decorate([
  39178. BABYLON.serialize()
  39179. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  39180. __decorate([
  39181. BABYLON.serialize()
  39182. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  39183. __decorate([
  39184. BABYLON.serialize()
  39185. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  39186. __decorate([
  39187. BABYLON.serialize()
  39188. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  39189. __decorate([
  39190. BABYLON.serialize()
  39191. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  39192. __decorate([
  39193. BABYLON.serialize()
  39194. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  39195. __decorate([
  39196. BABYLON.serialize()
  39197. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  39198. __decorate([
  39199. BABYLON.serialize()
  39200. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  39201. return ArcRotateCameraKeyboardMoveInput;
  39202. }());
  39203. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  39204. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  39205. })(BABYLON || (BABYLON = {}));
  39206. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  39207. var BABYLON;
  39208. (function (BABYLON) {
  39209. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  39210. function ArcRotateCameraMouseWheelInput() {
  39211. this.wheelPrecision = 3.0;
  39212. /**
  39213. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  39214. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  39215. */
  39216. this.wheelDeltaPercentage = 0;
  39217. }
  39218. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  39219. var _this = this;
  39220. this._wheel = function (p, s) {
  39221. //sanity check - this should be a PointerWheel event.
  39222. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  39223. return;
  39224. var event = p.event;
  39225. var delta = 0;
  39226. if (event.wheelDelta) {
  39227. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  39228. }
  39229. else if (event.detail) {
  39230. delta = -event.detail / _this.wheelPrecision;
  39231. }
  39232. if (delta)
  39233. _this.camera.inertialRadiusOffset += delta;
  39234. if (event.preventDefault) {
  39235. if (!noPreventDefault) {
  39236. event.preventDefault();
  39237. }
  39238. }
  39239. };
  39240. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  39241. };
  39242. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  39243. if (this._observer && element) {
  39244. this.camera.getScene().onPointerObservable.remove(this._observer);
  39245. this._observer = null;
  39246. this._wheel = null;
  39247. }
  39248. };
  39249. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  39250. return "ArcRotateCameraMouseWheelInput";
  39251. };
  39252. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  39253. return "mousewheel";
  39254. };
  39255. __decorate([
  39256. BABYLON.serialize()
  39257. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  39258. __decorate([
  39259. BABYLON.serialize()
  39260. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  39261. return ArcRotateCameraMouseWheelInput;
  39262. }());
  39263. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  39264. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  39265. })(BABYLON || (BABYLON = {}));
  39266. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  39267. var BABYLON;
  39268. (function (BABYLON) {
  39269. var ArcRotateCameraPointersInput = /** @class */ (function () {
  39270. function ArcRotateCameraPointersInput() {
  39271. this.buttons = [0, 1, 2];
  39272. this.angularSensibilityX = 1000.0;
  39273. this.angularSensibilityY = 1000.0;
  39274. this.pinchPrecision = 12.0;
  39275. /**
  39276. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  39277. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  39278. */
  39279. this.pinchDeltaPercentage = 0;
  39280. this.panningSensibility = 1000.0;
  39281. this.multiTouchPanning = true;
  39282. this.multiTouchPanAndZoom = true;
  39283. this._isPanClick = false;
  39284. this.pinchInwards = true;
  39285. }
  39286. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  39287. var _this = this;
  39288. var engine = this.camera.getEngine();
  39289. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  39290. var pointA = null;
  39291. var pointB = null;
  39292. var previousPinchSquaredDistance = 0;
  39293. var initialDistance = 0;
  39294. var twoFingerActivityCount = 0;
  39295. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  39296. this._pointerInput = function (p, s) {
  39297. var evt = p.event;
  39298. var isTouch = p.event.pointerType === "touch";
  39299. if (engine.isInVRExclusivePointerMode) {
  39300. return;
  39301. }
  39302. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  39303. return;
  39304. }
  39305. var srcElement = (evt.srcElement || evt.target);
  39306. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  39307. try {
  39308. srcElement.setPointerCapture(evt.pointerId);
  39309. }
  39310. catch (e) {
  39311. //Nothing to do with the error. Execution will continue.
  39312. }
  39313. // Manage panning with pan button click
  39314. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  39315. // manage pointers
  39316. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  39317. if (pointA === null) {
  39318. pointA = cacheSoloPointer;
  39319. }
  39320. else if (pointB === null) {
  39321. pointB = cacheSoloPointer;
  39322. }
  39323. if (!noPreventDefault) {
  39324. evt.preventDefault();
  39325. element.focus();
  39326. }
  39327. }
  39328. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  39329. _this.camera.restoreState();
  39330. }
  39331. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  39332. try {
  39333. srcElement.releasePointerCapture(evt.pointerId);
  39334. }
  39335. catch (e) {
  39336. //Nothing to do with the error.
  39337. }
  39338. cacheSoloPointer = null;
  39339. previousPinchSquaredDistance = 0;
  39340. previousMultiTouchPanPosition.isPaning = false;
  39341. previousMultiTouchPanPosition.isPinching = false;
  39342. twoFingerActivityCount = 0;
  39343. initialDistance = 0;
  39344. if (!isTouch) {
  39345. pointB = null; // Mouse and pen are mono pointer
  39346. }
  39347. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  39348. //but emptying completly pointers collection is required to fix a bug on iPhone :
  39349. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  39350. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  39351. if (engine.badOS) {
  39352. pointA = pointB = null;
  39353. }
  39354. else {
  39355. //only remove the impacted pointer in case of multitouch allowing on most
  39356. //platforms switching from rotate to zoom and pan seamlessly.
  39357. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  39358. pointA = pointB;
  39359. pointB = null;
  39360. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  39361. }
  39362. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  39363. pointB = null;
  39364. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  39365. }
  39366. else {
  39367. pointA = pointB = null;
  39368. }
  39369. }
  39370. if (!noPreventDefault) {
  39371. evt.preventDefault();
  39372. }
  39373. }
  39374. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  39375. if (!noPreventDefault) {
  39376. evt.preventDefault();
  39377. }
  39378. // One button down
  39379. if (pointA && pointB === null && cacheSoloPointer) {
  39380. if (_this.panningSensibility !== 0 &&
  39381. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  39382. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  39383. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  39384. }
  39385. else {
  39386. var offsetX = evt.clientX - cacheSoloPointer.x;
  39387. var offsetY = evt.clientY - cacheSoloPointer.y;
  39388. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  39389. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  39390. }
  39391. cacheSoloPointer.x = evt.clientX;
  39392. cacheSoloPointer.y = evt.clientY;
  39393. }
  39394. else if (pointA && pointB) {
  39395. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  39396. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  39397. ed.x = evt.clientX;
  39398. ed.y = evt.clientY;
  39399. var direction = _this.pinchInwards ? 1 : -1;
  39400. var distX = pointA.x - pointB.x;
  39401. var distY = pointA.y - pointB.y;
  39402. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  39403. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  39404. if (previousPinchSquaredDistance === 0) {
  39405. initialDistance = pinchDistance;
  39406. previousPinchSquaredDistance = pinchSquaredDistance;
  39407. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  39408. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  39409. return;
  39410. }
  39411. if (_this.multiTouchPanAndZoom) {
  39412. if (_this.pinchDeltaPercentage) {
  39413. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  39414. }
  39415. else {
  39416. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  39417. (_this.pinchPrecision *
  39418. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  39419. direction);
  39420. }
  39421. if (_this.panningSensibility !== 0) {
  39422. var pointersCenterX = (pointA.x + pointB.x) / 2;
  39423. var pointersCenterY = (pointA.y + pointB.y) / 2;
  39424. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  39425. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  39426. previousMultiTouchPanPosition.x = pointersCenterX;
  39427. previousMultiTouchPanPosition.y = pointersCenterY;
  39428. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  39429. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  39430. }
  39431. }
  39432. else {
  39433. twoFingerActivityCount++;
  39434. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  39435. if (_this.pinchDeltaPercentage) {
  39436. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  39437. }
  39438. else {
  39439. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  39440. (_this.pinchPrecision *
  39441. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  39442. direction);
  39443. }
  39444. previousMultiTouchPanPosition.isPaning = false;
  39445. previousMultiTouchPanPosition.isPinching = true;
  39446. }
  39447. else {
  39448. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  39449. if (!previousMultiTouchPanPosition.isPaning) {
  39450. previousMultiTouchPanPosition.isPaning = true;
  39451. previousMultiTouchPanPosition.isPinching = false;
  39452. previousMultiTouchPanPosition.x = ed.x;
  39453. previousMultiTouchPanPosition.y = ed.y;
  39454. return;
  39455. }
  39456. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  39457. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  39458. }
  39459. }
  39460. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  39461. previousMultiTouchPanPosition.x = ed.x;
  39462. previousMultiTouchPanPosition.y = ed.y;
  39463. }
  39464. }
  39465. previousPinchSquaredDistance = pinchSquaredDistance;
  39466. }
  39467. }
  39468. };
  39469. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  39470. this._onContextMenu = function (evt) {
  39471. evt.preventDefault();
  39472. };
  39473. if (!this.camera._useCtrlForPanning) {
  39474. element.addEventListener("contextmenu", this._onContextMenu, false);
  39475. }
  39476. this._onLostFocus = function () {
  39477. //this._keys = [];
  39478. pointA = pointB = null;
  39479. previousPinchSquaredDistance = 0;
  39480. previousMultiTouchPanPosition.isPaning = false;
  39481. previousMultiTouchPanPosition.isPinching = false;
  39482. twoFingerActivityCount = 0;
  39483. cacheSoloPointer = null;
  39484. initialDistance = 0;
  39485. };
  39486. this._onMouseMove = function (evt) {
  39487. if (!engine.isPointerLock) {
  39488. return;
  39489. }
  39490. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  39491. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  39492. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  39493. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  39494. if (!noPreventDefault) {
  39495. evt.preventDefault();
  39496. }
  39497. };
  39498. this._onGestureStart = function (e) {
  39499. if (window.MSGesture === undefined) {
  39500. return;
  39501. }
  39502. if (!_this._MSGestureHandler) {
  39503. _this._MSGestureHandler = new MSGesture();
  39504. _this._MSGestureHandler.target = element;
  39505. }
  39506. _this._MSGestureHandler.addPointer(e.pointerId);
  39507. };
  39508. this._onGesture = function (e) {
  39509. _this.camera.radius *= e.scale;
  39510. if (e.preventDefault) {
  39511. if (!noPreventDefault) {
  39512. e.stopPropagation();
  39513. e.preventDefault();
  39514. }
  39515. }
  39516. };
  39517. element.addEventListener("mousemove", this._onMouseMove, false);
  39518. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  39519. element.addEventListener("MSGestureChange", this._onGesture, false);
  39520. BABYLON.Tools.RegisterTopRootEvents([
  39521. { name: "blur", handler: this._onLostFocus }
  39522. ]);
  39523. };
  39524. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  39525. if (this._onLostFocus) {
  39526. BABYLON.Tools.UnregisterTopRootEvents([
  39527. { name: "blur", handler: this._onLostFocus }
  39528. ]);
  39529. }
  39530. if (element && this._observer) {
  39531. this.camera.getScene().onPointerObservable.remove(this._observer);
  39532. this._observer = null;
  39533. if (this._onContextMenu) {
  39534. element.removeEventListener("contextmenu", this._onContextMenu);
  39535. }
  39536. if (this._onMouseMove) {
  39537. element.removeEventListener("mousemove", this._onMouseMove);
  39538. }
  39539. if (this._onGestureStart) {
  39540. element.removeEventListener("MSPointerDown", this._onGestureStart);
  39541. }
  39542. if (this._onGesture) {
  39543. element.removeEventListener("MSGestureChange", this._onGesture);
  39544. }
  39545. this._isPanClick = false;
  39546. this.pinchInwards = true;
  39547. this._onMouseMove = null;
  39548. this._onGestureStart = null;
  39549. this._onGesture = null;
  39550. this._MSGestureHandler = null;
  39551. this._onLostFocus = null;
  39552. this._onContextMenu = null;
  39553. }
  39554. };
  39555. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  39556. return "ArcRotateCameraPointersInput";
  39557. };
  39558. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  39559. return "pointers";
  39560. };
  39561. __decorate([
  39562. BABYLON.serialize()
  39563. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  39564. __decorate([
  39565. BABYLON.serialize()
  39566. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  39567. __decorate([
  39568. BABYLON.serialize()
  39569. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  39570. __decorate([
  39571. BABYLON.serialize()
  39572. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  39573. __decorate([
  39574. BABYLON.serialize()
  39575. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  39576. __decorate([
  39577. BABYLON.serialize()
  39578. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  39579. __decorate([
  39580. BABYLON.serialize()
  39581. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  39582. __decorate([
  39583. BABYLON.serialize()
  39584. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  39585. return ArcRotateCameraPointersInput;
  39586. }());
  39587. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  39588. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  39589. })(BABYLON || (BABYLON = {}));
  39590. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  39591. var BABYLON;
  39592. (function (BABYLON) {
  39593. var ArcRotateCamera = /** @class */ (function (_super) {
  39594. __extends(ArcRotateCamera, _super);
  39595. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  39596. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  39597. _this.inertialAlphaOffset = 0;
  39598. _this.inertialBetaOffset = 0;
  39599. _this.inertialRadiusOffset = 0;
  39600. _this.lowerAlphaLimit = null;
  39601. _this.upperAlphaLimit = null;
  39602. _this.lowerBetaLimit = 0.01;
  39603. _this.upperBetaLimit = Math.PI;
  39604. _this.lowerRadiusLimit = null;
  39605. _this.upperRadiusLimit = null;
  39606. _this.inertialPanningX = 0;
  39607. _this.inertialPanningY = 0;
  39608. _this.pinchToPanMaxDistance = 20;
  39609. _this.panningDistanceLimit = null;
  39610. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  39611. _this.panningInertia = 0.9;
  39612. //-- end properties for backward compatibility for inputs
  39613. _this.zoomOnFactor = 1;
  39614. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  39615. _this.allowUpsideDown = true;
  39616. _this._viewMatrix = new BABYLON.Matrix();
  39617. // Panning
  39618. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  39619. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  39620. _this.checkCollisions = false;
  39621. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  39622. _this._previousPosition = BABYLON.Vector3.Zero();
  39623. _this._collisionVelocity = BABYLON.Vector3.Zero();
  39624. _this._newPosition = BABYLON.Vector3.Zero();
  39625. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  39626. if (collidedMesh === void 0) { collidedMesh = null; }
  39627. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  39628. newPosition.multiplyInPlace(_this._collider._radius);
  39629. }
  39630. if (!collidedMesh) {
  39631. _this._previousPosition.copyFrom(_this.position);
  39632. }
  39633. else {
  39634. _this.setPosition(newPosition);
  39635. if (_this.onCollide) {
  39636. _this.onCollide(collidedMesh);
  39637. }
  39638. }
  39639. // Recompute because of constraints
  39640. var cosa = Math.cos(_this.alpha);
  39641. var sina = Math.sin(_this.alpha);
  39642. var cosb = Math.cos(_this.beta);
  39643. var sinb = Math.sin(_this.beta);
  39644. if (sinb === 0) {
  39645. sinb = 0.0001;
  39646. }
  39647. var target = _this._getTargetPosition();
  39648. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  39649. _this.position.copyFrom(_this._newPosition);
  39650. var up = _this.upVector;
  39651. if (_this.allowUpsideDown && _this.beta < 0) {
  39652. up = up.clone();
  39653. up = up.negate();
  39654. }
  39655. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  39656. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  39657. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  39658. _this._collisionTriggered = false;
  39659. };
  39660. _this._target = BABYLON.Vector3.Zero();
  39661. if (target) {
  39662. _this.setTarget(target);
  39663. }
  39664. _this.alpha = alpha;
  39665. _this.beta = beta;
  39666. _this.radius = radius;
  39667. _this.getViewMatrix();
  39668. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  39669. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  39670. return _this;
  39671. }
  39672. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  39673. get: function () {
  39674. return this._target;
  39675. },
  39676. set: function (value) {
  39677. this.setTarget(value);
  39678. },
  39679. enumerable: true,
  39680. configurable: true
  39681. });
  39682. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  39683. //-- begin properties for backward compatibility for inputs
  39684. get: function () {
  39685. var pointers = this.inputs.attached["pointers"];
  39686. if (pointers)
  39687. return pointers.angularSensibilityX;
  39688. return 0;
  39689. },
  39690. set: function (value) {
  39691. var pointers = this.inputs.attached["pointers"];
  39692. if (pointers) {
  39693. pointers.angularSensibilityX = value;
  39694. }
  39695. },
  39696. enumerable: true,
  39697. configurable: true
  39698. });
  39699. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  39700. get: function () {
  39701. var pointers = this.inputs.attached["pointers"];
  39702. if (pointers)
  39703. return pointers.angularSensibilityY;
  39704. return 0;
  39705. },
  39706. set: function (value) {
  39707. var pointers = this.inputs.attached["pointers"];
  39708. if (pointers) {
  39709. pointers.angularSensibilityY = value;
  39710. }
  39711. },
  39712. enumerable: true,
  39713. configurable: true
  39714. });
  39715. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  39716. get: function () {
  39717. var pointers = this.inputs.attached["pointers"];
  39718. if (pointers)
  39719. return pointers.pinchPrecision;
  39720. return 0;
  39721. },
  39722. set: function (value) {
  39723. var pointers = this.inputs.attached["pointers"];
  39724. if (pointers) {
  39725. pointers.pinchPrecision = value;
  39726. }
  39727. },
  39728. enumerable: true,
  39729. configurable: true
  39730. });
  39731. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  39732. get: function () {
  39733. var pointers = this.inputs.attached["pointers"];
  39734. if (pointers)
  39735. return pointers.pinchDeltaPercentage;
  39736. return 0;
  39737. },
  39738. set: function (value) {
  39739. var pointers = this.inputs.attached["pointers"];
  39740. if (pointers) {
  39741. pointers.pinchDeltaPercentage = value;
  39742. }
  39743. },
  39744. enumerable: true,
  39745. configurable: true
  39746. });
  39747. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  39748. get: function () {
  39749. var pointers = this.inputs.attached["pointers"];
  39750. if (pointers)
  39751. return pointers.panningSensibility;
  39752. return 0;
  39753. },
  39754. set: function (value) {
  39755. var pointers = this.inputs.attached["pointers"];
  39756. if (pointers) {
  39757. pointers.panningSensibility = value;
  39758. }
  39759. },
  39760. enumerable: true,
  39761. configurable: true
  39762. });
  39763. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  39764. get: function () {
  39765. var keyboard = this.inputs.attached["keyboard"];
  39766. if (keyboard)
  39767. return keyboard.keysUp;
  39768. return [];
  39769. },
  39770. set: function (value) {
  39771. var keyboard = this.inputs.attached["keyboard"];
  39772. if (keyboard)
  39773. keyboard.keysUp = value;
  39774. },
  39775. enumerable: true,
  39776. configurable: true
  39777. });
  39778. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  39779. get: function () {
  39780. var keyboard = this.inputs.attached["keyboard"];
  39781. if (keyboard)
  39782. return keyboard.keysDown;
  39783. return [];
  39784. },
  39785. set: function (value) {
  39786. var keyboard = this.inputs.attached["keyboard"];
  39787. if (keyboard)
  39788. keyboard.keysDown = value;
  39789. },
  39790. enumerable: true,
  39791. configurable: true
  39792. });
  39793. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  39794. get: function () {
  39795. var keyboard = this.inputs.attached["keyboard"];
  39796. if (keyboard)
  39797. return keyboard.keysLeft;
  39798. return [];
  39799. },
  39800. set: function (value) {
  39801. var keyboard = this.inputs.attached["keyboard"];
  39802. if (keyboard)
  39803. keyboard.keysLeft = value;
  39804. },
  39805. enumerable: true,
  39806. configurable: true
  39807. });
  39808. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  39809. get: function () {
  39810. var keyboard = this.inputs.attached["keyboard"];
  39811. if (keyboard)
  39812. return keyboard.keysRight;
  39813. return [];
  39814. },
  39815. set: function (value) {
  39816. var keyboard = this.inputs.attached["keyboard"];
  39817. if (keyboard)
  39818. keyboard.keysRight = value;
  39819. },
  39820. enumerable: true,
  39821. configurable: true
  39822. });
  39823. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  39824. get: function () {
  39825. var mousewheel = this.inputs.attached["mousewheel"];
  39826. if (mousewheel)
  39827. return mousewheel.wheelPrecision;
  39828. return 0;
  39829. },
  39830. set: function (value) {
  39831. var mousewheel = this.inputs.attached["mousewheel"];
  39832. if (mousewheel)
  39833. mousewheel.wheelPrecision = value;
  39834. },
  39835. enumerable: true,
  39836. configurable: true
  39837. });
  39838. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  39839. get: function () {
  39840. var mousewheel = this.inputs.attached["mousewheel"];
  39841. if (mousewheel)
  39842. return mousewheel.wheelDeltaPercentage;
  39843. return 0;
  39844. },
  39845. set: function (value) {
  39846. var mousewheel = this.inputs.attached["mousewheel"];
  39847. if (mousewheel)
  39848. mousewheel.wheelDeltaPercentage = value;
  39849. },
  39850. enumerable: true,
  39851. configurable: true
  39852. });
  39853. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  39854. get: function () {
  39855. return this._bouncingBehavior;
  39856. },
  39857. enumerable: true,
  39858. configurable: true
  39859. });
  39860. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  39861. get: function () {
  39862. return this._bouncingBehavior != null;
  39863. },
  39864. set: function (value) {
  39865. if (value === this.useBouncingBehavior) {
  39866. return;
  39867. }
  39868. if (value) {
  39869. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  39870. this.addBehavior(this._bouncingBehavior);
  39871. }
  39872. else if (this._bouncingBehavior) {
  39873. this.removeBehavior(this._bouncingBehavior);
  39874. this._bouncingBehavior = null;
  39875. }
  39876. },
  39877. enumerable: true,
  39878. configurable: true
  39879. });
  39880. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  39881. get: function () {
  39882. return this._framingBehavior;
  39883. },
  39884. enumerable: true,
  39885. configurable: true
  39886. });
  39887. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  39888. get: function () {
  39889. return this._framingBehavior != null;
  39890. },
  39891. set: function (value) {
  39892. if (value === this.useFramingBehavior) {
  39893. return;
  39894. }
  39895. if (value) {
  39896. this._framingBehavior = new BABYLON.FramingBehavior();
  39897. this.addBehavior(this._framingBehavior);
  39898. }
  39899. else if (this._framingBehavior) {
  39900. this.removeBehavior(this._framingBehavior);
  39901. this._framingBehavior = null;
  39902. }
  39903. },
  39904. enumerable: true,
  39905. configurable: true
  39906. });
  39907. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  39908. get: function () {
  39909. return this._autoRotationBehavior;
  39910. },
  39911. enumerable: true,
  39912. configurable: true
  39913. });
  39914. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  39915. get: function () {
  39916. return this._autoRotationBehavior != null;
  39917. },
  39918. set: function (value) {
  39919. if (value === this.useAutoRotationBehavior) {
  39920. return;
  39921. }
  39922. if (value) {
  39923. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  39924. this.addBehavior(this._autoRotationBehavior);
  39925. }
  39926. else if (this._autoRotationBehavior) {
  39927. this.removeBehavior(this._autoRotationBehavior);
  39928. this._autoRotationBehavior = null;
  39929. }
  39930. },
  39931. enumerable: true,
  39932. configurable: true
  39933. });
  39934. // Cache
  39935. ArcRotateCamera.prototype._initCache = function () {
  39936. _super.prototype._initCache.call(this);
  39937. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  39938. this._cache.alpha = undefined;
  39939. this._cache.beta = undefined;
  39940. this._cache.radius = undefined;
  39941. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  39942. };
  39943. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  39944. if (!ignoreParentClass) {
  39945. _super.prototype._updateCache.call(this);
  39946. }
  39947. this._cache._target.copyFrom(this._getTargetPosition());
  39948. this._cache.alpha = this.alpha;
  39949. this._cache.beta = this.beta;
  39950. this._cache.radius = this.radius;
  39951. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  39952. };
  39953. ArcRotateCamera.prototype._getTargetPosition = function () {
  39954. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  39955. var pos = this._targetHost.getAbsolutePosition();
  39956. if (this._targetBoundingCenter) {
  39957. pos.addToRef(this._targetBoundingCenter, this._target);
  39958. }
  39959. else {
  39960. this._target.copyFrom(pos);
  39961. }
  39962. }
  39963. var lockedTargetPosition = this._getLockedTargetPosition();
  39964. if (lockedTargetPosition) {
  39965. return lockedTargetPosition;
  39966. }
  39967. return this._target;
  39968. };
  39969. ArcRotateCamera.prototype.storeState = function () {
  39970. this._storedAlpha = this.alpha;
  39971. this._storedBeta = this.beta;
  39972. this._storedRadius = this.radius;
  39973. this._storedTarget = this._getTargetPosition().clone();
  39974. return _super.prototype.storeState.call(this);
  39975. };
  39976. /**
  39977. * Restored camera state. You must call storeState() first
  39978. */
  39979. ArcRotateCamera.prototype._restoreStateValues = function () {
  39980. if (!_super.prototype._restoreStateValues.call(this)) {
  39981. return false;
  39982. }
  39983. this.alpha = this._storedAlpha;
  39984. this.beta = this._storedBeta;
  39985. this.radius = this._storedRadius;
  39986. this.setTarget(this._storedTarget.clone());
  39987. this.inertialAlphaOffset = 0;
  39988. this.inertialBetaOffset = 0;
  39989. this.inertialRadiusOffset = 0;
  39990. this.inertialPanningX = 0;
  39991. this.inertialPanningY = 0;
  39992. return true;
  39993. };
  39994. // Synchronized
  39995. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  39996. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  39997. return false;
  39998. return this._cache._target.equals(this._getTargetPosition())
  39999. && this._cache.alpha === this.alpha
  40000. && this._cache.beta === this.beta
  40001. && this._cache.radius === this.radius
  40002. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  40003. };
  40004. // Methods
  40005. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  40006. var _this = this;
  40007. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  40008. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  40009. this._useCtrlForPanning = useCtrlForPanning;
  40010. this._panningMouseButton = panningMouseButton;
  40011. this.inputs.attachElement(element, noPreventDefault);
  40012. this._reset = function () {
  40013. _this.inertialAlphaOffset = 0;
  40014. _this.inertialBetaOffset = 0;
  40015. _this.inertialRadiusOffset = 0;
  40016. _this.inertialPanningX = 0;
  40017. _this.inertialPanningY = 0;
  40018. };
  40019. };
  40020. ArcRotateCamera.prototype.detachControl = function (element) {
  40021. this.inputs.detachElement(element);
  40022. if (this._reset) {
  40023. this._reset();
  40024. }
  40025. };
  40026. ArcRotateCamera.prototype._checkInputs = function () {
  40027. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  40028. if (this._collisionTriggered) {
  40029. return;
  40030. }
  40031. this.inputs.checkInputs();
  40032. // Inertia
  40033. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  40034. if (this.getScene().useRightHandedSystem) {
  40035. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  40036. }
  40037. else {
  40038. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  40039. }
  40040. this.beta += this.inertialBetaOffset;
  40041. this.radius -= this.inertialRadiusOffset;
  40042. this.inertialAlphaOffset *= this.inertia;
  40043. this.inertialBetaOffset *= this.inertia;
  40044. this.inertialRadiusOffset *= this.inertia;
  40045. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  40046. this.inertialAlphaOffset = 0;
  40047. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  40048. this.inertialBetaOffset = 0;
  40049. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  40050. this.inertialRadiusOffset = 0;
  40051. }
  40052. // Panning inertia
  40053. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  40054. if (!this._localDirection) {
  40055. this._localDirection = BABYLON.Vector3.Zero();
  40056. this._transformedDirection = BABYLON.Vector3.Zero();
  40057. }
  40058. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  40059. this._localDirection.multiplyInPlace(this.panningAxis);
  40060. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  40061. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  40062. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  40063. if (!this.panningAxis.y) {
  40064. this._transformedDirection.y = 0;
  40065. }
  40066. if (!this._targetHost) {
  40067. if (this.panningDistanceLimit) {
  40068. this._transformedDirection.addInPlace(this._target);
  40069. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  40070. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  40071. this._target.copyFrom(this._transformedDirection);
  40072. }
  40073. }
  40074. else {
  40075. this._target.addInPlace(this._transformedDirection);
  40076. }
  40077. }
  40078. this.inertialPanningX *= this.panningInertia;
  40079. this.inertialPanningY *= this.panningInertia;
  40080. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  40081. this.inertialPanningX = 0;
  40082. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  40083. this.inertialPanningY = 0;
  40084. }
  40085. // Limits
  40086. this._checkLimits();
  40087. _super.prototype._checkInputs.call(this);
  40088. };
  40089. ArcRotateCamera.prototype._checkLimits = function () {
  40090. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  40091. if (this.allowUpsideDown && this.beta > Math.PI) {
  40092. this.beta = this.beta - (2 * Math.PI);
  40093. }
  40094. }
  40095. else {
  40096. if (this.beta < this.lowerBetaLimit) {
  40097. this.beta = this.lowerBetaLimit;
  40098. }
  40099. }
  40100. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  40101. if (this.allowUpsideDown && this.beta < -Math.PI) {
  40102. this.beta = this.beta + (2 * Math.PI);
  40103. }
  40104. }
  40105. else {
  40106. if (this.beta > this.upperBetaLimit) {
  40107. this.beta = this.upperBetaLimit;
  40108. }
  40109. }
  40110. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  40111. this.alpha = this.lowerAlphaLimit;
  40112. }
  40113. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  40114. this.alpha = this.upperAlphaLimit;
  40115. }
  40116. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  40117. this.radius = this.lowerRadiusLimit;
  40118. }
  40119. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  40120. this.radius = this.upperRadiusLimit;
  40121. }
  40122. };
  40123. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  40124. var radiusv3 = this.position.subtract(this._getTargetPosition());
  40125. this.radius = radiusv3.length();
  40126. if (this.radius === 0) {
  40127. this.radius = 0.0001; // Just to avoid division by zero
  40128. }
  40129. // Alpha
  40130. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  40131. if (radiusv3.z < 0) {
  40132. this.alpha = 2 * Math.PI - this.alpha;
  40133. }
  40134. // Beta
  40135. this.beta = Math.acos(radiusv3.y / this.radius);
  40136. this._checkLimits();
  40137. };
  40138. ArcRotateCamera.prototype.setPosition = function (position) {
  40139. if (this.position.equals(position)) {
  40140. return;
  40141. }
  40142. this.position.copyFrom(position);
  40143. this.rebuildAnglesAndRadius();
  40144. };
  40145. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  40146. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  40147. if (allowSamePosition === void 0) { allowSamePosition = false; }
  40148. if (target.getBoundingInfo) {
  40149. if (toBoundingCenter) {
  40150. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  40151. }
  40152. else {
  40153. this._targetBoundingCenter = null;
  40154. }
  40155. this._targetHost = target;
  40156. this._target = this._getTargetPosition();
  40157. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  40158. }
  40159. else {
  40160. var newTarget = target;
  40161. var currentTarget = this._getTargetPosition();
  40162. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  40163. return;
  40164. }
  40165. this._targetHost = null;
  40166. this._target = newTarget;
  40167. this._targetBoundingCenter = null;
  40168. this.onMeshTargetChangedObservable.notifyObservers(null);
  40169. }
  40170. this.rebuildAnglesAndRadius();
  40171. };
  40172. ArcRotateCamera.prototype._getViewMatrix = function () {
  40173. // Compute
  40174. var cosa = Math.cos(this.alpha);
  40175. var sina = Math.sin(this.alpha);
  40176. var cosb = Math.cos(this.beta);
  40177. var sinb = Math.sin(this.beta);
  40178. if (sinb === 0) {
  40179. sinb = 0.0001;
  40180. }
  40181. var target = this._getTargetPosition();
  40182. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  40183. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  40184. if (!this._collider) {
  40185. this._collider = new BABYLON.Collider();
  40186. }
  40187. this._collider._radius = this.collisionRadius;
  40188. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  40189. this._collisionTriggered = true;
  40190. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  40191. }
  40192. else {
  40193. this.position.copyFrom(this._newPosition);
  40194. var up = this.upVector;
  40195. if (this.allowUpsideDown && sinb < 0) {
  40196. up = up.clone();
  40197. up = up.negate();
  40198. }
  40199. if (this.getScene().useRightHandedSystem) {
  40200. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  40201. }
  40202. else {
  40203. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  40204. }
  40205. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  40206. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  40207. }
  40208. this._currentTarget = target;
  40209. return this._viewMatrix;
  40210. };
  40211. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  40212. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  40213. meshes = meshes || this.getScene().meshes;
  40214. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  40215. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  40216. this.radius = distance * this.zoomOnFactor;
  40217. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  40218. };
  40219. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  40220. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  40221. var meshesOrMinMaxVector;
  40222. var distance;
  40223. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  40224. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  40225. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  40226. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  40227. }
  40228. else {
  40229. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  40230. meshesOrMinMaxVector = minMaxVectorAndDistance;
  40231. distance = minMaxVectorAndDistance.distance;
  40232. }
  40233. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  40234. if (!doNotUpdateMaxZ) {
  40235. this.maxZ = distance * 2;
  40236. }
  40237. };
  40238. /**
  40239. * @override
  40240. * Override Camera.createRigCamera
  40241. */
  40242. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  40243. var alphaShift = 0;
  40244. switch (this.cameraRigMode) {
  40245. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  40246. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  40247. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  40248. case BABYLON.Camera.RIG_MODE_VR:
  40249. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  40250. break;
  40251. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  40252. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  40253. break;
  40254. }
  40255. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  40256. rigCam._cameraRigParams = {};
  40257. return rigCam;
  40258. };
  40259. /**
  40260. * @override
  40261. * Override Camera._updateRigCameras
  40262. */
  40263. ArcRotateCamera.prototype._updateRigCameras = function () {
  40264. var camLeft = this._rigCameras[0];
  40265. var camRight = this._rigCameras[1];
  40266. camLeft.beta = camRight.beta = this.beta;
  40267. camLeft.radius = camRight.radius = this.radius;
  40268. switch (this.cameraRigMode) {
  40269. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  40270. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  40271. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  40272. case BABYLON.Camera.RIG_MODE_VR:
  40273. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  40274. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  40275. break;
  40276. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  40277. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  40278. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  40279. break;
  40280. }
  40281. _super.prototype._updateRigCameras.call(this);
  40282. };
  40283. ArcRotateCamera.prototype.dispose = function () {
  40284. this.inputs.clear();
  40285. _super.prototype.dispose.call(this);
  40286. };
  40287. ArcRotateCamera.prototype.getClassName = function () {
  40288. return "ArcRotateCamera";
  40289. };
  40290. __decorate([
  40291. BABYLON.serialize()
  40292. ], ArcRotateCamera.prototype, "alpha", void 0);
  40293. __decorate([
  40294. BABYLON.serialize()
  40295. ], ArcRotateCamera.prototype, "beta", void 0);
  40296. __decorate([
  40297. BABYLON.serialize()
  40298. ], ArcRotateCamera.prototype, "radius", void 0);
  40299. __decorate([
  40300. BABYLON.serializeAsVector3("target")
  40301. ], ArcRotateCamera.prototype, "_target", void 0);
  40302. __decorate([
  40303. BABYLON.serialize()
  40304. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  40305. __decorate([
  40306. BABYLON.serialize()
  40307. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  40308. __decorate([
  40309. BABYLON.serialize()
  40310. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  40311. __decorate([
  40312. BABYLON.serialize()
  40313. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  40314. __decorate([
  40315. BABYLON.serialize()
  40316. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  40317. __decorate([
  40318. BABYLON.serialize()
  40319. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  40320. __decorate([
  40321. BABYLON.serialize()
  40322. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  40323. __decorate([
  40324. BABYLON.serialize()
  40325. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  40326. __decorate([
  40327. BABYLON.serialize()
  40328. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  40329. __decorate([
  40330. BABYLON.serialize()
  40331. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  40332. __decorate([
  40333. BABYLON.serialize()
  40334. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  40335. __decorate([
  40336. BABYLON.serialize()
  40337. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  40338. __decorate([
  40339. BABYLON.serialize()
  40340. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  40341. __decorate([
  40342. BABYLON.serializeAsVector3()
  40343. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  40344. __decorate([
  40345. BABYLON.serialize()
  40346. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  40347. __decorate([
  40348. BABYLON.serialize()
  40349. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  40350. __decorate([
  40351. BABYLON.serialize()
  40352. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  40353. return ArcRotateCamera;
  40354. }(BABYLON.TargetCamera));
  40355. BABYLON.ArcRotateCamera = ArcRotateCamera;
  40356. })(BABYLON || (BABYLON = {}));
  40357. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  40358. var BABYLON;
  40359. (function (BABYLON) {
  40360. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  40361. __extends(ArcRotateCameraInputsManager, _super);
  40362. function ArcRotateCameraInputsManager(camera) {
  40363. return _super.call(this, camera) || this;
  40364. }
  40365. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  40366. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  40367. return this;
  40368. };
  40369. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  40370. this.add(new BABYLON.ArcRotateCameraPointersInput());
  40371. return this;
  40372. };
  40373. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  40374. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  40375. return this;
  40376. };
  40377. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  40378. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  40379. return this;
  40380. };
  40381. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  40382. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  40383. return this;
  40384. };
  40385. return ArcRotateCameraInputsManager;
  40386. }(BABYLON.CameraInputsManager));
  40387. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  40388. })(BABYLON || (BABYLON = {}));
  40389. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  40390. var BABYLON;
  40391. (function (BABYLON) {
  40392. var HemisphericLight = /** @class */ (function (_super) {
  40393. __extends(HemisphericLight, _super);
  40394. /**
  40395. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  40396. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  40397. * The HemisphericLight can't cast shadows.
  40398. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40399. */
  40400. function HemisphericLight(name, direction, scene) {
  40401. var _this = _super.call(this, name, scene) || this;
  40402. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  40403. _this.direction = direction || BABYLON.Vector3.Up();
  40404. return _this;
  40405. }
  40406. HemisphericLight.prototype._buildUniformLayout = function () {
  40407. this._uniformBuffer.addUniform("vLightData", 4);
  40408. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40409. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40410. this._uniformBuffer.addUniform("vLightGround", 3);
  40411. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40412. this._uniformBuffer.addUniform("depthValues", 2);
  40413. this._uniformBuffer.create();
  40414. };
  40415. /**
  40416. * Returns the string "HemisphericLight".
  40417. */
  40418. HemisphericLight.prototype.getClassName = function () {
  40419. return "HemisphericLight";
  40420. };
  40421. /**
  40422. * Sets the HemisphericLight direction towards the passed target (Vector3).
  40423. * Returns the updated direction.
  40424. */
  40425. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  40426. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  40427. return this.direction;
  40428. };
  40429. HemisphericLight.prototype.getShadowGenerator = function () {
  40430. return null;
  40431. };
  40432. /**
  40433. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  40434. * Returns the HemisphericLight.
  40435. */
  40436. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  40437. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  40438. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  40439. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  40440. return this;
  40441. };
  40442. HemisphericLight.prototype._getWorldMatrix = function () {
  40443. if (!this._worldMatrix) {
  40444. this._worldMatrix = BABYLON.Matrix.Identity();
  40445. }
  40446. return this._worldMatrix;
  40447. };
  40448. /**
  40449. * Returns the integer 3.
  40450. */
  40451. HemisphericLight.prototype.getTypeID = function () {
  40452. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  40453. };
  40454. __decorate([
  40455. BABYLON.serializeAsColor3()
  40456. ], HemisphericLight.prototype, "groundColor", void 0);
  40457. __decorate([
  40458. BABYLON.serializeAsVector3()
  40459. ], HemisphericLight.prototype, "direction", void 0);
  40460. return HemisphericLight;
  40461. }(BABYLON.Light));
  40462. BABYLON.HemisphericLight = HemisphericLight;
  40463. })(BABYLON || (BABYLON = {}));
  40464. //# sourceMappingURL=babylon.hemisphericLight.js.map
  40465. var BABYLON;
  40466. (function (BABYLON) {
  40467. var ShadowLight = /** @class */ (function (_super) {
  40468. __extends(ShadowLight, _super);
  40469. function ShadowLight() {
  40470. var _this = _super !== null && _super.apply(this, arguments) || this;
  40471. _this._needProjectionMatrixCompute = true;
  40472. return _this;
  40473. }
  40474. Object.defineProperty(ShadowLight.prototype, "direction", {
  40475. get: function () {
  40476. return this._direction;
  40477. },
  40478. set: function (value) {
  40479. this._direction = value;
  40480. },
  40481. enumerable: true,
  40482. configurable: true
  40483. });
  40484. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  40485. get: function () {
  40486. return this._shadowMinZ;
  40487. },
  40488. set: function (value) {
  40489. this._shadowMinZ = value;
  40490. this.forceProjectionMatrixCompute();
  40491. },
  40492. enumerable: true,
  40493. configurable: true
  40494. });
  40495. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  40496. get: function () {
  40497. return this._shadowMaxZ;
  40498. },
  40499. set: function (value) {
  40500. this._shadowMaxZ = value;
  40501. this.forceProjectionMatrixCompute();
  40502. },
  40503. enumerable: true,
  40504. configurable: true
  40505. });
  40506. /**
  40507. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  40508. */
  40509. ShadowLight.prototype.computeTransformedInformation = function () {
  40510. if (this.parent && this.parent.getWorldMatrix) {
  40511. if (!this.transformedPosition) {
  40512. this.transformedPosition = BABYLON.Vector3.Zero();
  40513. }
  40514. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  40515. // In case the direction is present.
  40516. if (this.direction) {
  40517. if (!this.transformedDirection) {
  40518. this.transformedDirection = BABYLON.Vector3.Zero();
  40519. }
  40520. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  40521. }
  40522. return true;
  40523. }
  40524. return false;
  40525. };
  40526. /**
  40527. * Return the depth scale used for the shadow map.
  40528. */
  40529. ShadowLight.prototype.getDepthScale = function () {
  40530. return 50.0;
  40531. };
  40532. /**
  40533. * Returns the light direction (Vector3) for any passed face index.
  40534. */
  40535. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  40536. return this.transformedDirection ? this.transformedDirection : this.direction;
  40537. };
  40538. /**
  40539. * Returns the DirectionalLight absolute position in the World.
  40540. */
  40541. ShadowLight.prototype.getAbsolutePosition = function () {
  40542. return this.transformedPosition ? this.transformedPosition : this.position;
  40543. };
  40544. /**
  40545. * Sets the DirectionalLight direction toward the passed target (Vector3).
  40546. * Returns the updated DirectionalLight direction (Vector3).
  40547. */
  40548. ShadowLight.prototype.setDirectionToTarget = function (target) {
  40549. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  40550. return this.direction;
  40551. };
  40552. /**
  40553. * Returns the light rotation (Vector3).
  40554. */
  40555. ShadowLight.prototype.getRotation = function () {
  40556. this.direction.normalize();
  40557. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  40558. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  40559. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  40560. };
  40561. /**
  40562. * Boolean : false by default.
  40563. */
  40564. ShadowLight.prototype.needCube = function () {
  40565. return false;
  40566. };
  40567. /**
  40568. * Specifies wether or not the projection matrix should be recomputed this frame.
  40569. */
  40570. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  40571. return this._needProjectionMatrixCompute;
  40572. };
  40573. /**
  40574. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  40575. */
  40576. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  40577. this._needProjectionMatrixCompute = true;
  40578. };
  40579. /**
  40580. * Get the world matrix of the sahdow lights.
  40581. */
  40582. ShadowLight.prototype._getWorldMatrix = function () {
  40583. if (!this._worldMatrix) {
  40584. this._worldMatrix = BABYLON.Matrix.Identity();
  40585. }
  40586. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  40587. return this._worldMatrix;
  40588. };
  40589. /**
  40590. * Gets the minZ used for shadow according to both the scene and the light.
  40591. * @param activeCamera
  40592. */
  40593. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  40594. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  40595. };
  40596. /**
  40597. * Gets the maxZ used for shadow according to both the scene and the light.
  40598. * @param activeCamera
  40599. */
  40600. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  40601. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  40602. };
  40603. /**
  40604. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  40605. * Returns the light.
  40606. */
  40607. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40608. if (this.customProjectionMatrixBuilder) {
  40609. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  40610. }
  40611. else {
  40612. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  40613. }
  40614. return this;
  40615. };
  40616. __decorate([
  40617. BABYLON.serializeAsVector3()
  40618. ], ShadowLight.prototype, "position", void 0);
  40619. __decorate([
  40620. BABYLON.serializeAsVector3()
  40621. ], ShadowLight.prototype, "direction", null);
  40622. __decorate([
  40623. BABYLON.serialize()
  40624. ], ShadowLight.prototype, "shadowMinZ", null);
  40625. __decorate([
  40626. BABYLON.serialize()
  40627. ], ShadowLight.prototype, "shadowMaxZ", null);
  40628. return ShadowLight;
  40629. }(BABYLON.Light));
  40630. BABYLON.ShadowLight = ShadowLight;
  40631. })(BABYLON || (BABYLON = {}));
  40632. //# sourceMappingURL=babylon.shadowLight.js.map
  40633. var BABYLON;
  40634. (function (BABYLON) {
  40635. var PointLight = /** @class */ (function (_super) {
  40636. __extends(PointLight, _super);
  40637. /**
  40638. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  40639. * A PointLight emits the light in every direction.
  40640. * It can cast shadows.
  40641. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  40642. * ```javascript
  40643. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  40644. * ```
  40645. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40646. */
  40647. function PointLight(name, position, scene) {
  40648. var _this = _super.call(this, name, scene) || this;
  40649. _this._shadowAngle = Math.PI / 2;
  40650. _this.position = position;
  40651. return _this;
  40652. }
  40653. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  40654. /**
  40655. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40656. * This specifies what angle the shadow will use to be created.
  40657. *
  40658. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  40659. */
  40660. get: function () {
  40661. return this._shadowAngle;
  40662. },
  40663. /**
  40664. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40665. * This specifies what angle the shadow will use to be created.
  40666. *
  40667. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  40668. */
  40669. set: function (value) {
  40670. this._shadowAngle = value;
  40671. this.forceProjectionMatrixCompute();
  40672. },
  40673. enumerable: true,
  40674. configurable: true
  40675. });
  40676. Object.defineProperty(PointLight.prototype, "direction", {
  40677. get: function () {
  40678. return this._direction;
  40679. },
  40680. /**
  40681. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40682. */
  40683. set: function (value) {
  40684. var previousNeedCube = this.needCube();
  40685. this._direction = value;
  40686. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  40687. this._shadowGenerator.recreateShadowMap();
  40688. }
  40689. },
  40690. enumerable: true,
  40691. configurable: true
  40692. });
  40693. /**
  40694. * Returns the string "PointLight"
  40695. */
  40696. PointLight.prototype.getClassName = function () {
  40697. return "PointLight";
  40698. };
  40699. /**
  40700. * Returns the integer 0.
  40701. */
  40702. PointLight.prototype.getTypeID = function () {
  40703. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  40704. };
  40705. /**
  40706. * Specifies wether or not the shadowmap should be a cube texture.
  40707. */
  40708. PointLight.prototype.needCube = function () {
  40709. return !this.direction;
  40710. };
  40711. /**
  40712. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  40713. */
  40714. PointLight.prototype.getShadowDirection = function (faceIndex) {
  40715. if (this.direction) {
  40716. return _super.prototype.getShadowDirection.call(this, faceIndex);
  40717. }
  40718. else {
  40719. switch (faceIndex) {
  40720. case 0:
  40721. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  40722. case 1:
  40723. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  40724. case 2:
  40725. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  40726. case 3:
  40727. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  40728. case 4:
  40729. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  40730. case 5:
  40731. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  40732. }
  40733. }
  40734. return BABYLON.Vector3.Zero();
  40735. };
  40736. /**
  40737. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  40738. * - fov = PI / 2
  40739. * - aspect ratio : 1.0
  40740. * - z-near and far equal to the active camera minZ and maxZ.
  40741. * Returns the PointLight.
  40742. */
  40743. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40744. var activeCamera = this.getScene().activeCamera;
  40745. if (!activeCamera) {
  40746. return;
  40747. }
  40748. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  40749. };
  40750. PointLight.prototype._buildUniformLayout = function () {
  40751. this._uniformBuffer.addUniform("vLightData", 4);
  40752. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40753. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40754. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40755. this._uniformBuffer.addUniform("depthValues", 2);
  40756. this._uniformBuffer.create();
  40757. };
  40758. /**
  40759. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  40760. * Returns the PointLight.
  40761. */
  40762. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  40763. if (this.computeTransformedInformation()) {
  40764. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  40765. return this;
  40766. }
  40767. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  40768. return this;
  40769. };
  40770. __decorate([
  40771. BABYLON.serialize()
  40772. ], PointLight.prototype, "shadowAngle", null);
  40773. return PointLight;
  40774. }(BABYLON.ShadowLight));
  40775. BABYLON.PointLight = PointLight;
  40776. })(BABYLON || (BABYLON = {}));
  40777. //# sourceMappingURL=babylon.pointLight.js.map
  40778. var BABYLON;
  40779. (function (BABYLON) {
  40780. var DirectionalLight = /** @class */ (function (_super) {
  40781. __extends(DirectionalLight, _super);
  40782. /**
  40783. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  40784. * The directional light is emitted from everywhere in the given direction.
  40785. * It can cast shawdows.
  40786. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40787. */
  40788. function DirectionalLight(name, direction, scene) {
  40789. var _this = _super.call(this, name, scene) || this;
  40790. _this._shadowFrustumSize = 0;
  40791. _this._shadowOrthoScale = 0.5;
  40792. _this.autoUpdateExtends = true;
  40793. // Cache
  40794. _this._orthoLeft = Number.MAX_VALUE;
  40795. _this._orthoRight = Number.MIN_VALUE;
  40796. _this._orthoTop = Number.MIN_VALUE;
  40797. _this._orthoBottom = Number.MAX_VALUE;
  40798. _this.position = direction.scale(-1.0);
  40799. _this.direction = direction;
  40800. return _this;
  40801. }
  40802. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  40803. /**
  40804. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  40805. */
  40806. get: function () {
  40807. return this._shadowFrustumSize;
  40808. },
  40809. /**
  40810. * Specifies a fix frustum size for the shadow generation.
  40811. */
  40812. set: function (value) {
  40813. this._shadowFrustumSize = value;
  40814. this.forceProjectionMatrixCompute();
  40815. },
  40816. enumerable: true,
  40817. configurable: true
  40818. });
  40819. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  40820. get: function () {
  40821. return this._shadowOrthoScale;
  40822. },
  40823. set: function (value) {
  40824. this._shadowOrthoScale = value;
  40825. this.forceProjectionMatrixCompute();
  40826. },
  40827. enumerable: true,
  40828. configurable: true
  40829. });
  40830. /**
  40831. * Returns the string "DirectionalLight".
  40832. */
  40833. DirectionalLight.prototype.getClassName = function () {
  40834. return "DirectionalLight";
  40835. };
  40836. /**
  40837. * Returns the integer 1.
  40838. */
  40839. DirectionalLight.prototype.getTypeID = function () {
  40840. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  40841. };
  40842. /**
  40843. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  40844. * Returns the DirectionalLight Shadow projection matrix.
  40845. */
  40846. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40847. if (this.shadowFrustumSize > 0) {
  40848. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  40849. }
  40850. else {
  40851. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  40852. }
  40853. };
  40854. /**
  40855. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  40856. * Returns the DirectionalLight Shadow projection matrix.
  40857. */
  40858. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  40859. var activeCamera = this.getScene().activeCamera;
  40860. if (!activeCamera) {
  40861. return;
  40862. }
  40863. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  40864. };
  40865. /**
  40866. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  40867. * Returns the DirectionalLight Shadow projection matrix.
  40868. */
  40869. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40870. var activeCamera = this.getScene().activeCamera;
  40871. if (!activeCamera) {
  40872. return;
  40873. }
  40874. // Check extends
  40875. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  40876. var tempVector3 = BABYLON.Vector3.Zero();
  40877. this._orthoLeft = Number.MAX_VALUE;
  40878. this._orthoRight = Number.MIN_VALUE;
  40879. this._orthoTop = Number.MIN_VALUE;
  40880. this._orthoBottom = Number.MAX_VALUE;
  40881. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  40882. var mesh = renderList[meshIndex];
  40883. if (!mesh) {
  40884. continue;
  40885. }
  40886. var boundingInfo = mesh.getBoundingInfo();
  40887. var boundingBox = boundingInfo.boundingBox;
  40888. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  40889. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  40890. if (tempVector3.x < this._orthoLeft)
  40891. this._orthoLeft = tempVector3.x;
  40892. if (tempVector3.y < this._orthoBottom)
  40893. this._orthoBottom = tempVector3.y;
  40894. if (tempVector3.x > this._orthoRight)
  40895. this._orthoRight = tempVector3.x;
  40896. if (tempVector3.y > this._orthoTop)
  40897. this._orthoTop = tempVector3.y;
  40898. }
  40899. }
  40900. }
  40901. var xOffset = this._orthoRight - this._orthoLeft;
  40902. var yOffset = this._orthoTop - this._orthoBottom;
  40903. 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);
  40904. };
  40905. DirectionalLight.prototype._buildUniformLayout = function () {
  40906. this._uniformBuffer.addUniform("vLightData", 4);
  40907. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40908. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40909. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40910. this._uniformBuffer.addUniform("depthValues", 2);
  40911. this._uniformBuffer.create();
  40912. };
  40913. /**
  40914. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  40915. * Returns the DirectionalLight.
  40916. */
  40917. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  40918. if (this.computeTransformedInformation()) {
  40919. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  40920. return this;
  40921. }
  40922. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  40923. return this;
  40924. };
  40925. /**
  40926. * Gets the minZ used for shadow according to both the scene and the light.
  40927. *
  40928. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  40929. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  40930. * @param activeCamera
  40931. */
  40932. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  40933. return 1;
  40934. };
  40935. /**
  40936. * Gets the maxZ used for shadow according to both the scene and the light.
  40937. *
  40938. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  40939. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  40940. * @param activeCamera
  40941. */
  40942. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  40943. return 1;
  40944. };
  40945. __decorate([
  40946. BABYLON.serialize()
  40947. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  40948. __decorate([
  40949. BABYLON.serialize()
  40950. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  40951. __decorate([
  40952. BABYLON.serialize()
  40953. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  40954. return DirectionalLight;
  40955. }(BABYLON.ShadowLight));
  40956. BABYLON.DirectionalLight = DirectionalLight;
  40957. })(BABYLON || (BABYLON = {}));
  40958. //# sourceMappingURL=babylon.directionalLight.js.map
  40959. var BABYLON;
  40960. (function (BABYLON) {
  40961. var SpotLight = /** @class */ (function (_super) {
  40962. __extends(SpotLight, _super);
  40963. /**
  40964. * Creates a SpotLight object in the scene with the passed parameters :
  40965. * - `position` (Vector3) is the initial SpotLight position,
  40966. * - `direction` (Vector3) is the initial SpotLight direction,
  40967. * - `angle` (float, in radians) is the spot light cone angle,
  40968. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  40969. * A spot light is a simply light oriented cone.
  40970. * It can cast shadows.
  40971. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40972. */
  40973. function SpotLight(name, position, direction, angle, exponent, scene) {
  40974. var _this = _super.call(this, name, scene) || this;
  40975. _this.position = position;
  40976. _this.direction = direction;
  40977. _this.angle = angle;
  40978. _this.exponent = exponent;
  40979. return _this;
  40980. }
  40981. Object.defineProperty(SpotLight.prototype, "angle", {
  40982. get: function () {
  40983. return this._angle;
  40984. },
  40985. set: function (value) {
  40986. this._angle = value;
  40987. this.forceProjectionMatrixCompute();
  40988. },
  40989. enumerable: true,
  40990. configurable: true
  40991. });
  40992. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  40993. get: function () {
  40994. return this._shadowAngleScale;
  40995. },
  40996. /**
  40997. * Allows scaling the angle of the light for shadow generation only.
  40998. */
  40999. set: function (value) {
  41000. this._shadowAngleScale = value;
  41001. this.forceProjectionMatrixCompute();
  41002. },
  41003. enumerable: true,
  41004. configurable: true
  41005. });
  41006. /**
  41007. * Returns the string "SpotLight".
  41008. */
  41009. SpotLight.prototype.getClassName = function () {
  41010. return "SpotLight";
  41011. };
  41012. /**
  41013. * Returns the integer 2.
  41014. */
  41015. SpotLight.prototype.getTypeID = function () {
  41016. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  41017. };
  41018. /**
  41019. * 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.
  41020. * Returns the SpotLight.
  41021. */
  41022. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41023. var activeCamera = this.getScene().activeCamera;
  41024. if (!activeCamera) {
  41025. return;
  41026. }
  41027. this._shadowAngleScale = this._shadowAngleScale || 1;
  41028. var angle = this._shadowAngleScale * this._angle;
  41029. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  41030. };
  41031. SpotLight.prototype._buildUniformLayout = function () {
  41032. this._uniformBuffer.addUniform("vLightData", 4);
  41033. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41034. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41035. this._uniformBuffer.addUniform("vLightDirection", 3);
  41036. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41037. this._uniformBuffer.addUniform("depthValues", 2);
  41038. this._uniformBuffer.create();
  41039. };
  41040. /**
  41041. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  41042. * Return the SpotLight.
  41043. */
  41044. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  41045. var normalizeDirection;
  41046. if (this.computeTransformedInformation()) {
  41047. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  41048. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  41049. }
  41050. else {
  41051. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  41052. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  41053. }
  41054. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  41055. return this;
  41056. };
  41057. __decorate([
  41058. BABYLON.serialize()
  41059. ], SpotLight.prototype, "angle", null);
  41060. __decorate([
  41061. BABYLON.serialize()
  41062. /**
  41063. * Allows scaling the angle of the light for shadow generation only.
  41064. */
  41065. ], SpotLight.prototype, "shadowAngleScale", null);
  41066. __decorate([
  41067. BABYLON.serialize()
  41068. ], SpotLight.prototype, "exponent", void 0);
  41069. return SpotLight;
  41070. }(BABYLON.ShadowLight));
  41071. BABYLON.SpotLight = SpotLight;
  41072. })(BABYLON || (BABYLON = {}));
  41073. //# sourceMappingURL=babylon.spotLight.js.map
  41074. var BABYLON;
  41075. (function (BABYLON) {
  41076. var AnimationRange = /** @class */ (function () {
  41077. function AnimationRange(name, from, to) {
  41078. this.name = name;
  41079. this.from = from;
  41080. this.to = to;
  41081. }
  41082. AnimationRange.prototype.clone = function () {
  41083. return new AnimationRange(this.name, this.from, this.to);
  41084. };
  41085. return AnimationRange;
  41086. }());
  41087. BABYLON.AnimationRange = AnimationRange;
  41088. /**
  41089. * Composed of a frame, and an action function
  41090. */
  41091. var AnimationEvent = /** @class */ (function () {
  41092. function AnimationEvent(frame, action, onlyOnce) {
  41093. this.frame = frame;
  41094. this.action = action;
  41095. this.onlyOnce = onlyOnce;
  41096. this.isDone = false;
  41097. }
  41098. return AnimationEvent;
  41099. }());
  41100. BABYLON.AnimationEvent = AnimationEvent;
  41101. var PathCursor = /** @class */ (function () {
  41102. function PathCursor(path) {
  41103. this.path = path;
  41104. this._onchange = new Array();
  41105. this.value = 0;
  41106. this.animations = new Array();
  41107. }
  41108. PathCursor.prototype.getPoint = function () {
  41109. var point = this.path.getPointAtLengthPosition(this.value);
  41110. return new BABYLON.Vector3(point.x, 0, point.y);
  41111. };
  41112. PathCursor.prototype.moveAhead = function (step) {
  41113. if (step === void 0) { step = 0.002; }
  41114. this.move(step);
  41115. return this;
  41116. };
  41117. PathCursor.prototype.moveBack = function (step) {
  41118. if (step === void 0) { step = 0.002; }
  41119. this.move(-step);
  41120. return this;
  41121. };
  41122. PathCursor.prototype.move = function (step) {
  41123. if (Math.abs(step) > 1) {
  41124. throw "step size should be less than 1.";
  41125. }
  41126. this.value += step;
  41127. this.ensureLimits();
  41128. this.raiseOnChange();
  41129. return this;
  41130. };
  41131. PathCursor.prototype.ensureLimits = function () {
  41132. while (this.value > 1) {
  41133. this.value -= 1;
  41134. }
  41135. while (this.value < 0) {
  41136. this.value += 1;
  41137. }
  41138. return this;
  41139. };
  41140. // used by animation engine
  41141. PathCursor.prototype.raiseOnChange = function () {
  41142. var _this = this;
  41143. this._onchange.forEach(function (f) { return f(_this); });
  41144. return this;
  41145. };
  41146. PathCursor.prototype.onchange = function (f) {
  41147. this._onchange.push(f);
  41148. return this;
  41149. };
  41150. return PathCursor;
  41151. }());
  41152. BABYLON.PathCursor = PathCursor;
  41153. var Animation = /** @class */ (function () {
  41154. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  41155. this.name = name;
  41156. this.targetProperty = targetProperty;
  41157. this.framePerSecond = framePerSecond;
  41158. this.dataType = dataType;
  41159. this.loopMode = loopMode;
  41160. this.enableBlending = enableBlending;
  41161. this._runtimeAnimations = new Array();
  41162. // The set of event that will be linked to this animation
  41163. this._events = new Array();
  41164. this.blendingSpeed = 0.01;
  41165. this._ranges = {};
  41166. this.targetPropertyPath = targetProperty.split(".");
  41167. this.dataType = dataType;
  41168. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  41169. }
  41170. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  41171. var dataType = undefined;
  41172. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  41173. dataType = Animation.ANIMATIONTYPE_FLOAT;
  41174. }
  41175. else if (from instanceof BABYLON.Quaternion) {
  41176. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  41177. }
  41178. else if (from instanceof BABYLON.Vector3) {
  41179. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  41180. }
  41181. else if (from instanceof BABYLON.Vector2) {
  41182. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  41183. }
  41184. else if (from instanceof BABYLON.Color3) {
  41185. dataType = Animation.ANIMATIONTYPE_COLOR3;
  41186. }
  41187. else if (from instanceof BABYLON.Size) {
  41188. dataType = Animation.ANIMATIONTYPE_SIZE;
  41189. }
  41190. if (dataType == undefined) {
  41191. return null;
  41192. }
  41193. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  41194. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  41195. animation.setKeys(keys);
  41196. if (easingFunction !== undefined) {
  41197. animation.setEasingFunction(easingFunction);
  41198. }
  41199. return animation;
  41200. };
  41201. /**
  41202. * Sets up an animation.
  41203. * @param property the property to animate
  41204. * @param animationType the animation type to apply
  41205. * @param easingFunction the easing function used in the animation
  41206. * @returns The created animation
  41207. */
  41208. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  41209. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  41210. animation.setEasingFunction(easingFunction);
  41211. return animation;
  41212. };
  41213. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  41214. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  41215. if (!animation) {
  41216. return null;
  41217. }
  41218. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  41219. };
  41220. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  41221. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  41222. if (!animation) {
  41223. return null;
  41224. }
  41225. node.animations.push(animation);
  41226. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  41227. };
  41228. /**
  41229. * Transition property of the Camera to the target Value.
  41230. * @param property The property to transition
  41231. * @param targetValue The target Value of the property
  41232. * @param host The object where the property to animate belongs
  41233. * @param scene Scene used to run the animation
  41234. * @param frameRate Framerate (in frame/s) to use
  41235. * @param transition The transition type we want to use
  41236. * @param duration The duration of the animation, in milliseconds
  41237. * @param onAnimationEnd Call back trigger at the end of the animation.
  41238. */
  41239. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  41240. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  41241. if (duration <= 0) {
  41242. host[property] = targetValue;
  41243. if (onAnimationEnd) {
  41244. onAnimationEnd();
  41245. }
  41246. return null;
  41247. }
  41248. var endFrame = frameRate * (duration / 1000);
  41249. transition.setKeys([{
  41250. frame: 0,
  41251. value: host[property].clone ? host[property].clone() : host[property]
  41252. },
  41253. {
  41254. frame: endFrame,
  41255. value: targetValue
  41256. }]);
  41257. if (!host.animations) {
  41258. host.animations = [];
  41259. }
  41260. host.animations.push(transition);
  41261. var animation = scene.beginAnimation(host, 0, endFrame, false);
  41262. animation.onAnimationEnd = onAnimationEnd;
  41263. return animation;
  41264. };
  41265. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  41266. /**
  41267. * Return the array of runtime animations currently using this animation
  41268. */
  41269. get: function () {
  41270. return this._runtimeAnimations;
  41271. },
  41272. enumerable: true,
  41273. configurable: true
  41274. });
  41275. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  41276. get: function () {
  41277. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  41278. var runtimeAnimation = _a[_i];
  41279. if (!runtimeAnimation.isStopped) {
  41280. return true;
  41281. }
  41282. }
  41283. return false;
  41284. },
  41285. enumerable: true,
  41286. configurable: true
  41287. });
  41288. // Methods
  41289. /**
  41290. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  41291. */
  41292. Animation.prototype.toString = function (fullDetails) {
  41293. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  41294. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  41295. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  41296. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  41297. if (fullDetails) {
  41298. ret += ", Ranges: {";
  41299. var first = true;
  41300. for (var name in this._ranges) {
  41301. if (first) {
  41302. ret += ", ";
  41303. first = false;
  41304. }
  41305. ret += name;
  41306. }
  41307. ret += "}";
  41308. }
  41309. return ret;
  41310. };
  41311. /**
  41312. * Add an event to this animation.
  41313. */
  41314. Animation.prototype.addEvent = function (event) {
  41315. this._events.push(event);
  41316. };
  41317. /**
  41318. * Remove all events found at the given frame
  41319. * @param frame
  41320. */
  41321. Animation.prototype.removeEvents = function (frame) {
  41322. for (var index = 0; index < this._events.length; index++) {
  41323. if (this._events[index].frame === frame) {
  41324. this._events.splice(index, 1);
  41325. index--;
  41326. }
  41327. }
  41328. };
  41329. Animation.prototype.getEvents = function () {
  41330. return this._events;
  41331. };
  41332. Animation.prototype.createRange = function (name, from, to) {
  41333. // check name not already in use; could happen for bones after serialized
  41334. if (!this._ranges[name]) {
  41335. this._ranges[name] = new AnimationRange(name, from, to);
  41336. }
  41337. };
  41338. Animation.prototype.deleteRange = function (name, deleteFrames) {
  41339. if (deleteFrames === void 0) { deleteFrames = true; }
  41340. var range = this._ranges[name];
  41341. if (!range) {
  41342. return;
  41343. }
  41344. if (deleteFrames) {
  41345. var from = range.from;
  41346. var to = range.to;
  41347. // this loop MUST go high to low for multiple splices to work
  41348. for (var key = this._keys.length - 1; key >= 0; key--) {
  41349. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  41350. this._keys.splice(key, 1);
  41351. }
  41352. }
  41353. }
  41354. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  41355. };
  41356. Animation.prototype.getRange = function (name) {
  41357. return this._ranges[name];
  41358. };
  41359. Animation.prototype.getKeys = function () {
  41360. return this._keys;
  41361. };
  41362. Animation.prototype.getHighestFrame = function () {
  41363. var ret = 0;
  41364. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  41365. if (ret < this._keys[key].frame) {
  41366. ret = this._keys[key].frame;
  41367. }
  41368. }
  41369. return ret;
  41370. };
  41371. Animation.prototype.getEasingFunction = function () {
  41372. return this._easingFunction;
  41373. };
  41374. Animation.prototype.setEasingFunction = function (easingFunction) {
  41375. this._easingFunction = easingFunction;
  41376. };
  41377. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  41378. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  41379. };
  41380. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  41381. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  41382. };
  41383. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  41384. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  41385. };
  41386. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  41387. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  41388. };
  41389. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  41390. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  41391. };
  41392. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  41393. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  41394. };
  41395. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  41396. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  41397. };
  41398. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  41399. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  41400. };
  41401. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  41402. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  41403. };
  41404. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  41405. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  41406. };
  41407. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  41408. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  41409. };
  41410. Animation.prototype.clone = function () {
  41411. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  41412. clone.enableBlending = this.enableBlending;
  41413. clone.blendingSpeed = this.blendingSpeed;
  41414. if (this._keys) {
  41415. clone.setKeys(this._keys);
  41416. }
  41417. if (this._ranges) {
  41418. clone._ranges = {};
  41419. for (var name in this._ranges) {
  41420. var range = this._ranges[name];
  41421. if (!range) {
  41422. continue;
  41423. }
  41424. clone._ranges[name] = range.clone();
  41425. }
  41426. }
  41427. return clone;
  41428. };
  41429. Animation.prototype.setKeys = function (values) {
  41430. this._keys = values.slice(0);
  41431. };
  41432. Animation.prototype.serialize = function () {
  41433. var serializationObject = {};
  41434. serializationObject.name = this.name;
  41435. serializationObject.property = this.targetProperty;
  41436. serializationObject.framePerSecond = this.framePerSecond;
  41437. serializationObject.dataType = this.dataType;
  41438. serializationObject.loopBehavior = this.loopMode;
  41439. serializationObject.enableBlending = this.enableBlending;
  41440. serializationObject.blendingSpeed = this.blendingSpeed;
  41441. var dataType = this.dataType;
  41442. serializationObject.keys = [];
  41443. var keys = this.getKeys();
  41444. for (var index = 0; index < keys.length; index++) {
  41445. var animationKey = keys[index];
  41446. var key = {};
  41447. key.frame = animationKey.frame;
  41448. switch (dataType) {
  41449. case Animation.ANIMATIONTYPE_FLOAT:
  41450. key.values = [animationKey.value];
  41451. break;
  41452. case Animation.ANIMATIONTYPE_QUATERNION:
  41453. case Animation.ANIMATIONTYPE_MATRIX:
  41454. case Animation.ANIMATIONTYPE_VECTOR3:
  41455. case Animation.ANIMATIONTYPE_COLOR3:
  41456. key.values = animationKey.value.asArray();
  41457. break;
  41458. }
  41459. serializationObject.keys.push(key);
  41460. }
  41461. serializationObject.ranges = [];
  41462. for (var name in this._ranges) {
  41463. var source = this._ranges[name];
  41464. if (!source) {
  41465. continue;
  41466. }
  41467. var range = {};
  41468. range.name = name;
  41469. range.from = source.from;
  41470. range.to = source.to;
  41471. serializationObject.ranges.push(range);
  41472. }
  41473. return serializationObject;
  41474. };
  41475. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  41476. get: function () {
  41477. return Animation._ANIMATIONTYPE_FLOAT;
  41478. },
  41479. enumerable: true,
  41480. configurable: true
  41481. });
  41482. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  41483. get: function () {
  41484. return Animation._ANIMATIONTYPE_VECTOR3;
  41485. },
  41486. enumerable: true,
  41487. configurable: true
  41488. });
  41489. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  41490. get: function () {
  41491. return Animation._ANIMATIONTYPE_VECTOR2;
  41492. },
  41493. enumerable: true,
  41494. configurable: true
  41495. });
  41496. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  41497. get: function () {
  41498. return Animation._ANIMATIONTYPE_SIZE;
  41499. },
  41500. enumerable: true,
  41501. configurable: true
  41502. });
  41503. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  41504. get: function () {
  41505. return Animation._ANIMATIONTYPE_QUATERNION;
  41506. },
  41507. enumerable: true,
  41508. configurable: true
  41509. });
  41510. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  41511. get: function () {
  41512. return Animation._ANIMATIONTYPE_MATRIX;
  41513. },
  41514. enumerable: true,
  41515. configurable: true
  41516. });
  41517. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  41518. get: function () {
  41519. return Animation._ANIMATIONTYPE_COLOR3;
  41520. },
  41521. enumerable: true,
  41522. configurable: true
  41523. });
  41524. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  41525. get: function () {
  41526. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  41527. },
  41528. enumerable: true,
  41529. configurable: true
  41530. });
  41531. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  41532. get: function () {
  41533. return Animation._ANIMATIONLOOPMODE_CYCLE;
  41534. },
  41535. enumerable: true,
  41536. configurable: true
  41537. });
  41538. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  41539. get: function () {
  41540. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  41541. },
  41542. enumerable: true,
  41543. configurable: true
  41544. });
  41545. Animation.Parse = function (parsedAnimation) {
  41546. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  41547. var dataType = parsedAnimation.dataType;
  41548. var keys = [];
  41549. var data;
  41550. var index;
  41551. if (parsedAnimation.enableBlending) {
  41552. animation.enableBlending = parsedAnimation.enableBlending;
  41553. }
  41554. if (parsedAnimation.blendingSpeed) {
  41555. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  41556. }
  41557. for (index = 0; index < parsedAnimation.keys.length; index++) {
  41558. var key = parsedAnimation.keys[index];
  41559. var inTangent;
  41560. var outTangent;
  41561. switch (dataType) {
  41562. case Animation.ANIMATIONTYPE_FLOAT:
  41563. data = key.values[0];
  41564. if (key.values.length >= 1) {
  41565. inTangent = key.values[1];
  41566. }
  41567. if (key.values.length >= 2) {
  41568. outTangent = key.values[2];
  41569. }
  41570. break;
  41571. case Animation.ANIMATIONTYPE_QUATERNION:
  41572. data = BABYLON.Quaternion.FromArray(key.values);
  41573. if (key.values.length >= 8) {
  41574. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  41575. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  41576. inTangent = _inTangent;
  41577. }
  41578. }
  41579. if (key.values.length >= 12) {
  41580. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  41581. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  41582. outTangent = _outTangent;
  41583. }
  41584. }
  41585. break;
  41586. case Animation.ANIMATIONTYPE_MATRIX:
  41587. data = BABYLON.Matrix.FromArray(key.values);
  41588. break;
  41589. case Animation.ANIMATIONTYPE_COLOR3:
  41590. data = BABYLON.Color3.FromArray(key.values);
  41591. break;
  41592. case Animation.ANIMATIONTYPE_VECTOR3:
  41593. default:
  41594. data = BABYLON.Vector3.FromArray(key.values);
  41595. break;
  41596. }
  41597. var keyData = {};
  41598. keyData.frame = key.frame;
  41599. keyData.value = data;
  41600. if (inTangent != undefined) {
  41601. keyData.inTangent = inTangent;
  41602. }
  41603. if (outTangent != undefined) {
  41604. keyData.outTangent = outTangent;
  41605. }
  41606. keys.push(keyData);
  41607. }
  41608. animation.setKeys(keys);
  41609. if (parsedAnimation.ranges) {
  41610. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  41611. data = parsedAnimation.ranges[index];
  41612. animation.createRange(data.name, data.from, data.to);
  41613. }
  41614. }
  41615. return animation;
  41616. };
  41617. Animation.AppendSerializedAnimations = function (source, destination) {
  41618. if (source.animations) {
  41619. destination.animations = [];
  41620. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  41621. var animation = source.animations[animationIndex];
  41622. destination.animations.push(animation.serialize());
  41623. }
  41624. }
  41625. };
  41626. Animation.AllowMatricesInterpolation = false;
  41627. // Statics
  41628. Animation._ANIMATIONTYPE_FLOAT = 0;
  41629. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  41630. Animation._ANIMATIONTYPE_QUATERNION = 2;
  41631. Animation._ANIMATIONTYPE_MATRIX = 3;
  41632. Animation._ANIMATIONTYPE_COLOR3 = 4;
  41633. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  41634. Animation._ANIMATIONTYPE_SIZE = 6;
  41635. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  41636. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  41637. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  41638. return Animation;
  41639. }());
  41640. BABYLON.Animation = Animation;
  41641. })(BABYLON || (BABYLON = {}));
  41642. //# sourceMappingURL=babylon.animation.js.map
  41643. var BABYLON;
  41644. (function (BABYLON) {
  41645. /**
  41646. * This class defines the direct association between an animation and a target
  41647. */
  41648. var TargetedAnimation = /** @class */ (function () {
  41649. function TargetedAnimation() {
  41650. }
  41651. return TargetedAnimation;
  41652. }());
  41653. BABYLON.TargetedAnimation = TargetedAnimation;
  41654. /**
  41655. * Use this class to create coordinated animations on multiple targets
  41656. */
  41657. var AnimationGroup = /** @class */ (function () {
  41658. function AnimationGroup(name, scene) {
  41659. if (scene === void 0) { scene = null; }
  41660. this.name = name;
  41661. this._targetedAnimations = new Array();
  41662. this._animatables = new Array();
  41663. this._from = Number.MAX_VALUE;
  41664. this._to = Number.MIN_VALUE;
  41665. this.onAnimationEndObservable = new BABYLON.Observable();
  41666. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  41667. this._scene.animationGroups.push(this);
  41668. }
  41669. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  41670. get: function () {
  41671. return this._isStarted;
  41672. },
  41673. enumerable: true,
  41674. configurable: true
  41675. });
  41676. /**
  41677. * Add an animation (with its target) in the group
  41678. * @param animation defines the animation we want to add
  41679. * @param target defines the target of the animation
  41680. * @returns the {BABYLON.TargetedAnimation} object
  41681. */
  41682. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  41683. var targetedAnimation = {
  41684. animation: animation,
  41685. target: target
  41686. };
  41687. var keys = animation.getKeys();
  41688. if (this._from > keys[0].frame) {
  41689. this._from = keys[0].frame;
  41690. }
  41691. if (this._to < keys[keys.length - 1].frame) {
  41692. this._to = keys[keys.length - 1].frame;
  41693. }
  41694. this._targetedAnimations.push(targetedAnimation);
  41695. return targetedAnimation;
  41696. };
  41697. /**
  41698. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  41699. * It can add constant keys at begin or end
  41700. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smaller begin frame of all animations
  41701. * @param endFrame defines the new end frame for all animations. It can't be smaller than the larger end frame of all animations
  41702. */
  41703. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  41704. beginFrame = Math.min(beginFrame, this._from);
  41705. endFrame = Math.min(endFrame, this._to);
  41706. for (var index = 0; index < this._targetedAnimations.length; index++) {
  41707. var targetedAnimation = this._targetedAnimations[index];
  41708. var keys = targetedAnimation.animation.getKeys();
  41709. var startKey = keys[0];
  41710. var endKey = keys[keys.length - 1];
  41711. if (startKey.frame > beginFrame) {
  41712. var newKey = {
  41713. frame: beginFrame,
  41714. value: startKey.value,
  41715. inTangent: startKey.inTangent,
  41716. outTangent: startKey.outTangent
  41717. };
  41718. keys.splice(0, 0, newKey);
  41719. }
  41720. if (endKey.frame < endFrame) {
  41721. var newKey = {
  41722. frame: endFrame,
  41723. value: endKey.value,
  41724. inTangent: startKey.outTangent,
  41725. outTangent: startKey.outTangent
  41726. };
  41727. keys.push(newKey);
  41728. }
  41729. }
  41730. return this;
  41731. };
  41732. /**
  41733. * Start all animations on given targets
  41734. * @param loop defines if animations must loop
  41735. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  41736. */
  41737. AnimationGroup.prototype.start = function (loop, speedRatio) {
  41738. if (loop === void 0) { loop = false; }
  41739. if (speedRatio === void 0) { speedRatio = 1; }
  41740. if (this._isStarted || this._targetedAnimations.length === 0) {
  41741. return this;
  41742. }
  41743. for (var index = 0; index < this._targetedAnimations.length; index++) {
  41744. var targetedAnimation = this._targetedAnimations[index];
  41745. this._animatables.push(this._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this._from, this._to, loop, speedRatio, function () {
  41746. }));
  41747. }
  41748. this._isStarted = true;
  41749. return this;
  41750. };
  41751. /**
  41752. * Pause all animations
  41753. */
  41754. AnimationGroup.prototype.pause = function () {
  41755. if (!this._isStarted) {
  41756. return this;
  41757. }
  41758. for (var index = 0; index < this._animatables.length; index++) {
  41759. var animatable = this._animatables[index];
  41760. animatable.pause();
  41761. }
  41762. return this;
  41763. };
  41764. /**
  41765. * Play all animations to initial state
  41766. * This function will start() the animations if they were not started or will restart() them if they were paused
  41767. */
  41768. AnimationGroup.prototype.play = function (loop) {
  41769. if (loop === void 0) { loop = false; }
  41770. if (this.isStarted) {
  41771. this.restart();
  41772. }
  41773. else {
  41774. this.start(loop);
  41775. }
  41776. return this;
  41777. };
  41778. /**
  41779. * Reset all animations to initial state
  41780. */
  41781. AnimationGroup.prototype.reset = function () {
  41782. if (!this._isStarted) {
  41783. return this;
  41784. }
  41785. for (var index = 0; index < this._animatables.length; index++) {
  41786. var animatable = this._animatables[index];
  41787. animatable.reset();
  41788. }
  41789. return this;
  41790. };
  41791. /**
  41792. * Restart animations from key 0
  41793. */
  41794. AnimationGroup.prototype.restart = function () {
  41795. if (!this._isStarted) {
  41796. return this;
  41797. }
  41798. for (var index = 0; index < this._animatables.length; index++) {
  41799. var animatable = this._animatables[index];
  41800. animatable.restart();
  41801. }
  41802. return this;
  41803. };
  41804. /**
  41805. * Stop all animations
  41806. */
  41807. AnimationGroup.prototype.stop = function () {
  41808. if (!this._isStarted) {
  41809. return this;
  41810. }
  41811. for (var index = 0; index < this._animatables.length; index++) {
  41812. var animatable = this._animatables[index];
  41813. animatable.stop();
  41814. }
  41815. this._isStarted = false;
  41816. return this;
  41817. };
  41818. /**
  41819. * Dispose all associated resources
  41820. */
  41821. AnimationGroup.prototype.dispose = function () {
  41822. this._targetedAnimations = [];
  41823. this._animatables = [];
  41824. var index = this._scene.animationGroups.indexOf(this);
  41825. if (index > -1) {
  41826. this._scene.animationGroups.splice(index, 1);
  41827. }
  41828. };
  41829. return AnimationGroup;
  41830. }());
  41831. BABYLON.AnimationGroup = AnimationGroup;
  41832. })(BABYLON || (BABYLON = {}));
  41833. //# sourceMappingURL=babylon.animationGroup.js.map
  41834. var BABYLON;
  41835. (function (BABYLON) {
  41836. var RuntimeAnimation = /** @class */ (function () {
  41837. function RuntimeAnimation(target, animation) {
  41838. this._offsetsCache = {};
  41839. this._highLimitsCache = {};
  41840. this._stopped = false;
  41841. this._blendingFactor = 0;
  41842. this._ratioOffset = 0;
  41843. this._animation = animation;
  41844. this._target = target;
  41845. animation._runtimeAnimations.push(this);
  41846. }
  41847. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  41848. get: function () {
  41849. return this._animation;
  41850. },
  41851. enumerable: true,
  41852. configurable: true
  41853. });
  41854. RuntimeAnimation.prototype.reset = function () {
  41855. this._offsetsCache = {};
  41856. this._highLimitsCache = {};
  41857. this.currentFrame = 0;
  41858. this._blendingFactor = 0;
  41859. this._originalBlendValue = null;
  41860. };
  41861. RuntimeAnimation.prototype.isStopped = function () {
  41862. return this._stopped;
  41863. };
  41864. RuntimeAnimation.prototype.dispose = function () {
  41865. var index = this._animation.runtimeAnimations.indexOf(this);
  41866. if (index > -1) {
  41867. this._animation.runtimeAnimations.splice(index, 1);
  41868. }
  41869. };
  41870. RuntimeAnimation.prototype._getKeyValue = function (value) {
  41871. if (typeof value === "function") {
  41872. return value();
  41873. }
  41874. return value;
  41875. };
  41876. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  41877. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  41878. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  41879. }
  41880. this.currentFrame = currentFrame;
  41881. var keys = this._animation.getKeys();
  41882. // Try to get a hash to find the right key
  41883. 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));
  41884. if (keys[startKeyIndex].frame >= currentFrame) {
  41885. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  41886. startKeyIndex--;
  41887. }
  41888. }
  41889. for (var key = startKeyIndex; key < keys.length; key++) {
  41890. var endKey = keys[key + 1];
  41891. if (endKey.frame >= currentFrame) {
  41892. var startKey = keys[key];
  41893. var startValue = this._getKeyValue(startKey.value);
  41894. var endValue = this._getKeyValue(endKey.value);
  41895. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  41896. var frameDelta = endKey.frame - startKey.frame;
  41897. // gradient : percent of currentFrame between the frame inf and the frame sup
  41898. var gradient = (currentFrame - startKey.frame) / frameDelta;
  41899. // check for easingFunction and correction of gradient
  41900. var easingFunction = this._animation.getEasingFunction();
  41901. if (easingFunction != null) {
  41902. gradient = easingFunction.ease(gradient);
  41903. }
  41904. switch (this._animation.dataType) {
  41905. // Float
  41906. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  41907. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  41908. switch (loopMode) {
  41909. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41910. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41911. return floatValue;
  41912. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41913. return offsetValue * repeatCount + floatValue;
  41914. }
  41915. break;
  41916. // Quaternion
  41917. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  41918. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  41919. switch (loopMode) {
  41920. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41921. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41922. return quatValue;
  41923. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41924. return quatValue.add(offsetValue.scale(repeatCount));
  41925. }
  41926. return quatValue;
  41927. // Vector3
  41928. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  41929. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  41930. switch (loopMode) {
  41931. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41932. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41933. return vec3Value;
  41934. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41935. return vec3Value.add(offsetValue.scale(repeatCount));
  41936. }
  41937. // Vector2
  41938. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  41939. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  41940. switch (loopMode) {
  41941. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41942. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41943. return vec2Value;
  41944. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41945. return vec2Value.add(offsetValue.scale(repeatCount));
  41946. }
  41947. // Size
  41948. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  41949. switch (loopMode) {
  41950. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41951. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41952. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  41953. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41954. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  41955. }
  41956. // Color3
  41957. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  41958. switch (loopMode) {
  41959. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41960. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41961. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  41962. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41963. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  41964. }
  41965. // Matrix
  41966. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  41967. switch (loopMode) {
  41968. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41969. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41970. if (BABYLON.Animation.AllowMatricesInterpolation) {
  41971. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  41972. }
  41973. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41974. return startValue;
  41975. }
  41976. default:
  41977. break;
  41978. }
  41979. break;
  41980. }
  41981. }
  41982. return this._getKeyValue(keys[keys.length - 1].value);
  41983. };
  41984. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  41985. if (blend === void 0) { blend = false; }
  41986. // Set value
  41987. var path;
  41988. var destination;
  41989. var targetPropertyPath = this._animation.targetPropertyPath;
  41990. if (targetPropertyPath.length > 1) {
  41991. var property = this._target[targetPropertyPath[0]];
  41992. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  41993. property = property[targetPropertyPath[index]];
  41994. }
  41995. path = targetPropertyPath[targetPropertyPath.length - 1];
  41996. destination = property;
  41997. }
  41998. else {
  41999. path = targetPropertyPath[0];
  42000. destination = this._target;
  42001. }
  42002. // Blending
  42003. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  42004. if (!this._originalBlendValue) {
  42005. if (destination[path].clone) {
  42006. this._originalBlendValue = destination[path].clone();
  42007. }
  42008. else {
  42009. this._originalBlendValue = destination[path];
  42010. }
  42011. }
  42012. if (this._originalBlendValue.prototype) {
  42013. if (this._originalBlendValue.prototype.Lerp) {
  42014. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  42015. }
  42016. else {
  42017. destination[path] = currentValue;
  42018. }
  42019. }
  42020. else if (this._originalBlendValue.m) {
  42021. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  42022. }
  42023. else {
  42024. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  42025. }
  42026. this._blendingFactor += this._animation.blendingSpeed;
  42027. }
  42028. else {
  42029. destination[path] = currentValue;
  42030. }
  42031. if (this._target.markAsDirty) {
  42032. this._target.markAsDirty(this._animation.targetProperty);
  42033. }
  42034. };
  42035. RuntimeAnimation.prototype.goToFrame = function (frame) {
  42036. var keys = this._animation.getKeys();
  42037. if (frame < keys[0].frame) {
  42038. frame = keys[0].frame;
  42039. }
  42040. else if (frame > keys[keys.length - 1].frame) {
  42041. frame = keys[keys.length - 1].frame;
  42042. }
  42043. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  42044. this.setValue(currentValue);
  42045. };
  42046. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  42047. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  42048. this._ratioOffset = this._previousRatio - newRatio;
  42049. };
  42050. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  42051. if (blend === void 0) { blend = false; }
  42052. var targetPropertyPath = this._animation.targetPropertyPath;
  42053. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  42054. this._stopped = true;
  42055. return false;
  42056. }
  42057. var returnValue = true;
  42058. var keys = this._animation.getKeys();
  42059. // Adding a start key at frame 0 if missing
  42060. if (keys[0].frame !== 0) {
  42061. var newKey = { frame: 0, value: keys[0].value };
  42062. keys.splice(0, 0, newKey);
  42063. }
  42064. // Check limits
  42065. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  42066. from = keys[0].frame;
  42067. }
  42068. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  42069. to = keys[keys.length - 1].frame;
  42070. }
  42071. //to and from cannot be the same key
  42072. if (from === to) {
  42073. if (from > keys[0].frame) {
  42074. from--;
  42075. }
  42076. else if (to < keys[keys.length - 1].frame) {
  42077. to++;
  42078. }
  42079. }
  42080. // Compute ratio
  42081. var range = to - from;
  42082. var offsetValue;
  42083. // ratio represents the frame delta between from and to
  42084. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  42085. var highLimitValue = 0;
  42086. this._previousDelay = delay;
  42087. this._previousRatio = ratio;
  42088. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  42089. returnValue = false;
  42090. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  42091. }
  42092. else {
  42093. // Get max value if required
  42094. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  42095. var keyOffset = to.toString() + from.toString();
  42096. if (!this._offsetsCache[keyOffset]) {
  42097. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  42098. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  42099. switch (this._animation.dataType) {
  42100. // Float
  42101. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  42102. this._offsetsCache[keyOffset] = toValue - fromValue;
  42103. break;
  42104. // Quaternion
  42105. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  42106. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42107. break;
  42108. // Vector3
  42109. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  42110. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42111. // Vector2
  42112. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  42113. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42114. // Size
  42115. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  42116. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42117. // Color3
  42118. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  42119. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42120. default:
  42121. break;
  42122. }
  42123. this._highLimitsCache[keyOffset] = toValue;
  42124. }
  42125. highLimitValue = this._highLimitsCache[keyOffset];
  42126. offsetValue = this._offsetsCache[keyOffset];
  42127. }
  42128. }
  42129. if (offsetValue === undefined) {
  42130. switch (this._animation.dataType) {
  42131. // Float
  42132. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  42133. offsetValue = 0;
  42134. break;
  42135. // Quaternion
  42136. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  42137. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  42138. break;
  42139. // Vector3
  42140. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  42141. offsetValue = BABYLON.Vector3.Zero();
  42142. break;
  42143. // Vector2
  42144. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  42145. offsetValue = BABYLON.Vector2.Zero();
  42146. break;
  42147. // Size
  42148. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  42149. offsetValue = BABYLON.Size.Zero();
  42150. break;
  42151. // Color3
  42152. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  42153. offsetValue = BABYLON.Color3.Black();
  42154. }
  42155. }
  42156. // Compute value
  42157. var repeatCount = (ratio / range) >> 0;
  42158. var currentFrame = returnValue ? from + ratio % range : to;
  42159. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  42160. // Set value
  42161. this.setValue(currentValue);
  42162. // Check events
  42163. var events = this._animation.getEvents();
  42164. for (var index = 0; index < events.length; index++) {
  42165. // Make sure current frame has passed event frame and that event frame is within the current range
  42166. // Also, handle both forward and reverse animations
  42167. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  42168. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  42169. var event = events[index];
  42170. if (!event.isDone) {
  42171. // If event should be done only once, remove it.
  42172. if (event.onlyOnce) {
  42173. events.splice(index, 1);
  42174. index--;
  42175. }
  42176. event.isDone = true;
  42177. event.action();
  42178. } // Don't do anything if the event has already be done.
  42179. }
  42180. else if (events[index].isDone && !events[index].onlyOnce) {
  42181. // reset event, the animation is looping
  42182. events[index].isDone = false;
  42183. }
  42184. }
  42185. if (!returnValue) {
  42186. this._stopped = true;
  42187. }
  42188. return returnValue;
  42189. };
  42190. return RuntimeAnimation;
  42191. }());
  42192. BABYLON.RuntimeAnimation = RuntimeAnimation;
  42193. })(BABYLON || (BABYLON = {}));
  42194. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  42195. var BABYLON;
  42196. (function (BABYLON) {
  42197. var Animatable = /** @class */ (function () {
  42198. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  42199. if (fromFrame === void 0) { fromFrame = 0; }
  42200. if (toFrame === void 0) { toFrame = 100; }
  42201. if (loopAnimation === void 0) { loopAnimation = false; }
  42202. if (speedRatio === void 0) { speedRatio = 1.0; }
  42203. this.target = target;
  42204. this.fromFrame = fromFrame;
  42205. this.toFrame = toFrame;
  42206. this.loopAnimation = loopAnimation;
  42207. this.onAnimationEnd = onAnimationEnd;
  42208. this._localDelayOffset = null;
  42209. this._pausedDelay = null;
  42210. this._runtimeAnimations = new Array();
  42211. this._paused = false;
  42212. this._speedRatio = 1;
  42213. this.animationStarted = false;
  42214. if (animations) {
  42215. this.appendAnimations(target, animations);
  42216. }
  42217. this._speedRatio = speedRatio;
  42218. this._scene = scene;
  42219. scene._activeAnimatables.push(this);
  42220. }
  42221. Object.defineProperty(Animatable.prototype, "speedRatio", {
  42222. get: function () {
  42223. return this._speedRatio;
  42224. },
  42225. set: function (value) {
  42226. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  42227. var animation = this._runtimeAnimations[index];
  42228. animation._prepareForSpeedRatioChange(value);
  42229. }
  42230. this._speedRatio = value;
  42231. },
  42232. enumerable: true,
  42233. configurable: true
  42234. });
  42235. // Methods
  42236. Animatable.prototype.getAnimations = function () {
  42237. return this._runtimeAnimations;
  42238. };
  42239. Animatable.prototype.appendAnimations = function (target, animations) {
  42240. for (var index = 0; index < animations.length; index++) {
  42241. var animation = animations[index];
  42242. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  42243. }
  42244. };
  42245. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  42246. var runtimeAnimations = this._runtimeAnimations;
  42247. for (var index = 0; index < runtimeAnimations.length; index++) {
  42248. if (runtimeAnimations[index].animation.targetProperty === property) {
  42249. return runtimeAnimations[index].animation;
  42250. }
  42251. }
  42252. return null;
  42253. };
  42254. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  42255. var runtimeAnimations = this._runtimeAnimations;
  42256. for (var index = 0; index < runtimeAnimations.length; index++) {
  42257. if (runtimeAnimations[index].animation.targetProperty === property) {
  42258. return runtimeAnimations[index];
  42259. }
  42260. }
  42261. return null;
  42262. };
  42263. Animatable.prototype.reset = function () {
  42264. var runtimeAnimations = this._runtimeAnimations;
  42265. for (var index = 0; index < runtimeAnimations.length; index++) {
  42266. runtimeAnimations[index].reset();
  42267. }
  42268. this._localDelayOffset = null;
  42269. this._pausedDelay = null;
  42270. var oldPauseState = this._paused;
  42271. this._paused = false;
  42272. this._animate(0);
  42273. this._paused = oldPauseState;
  42274. };
  42275. Animatable.prototype.enableBlending = function (blendingSpeed) {
  42276. var runtimeAnimations = this._runtimeAnimations;
  42277. for (var index = 0; index < runtimeAnimations.length; index++) {
  42278. runtimeAnimations[index].animation.enableBlending = true;
  42279. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  42280. }
  42281. };
  42282. Animatable.prototype.disableBlending = function () {
  42283. var runtimeAnimations = this._runtimeAnimations;
  42284. for (var index = 0; index < runtimeAnimations.length; index++) {
  42285. runtimeAnimations[index].animation.enableBlending = false;
  42286. }
  42287. };
  42288. Animatable.prototype.goToFrame = function (frame) {
  42289. var runtimeAnimations = this._runtimeAnimations;
  42290. if (runtimeAnimations[0]) {
  42291. var fps = runtimeAnimations[0].animation.framePerSecond;
  42292. var currentFrame = runtimeAnimations[0].currentFrame;
  42293. var adjustTime = frame - currentFrame;
  42294. var delay = adjustTime * 1000 / fps;
  42295. if (this._localDelayOffset === null) {
  42296. this._localDelayOffset = 0;
  42297. }
  42298. this._localDelayOffset -= delay;
  42299. }
  42300. for (var index = 0; index < runtimeAnimations.length; index++) {
  42301. runtimeAnimations[index].goToFrame(frame);
  42302. }
  42303. };
  42304. Animatable.prototype.pause = function () {
  42305. if (this._paused) {
  42306. return;
  42307. }
  42308. this._paused = true;
  42309. };
  42310. Animatable.prototype.restart = function () {
  42311. this._paused = false;
  42312. };
  42313. Animatable.prototype.stop = function (animationName) {
  42314. if (animationName) {
  42315. var idx = this._scene._activeAnimatables.indexOf(this);
  42316. if (idx > -1) {
  42317. var runtimeAnimations = this._runtimeAnimations;
  42318. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  42319. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  42320. continue;
  42321. }
  42322. runtimeAnimations[index].dispose();
  42323. runtimeAnimations.splice(index, 1);
  42324. }
  42325. if (runtimeAnimations.length == 0) {
  42326. this._scene._activeAnimatables.splice(idx, 1);
  42327. if (this.onAnimationEnd) {
  42328. this.onAnimationEnd();
  42329. }
  42330. }
  42331. }
  42332. }
  42333. else {
  42334. var index = this._scene._activeAnimatables.indexOf(this);
  42335. if (index > -1) {
  42336. this._scene._activeAnimatables.splice(index, 1);
  42337. var runtimeAnimations = this._runtimeAnimations;
  42338. for (var index = 0; index < runtimeAnimations.length; index++) {
  42339. runtimeAnimations[index].dispose();
  42340. }
  42341. if (this.onAnimationEnd) {
  42342. this.onAnimationEnd();
  42343. }
  42344. }
  42345. }
  42346. };
  42347. Animatable.prototype._animate = function (delay) {
  42348. if (this._paused) {
  42349. this.animationStarted = false;
  42350. if (this._pausedDelay === null) {
  42351. this._pausedDelay = delay;
  42352. }
  42353. return true;
  42354. }
  42355. if (this._localDelayOffset === null) {
  42356. this._localDelayOffset = delay;
  42357. }
  42358. else if (this._pausedDelay !== null) {
  42359. this._localDelayOffset += delay - this._pausedDelay;
  42360. this._pausedDelay = null;
  42361. }
  42362. // Animating
  42363. var running = false;
  42364. var runtimeAnimations = this._runtimeAnimations;
  42365. var index;
  42366. for (index = 0; index < runtimeAnimations.length; index++) {
  42367. var animation = runtimeAnimations[index];
  42368. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  42369. running = running || isRunning;
  42370. }
  42371. this.animationStarted = running;
  42372. if (!running) {
  42373. // Remove from active animatables
  42374. index = this._scene._activeAnimatables.indexOf(this);
  42375. this._scene._activeAnimatables.splice(index, 1);
  42376. // Dispose all runtime animations
  42377. for (index = 0; index < runtimeAnimations.length; index++) {
  42378. runtimeAnimations[index].dispose();
  42379. }
  42380. }
  42381. if (!running && this.onAnimationEnd) {
  42382. this.onAnimationEnd();
  42383. this.onAnimationEnd = null;
  42384. }
  42385. return running;
  42386. };
  42387. return Animatable;
  42388. }());
  42389. BABYLON.Animatable = Animatable;
  42390. })(BABYLON || (BABYLON = {}));
  42391. //# sourceMappingURL=babylon.animatable.js.map
  42392. var BABYLON;
  42393. (function (BABYLON) {
  42394. var EasingFunction = /** @class */ (function () {
  42395. function EasingFunction() {
  42396. // Properties
  42397. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  42398. }
  42399. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  42400. get: function () {
  42401. return EasingFunction._EASINGMODE_EASEIN;
  42402. },
  42403. enumerable: true,
  42404. configurable: true
  42405. });
  42406. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  42407. get: function () {
  42408. return EasingFunction._EASINGMODE_EASEOUT;
  42409. },
  42410. enumerable: true,
  42411. configurable: true
  42412. });
  42413. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  42414. get: function () {
  42415. return EasingFunction._EASINGMODE_EASEINOUT;
  42416. },
  42417. enumerable: true,
  42418. configurable: true
  42419. });
  42420. EasingFunction.prototype.setEasingMode = function (easingMode) {
  42421. var n = Math.min(Math.max(easingMode, 0), 2);
  42422. this._easingMode = n;
  42423. };
  42424. EasingFunction.prototype.getEasingMode = function () {
  42425. return this._easingMode;
  42426. };
  42427. EasingFunction.prototype.easeInCore = function (gradient) {
  42428. throw new Error('You must implement this method');
  42429. };
  42430. EasingFunction.prototype.ease = function (gradient) {
  42431. switch (this._easingMode) {
  42432. case EasingFunction.EASINGMODE_EASEIN:
  42433. return this.easeInCore(gradient);
  42434. case EasingFunction.EASINGMODE_EASEOUT:
  42435. return (1 - this.easeInCore(1 - gradient));
  42436. }
  42437. if (gradient >= 0.5) {
  42438. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  42439. }
  42440. return (this.easeInCore(gradient * 2) * 0.5);
  42441. };
  42442. //Statics
  42443. EasingFunction._EASINGMODE_EASEIN = 0;
  42444. EasingFunction._EASINGMODE_EASEOUT = 1;
  42445. EasingFunction._EASINGMODE_EASEINOUT = 2;
  42446. return EasingFunction;
  42447. }());
  42448. BABYLON.EasingFunction = EasingFunction;
  42449. var CircleEase = /** @class */ (function (_super) {
  42450. __extends(CircleEase, _super);
  42451. function CircleEase() {
  42452. return _super !== null && _super.apply(this, arguments) || this;
  42453. }
  42454. CircleEase.prototype.easeInCore = function (gradient) {
  42455. gradient = Math.max(0, Math.min(1, gradient));
  42456. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  42457. };
  42458. return CircleEase;
  42459. }(EasingFunction));
  42460. BABYLON.CircleEase = CircleEase;
  42461. var BackEase = /** @class */ (function (_super) {
  42462. __extends(BackEase, _super);
  42463. function BackEase(amplitude) {
  42464. if (amplitude === void 0) { amplitude = 1; }
  42465. var _this = _super.call(this) || this;
  42466. _this.amplitude = amplitude;
  42467. return _this;
  42468. }
  42469. BackEase.prototype.easeInCore = function (gradient) {
  42470. var num = Math.max(0, this.amplitude);
  42471. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  42472. };
  42473. return BackEase;
  42474. }(EasingFunction));
  42475. BABYLON.BackEase = BackEase;
  42476. var BounceEase = /** @class */ (function (_super) {
  42477. __extends(BounceEase, _super);
  42478. function BounceEase(bounces, bounciness) {
  42479. if (bounces === void 0) { bounces = 3; }
  42480. if (bounciness === void 0) { bounciness = 2; }
  42481. var _this = _super.call(this) || this;
  42482. _this.bounces = bounces;
  42483. _this.bounciness = bounciness;
  42484. return _this;
  42485. }
  42486. BounceEase.prototype.easeInCore = function (gradient) {
  42487. var y = Math.max(0.0, this.bounces);
  42488. var bounciness = this.bounciness;
  42489. if (bounciness <= 1.0) {
  42490. bounciness = 1.001;
  42491. }
  42492. var num9 = Math.pow(bounciness, y);
  42493. var num5 = 1.0 - bounciness;
  42494. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  42495. var num15 = gradient * num4;
  42496. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  42497. var num3 = Math.floor(num65);
  42498. var num13 = num3 + 1.0;
  42499. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  42500. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  42501. var num7 = (num8 + num12) * 0.5;
  42502. var num6 = gradient - num7;
  42503. var num2 = num7 - num8;
  42504. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  42505. };
  42506. return BounceEase;
  42507. }(EasingFunction));
  42508. BABYLON.BounceEase = BounceEase;
  42509. var CubicEase = /** @class */ (function (_super) {
  42510. __extends(CubicEase, _super);
  42511. function CubicEase() {
  42512. return _super !== null && _super.apply(this, arguments) || this;
  42513. }
  42514. CubicEase.prototype.easeInCore = function (gradient) {
  42515. return (gradient * gradient * gradient);
  42516. };
  42517. return CubicEase;
  42518. }(EasingFunction));
  42519. BABYLON.CubicEase = CubicEase;
  42520. var ElasticEase = /** @class */ (function (_super) {
  42521. __extends(ElasticEase, _super);
  42522. function ElasticEase(oscillations, springiness) {
  42523. if (oscillations === void 0) { oscillations = 3; }
  42524. if (springiness === void 0) { springiness = 3; }
  42525. var _this = _super.call(this) || this;
  42526. _this.oscillations = oscillations;
  42527. _this.springiness = springiness;
  42528. return _this;
  42529. }
  42530. ElasticEase.prototype.easeInCore = function (gradient) {
  42531. var num2;
  42532. var num3 = Math.max(0.0, this.oscillations);
  42533. var num = Math.max(0.0, this.springiness);
  42534. if (num == 0) {
  42535. num2 = gradient;
  42536. }
  42537. else {
  42538. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  42539. }
  42540. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  42541. };
  42542. return ElasticEase;
  42543. }(EasingFunction));
  42544. BABYLON.ElasticEase = ElasticEase;
  42545. var ExponentialEase = /** @class */ (function (_super) {
  42546. __extends(ExponentialEase, _super);
  42547. function ExponentialEase(exponent) {
  42548. if (exponent === void 0) { exponent = 2; }
  42549. var _this = _super.call(this) || this;
  42550. _this.exponent = exponent;
  42551. return _this;
  42552. }
  42553. ExponentialEase.prototype.easeInCore = function (gradient) {
  42554. if (this.exponent <= 0) {
  42555. return gradient;
  42556. }
  42557. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  42558. };
  42559. return ExponentialEase;
  42560. }(EasingFunction));
  42561. BABYLON.ExponentialEase = ExponentialEase;
  42562. var PowerEase = /** @class */ (function (_super) {
  42563. __extends(PowerEase, _super);
  42564. function PowerEase(power) {
  42565. if (power === void 0) { power = 2; }
  42566. var _this = _super.call(this) || this;
  42567. _this.power = power;
  42568. return _this;
  42569. }
  42570. PowerEase.prototype.easeInCore = function (gradient) {
  42571. var y = Math.max(0.0, this.power);
  42572. return Math.pow(gradient, y);
  42573. };
  42574. return PowerEase;
  42575. }(EasingFunction));
  42576. BABYLON.PowerEase = PowerEase;
  42577. var QuadraticEase = /** @class */ (function (_super) {
  42578. __extends(QuadraticEase, _super);
  42579. function QuadraticEase() {
  42580. return _super !== null && _super.apply(this, arguments) || this;
  42581. }
  42582. QuadraticEase.prototype.easeInCore = function (gradient) {
  42583. return (gradient * gradient);
  42584. };
  42585. return QuadraticEase;
  42586. }(EasingFunction));
  42587. BABYLON.QuadraticEase = QuadraticEase;
  42588. var QuarticEase = /** @class */ (function (_super) {
  42589. __extends(QuarticEase, _super);
  42590. function QuarticEase() {
  42591. return _super !== null && _super.apply(this, arguments) || this;
  42592. }
  42593. QuarticEase.prototype.easeInCore = function (gradient) {
  42594. return (gradient * gradient * gradient * gradient);
  42595. };
  42596. return QuarticEase;
  42597. }(EasingFunction));
  42598. BABYLON.QuarticEase = QuarticEase;
  42599. var QuinticEase = /** @class */ (function (_super) {
  42600. __extends(QuinticEase, _super);
  42601. function QuinticEase() {
  42602. return _super !== null && _super.apply(this, arguments) || this;
  42603. }
  42604. QuinticEase.prototype.easeInCore = function (gradient) {
  42605. return (gradient * gradient * gradient * gradient * gradient);
  42606. };
  42607. return QuinticEase;
  42608. }(EasingFunction));
  42609. BABYLON.QuinticEase = QuinticEase;
  42610. var SineEase = /** @class */ (function (_super) {
  42611. __extends(SineEase, _super);
  42612. function SineEase() {
  42613. return _super !== null && _super.apply(this, arguments) || this;
  42614. }
  42615. SineEase.prototype.easeInCore = function (gradient) {
  42616. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  42617. };
  42618. return SineEase;
  42619. }(EasingFunction));
  42620. BABYLON.SineEase = SineEase;
  42621. var BezierCurveEase = /** @class */ (function (_super) {
  42622. __extends(BezierCurveEase, _super);
  42623. function BezierCurveEase(x1, y1, x2, y2) {
  42624. if (x1 === void 0) { x1 = 0; }
  42625. if (y1 === void 0) { y1 = 0; }
  42626. if (x2 === void 0) { x2 = 1; }
  42627. if (y2 === void 0) { y2 = 1; }
  42628. var _this = _super.call(this) || this;
  42629. _this.x1 = x1;
  42630. _this.y1 = y1;
  42631. _this.x2 = x2;
  42632. _this.y2 = y2;
  42633. return _this;
  42634. }
  42635. BezierCurveEase.prototype.easeInCore = function (gradient) {
  42636. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  42637. };
  42638. return BezierCurveEase;
  42639. }(EasingFunction));
  42640. BABYLON.BezierCurveEase = BezierCurveEase;
  42641. })(BABYLON || (BABYLON = {}));
  42642. //# sourceMappingURL=babylon.easing.js.map
  42643. var BABYLON;
  42644. (function (BABYLON) {
  42645. var Condition = /** @class */ (function () {
  42646. function Condition(actionManager) {
  42647. this._actionManager = actionManager;
  42648. }
  42649. Condition.prototype.isValid = function () {
  42650. return true;
  42651. };
  42652. Condition.prototype._getProperty = function (propertyPath) {
  42653. return this._actionManager._getProperty(propertyPath);
  42654. };
  42655. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  42656. return this._actionManager._getEffectiveTarget(target, propertyPath);
  42657. };
  42658. Condition.prototype.serialize = function () {
  42659. };
  42660. Condition.prototype._serialize = function (serializedCondition) {
  42661. return {
  42662. type: 2,
  42663. children: [],
  42664. name: serializedCondition.name,
  42665. properties: serializedCondition.properties
  42666. };
  42667. };
  42668. return Condition;
  42669. }());
  42670. BABYLON.Condition = Condition;
  42671. var ValueCondition = /** @class */ (function (_super) {
  42672. __extends(ValueCondition, _super);
  42673. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  42674. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  42675. var _this = _super.call(this, actionManager) || this;
  42676. _this.propertyPath = propertyPath;
  42677. _this.value = value;
  42678. _this.operator = operator;
  42679. _this._target = target;
  42680. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  42681. _this._property = _this._getProperty(_this.propertyPath);
  42682. return _this;
  42683. }
  42684. Object.defineProperty(ValueCondition, "IsEqual", {
  42685. get: function () {
  42686. return ValueCondition._IsEqual;
  42687. },
  42688. enumerable: true,
  42689. configurable: true
  42690. });
  42691. Object.defineProperty(ValueCondition, "IsDifferent", {
  42692. get: function () {
  42693. return ValueCondition._IsDifferent;
  42694. },
  42695. enumerable: true,
  42696. configurable: true
  42697. });
  42698. Object.defineProperty(ValueCondition, "IsGreater", {
  42699. get: function () {
  42700. return ValueCondition._IsGreater;
  42701. },
  42702. enumerable: true,
  42703. configurable: true
  42704. });
  42705. Object.defineProperty(ValueCondition, "IsLesser", {
  42706. get: function () {
  42707. return ValueCondition._IsLesser;
  42708. },
  42709. enumerable: true,
  42710. configurable: true
  42711. });
  42712. // Methods
  42713. ValueCondition.prototype.isValid = function () {
  42714. switch (this.operator) {
  42715. case ValueCondition.IsGreater:
  42716. return this._effectiveTarget[this._property] > this.value;
  42717. case ValueCondition.IsLesser:
  42718. return this._effectiveTarget[this._property] < this.value;
  42719. case ValueCondition.IsEqual:
  42720. case ValueCondition.IsDifferent:
  42721. var check;
  42722. if (this.value.equals) {
  42723. check = this.value.equals(this._effectiveTarget[this._property]);
  42724. }
  42725. else {
  42726. check = this.value === this._effectiveTarget[this._property];
  42727. }
  42728. return this.operator === ValueCondition.IsEqual ? check : !check;
  42729. }
  42730. return false;
  42731. };
  42732. ValueCondition.prototype.serialize = function () {
  42733. return this._serialize({
  42734. name: "ValueCondition",
  42735. properties: [
  42736. BABYLON.Action._GetTargetProperty(this._target),
  42737. { name: "propertyPath", value: this.propertyPath },
  42738. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  42739. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  42740. ]
  42741. });
  42742. };
  42743. ValueCondition.GetOperatorName = function (operator) {
  42744. switch (operator) {
  42745. case ValueCondition._IsEqual: return "IsEqual";
  42746. case ValueCondition._IsDifferent: return "IsDifferent";
  42747. case ValueCondition._IsGreater: return "IsGreater";
  42748. case ValueCondition._IsLesser: return "IsLesser";
  42749. default: return "";
  42750. }
  42751. };
  42752. // Statics
  42753. ValueCondition._IsEqual = 0;
  42754. ValueCondition._IsDifferent = 1;
  42755. ValueCondition._IsGreater = 2;
  42756. ValueCondition._IsLesser = 3;
  42757. return ValueCondition;
  42758. }(Condition));
  42759. BABYLON.ValueCondition = ValueCondition;
  42760. var PredicateCondition = /** @class */ (function (_super) {
  42761. __extends(PredicateCondition, _super);
  42762. function PredicateCondition(actionManager, predicate) {
  42763. var _this = _super.call(this, actionManager) || this;
  42764. _this.predicate = predicate;
  42765. return _this;
  42766. }
  42767. PredicateCondition.prototype.isValid = function () {
  42768. return this.predicate();
  42769. };
  42770. return PredicateCondition;
  42771. }(Condition));
  42772. BABYLON.PredicateCondition = PredicateCondition;
  42773. var StateCondition = /** @class */ (function (_super) {
  42774. __extends(StateCondition, _super);
  42775. function StateCondition(actionManager, target, value) {
  42776. var _this = _super.call(this, actionManager) || this;
  42777. _this.value = value;
  42778. _this._target = target;
  42779. return _this;
  42780. }
  42781. // Methods
  42782. StateCondition.prototype.isValid = function () {
  42783. return this._target.state === this.value;
  42784. };
  42785. StateCondition.prototype.serialize = function () {
  42786. return this._serialize({
  42787. name: "StateCondition",
  42788. properties: [
  42789. BABYLON.Action._GetTargetProperty(this._target),
  42790. { name: "value", value: this.value }
  42791. ]
  42792. });
  42793. };
  42794. return StateCondition;
  42795. }(Condition));
  42796. BABYLON.StateCondition = StateCondition;
  42797. })(BABYLON || (BABYLON = {}));
  42798. //# sourceMappingURL=babylon.condition.js.map
  42799. var BABYLON;
  42800. (function (BABYLON) {
  42801. var Action = /** @class */ (function () {
  42802. function Action(triggerOptions, condition) {
  42803. this.triggerOptions = triggerOptions;
  42804. this.onBeforeExecuteObservable = new BABYLON.Observable();
  42805. if (triggerOptions.parameter) {
  42806. this.trigger = triggerOptions.trigger;
  42807. this._triggerParameter = triggerOptions.parameter;
  42808. }
  42809. else {
  42810. this.trigger = triggerOptions;
  42811. }
  42812. this._nextActiveAction = this;
  42813. this._condition = condition;
  42814. }
  42815. // Methods
  42816. Action.prototype._prepare = function () {
  42817. };
  42818. Action.prototype.getTriggerParameter = function () {
  42819. return this._triggerParameter;
  42820. };
  42821. Action.prototype._executeCurrent = function (evt) {
  42822. if (this._nextActiveAction._condition) {
  42823. var condition = this._nextActiveAction._condition;
  42824. var currentRenderId = this._actionManager.getScene().getRenderId();
  42825. // We cache the current evaluation for the current frame
  42826. if (condition._evaluationId === currentRenderId) {
  42827. if (!condition._currentResult) {
  42828. return;
  42829. }
  42830. }
  42831. else {
  42832. condition._evaluationId = currentRenderId;
  42833. if (!condition.isValid()) {
  42834. condition._currentResult = false;
  42835. return;
  42836. }
  42837. condition._currentResult = true;
  42838. }
  42839. }
  42840. this.onBeforeExecuteObservable.notifyObservers(this);
  42841. this._nextActiveAction.execute(evt);
  42842. this.skipToNextActiveAction();
  42843. };
  42844. Action.prototype.execute = function (evt) {
  42845. };
  42846. Action.prototype.skipToNextActiveAction = function () {
  42847. if (this._nextActiveAction._child) {
  42848. if (!this._nextActiveAction._child._actionManager) {
  42849. this._nextActiveAction._child._actionManager = this._actionManager;
  42850. }
  42851. this._nextActiveAction = this._nextActiveAction._child;
  42852. }
  42853. else {
  42854. this._nextActiveAction = this;
  42855. }
  42856. };
  42857. Action.prototype.then = function (action) {
  42858. this._child = action;
  42859. action._actionManager = this._actionManager;
  42860. action._prepare();
  42861. return action;
  42862. };
  42863. Action.prototype._getProperty = function (propertyPath) {
  42864. return this._actionManager._getProperty(propertyPath);
  42865. };
  42866. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  42867. return this._actionManager._getEffectiveTarget(target, propertyPath);
  42868. };
  42869. Action.prototype.serialize = function (parent) {
  42870. };
  42871. // Called by BABYLON.Action objects in serialize(...). Internal use
  42872. Action.prototype._serialize = function (serializedAction, parent) {
  42873. var serializationObject = {
  42874. type: 1,
  42875. children: [],
  42876. name: serializedAction.name,
  42877. properties: serializedAction.properties || []
  42878. };
  42879. // Serialize child
  42880. if (this._child) {
  42881. this._child.serialize(serializationObject);
  42882. }
  42883. // Check if "this" has a condition
  42884. if (this._condition) {
  42885. var serializedCondition = this._condition.serialize();
  42886. serializedCondition.children.push(serializationObject);
  42887. if (parent) {
  42888. parent.children.push(serializedCondition);
  42889. }
  42890. return serializedCondition;
  42891. }
  42892. if (parent) {
  42893. parent.children.push(serializationObject);
  42894. }
  42895. return serializationObject;
  42896. };
  42897. Action._SerializeValueAsString = function (value) {
  42898. if (typeof value === "number") {
  42899. return value.toString();
  42900. }
  42901. if (typeof value === "boolean") {
  42902. return value ? "true" : "false";
  42903. }
  42904. if (value instanceof BABYLON.Vector2) {
  42905. return value.x + ", " + value.y;
  42906. }
  42907. if (value instanceof BABYLON.Vector3) {
  42908. return value.x + ", " + value.y + ", " + value.z;
  42909. }
  42910. if (value instanceof BABYLON.Color3) {
  42911. return value.r + ", " + value.g + ", " + value.b;
  42912. }
  42913. if (value instanceof BABYLON.Color4) {
  42914. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  42915. }
  42916. return value; // string
  42917. };
  42918. Action._GetTargetProperty = function (target) {
  42919. return {
  42920. name: "target",
  42921. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  42922. : target instanceof BABYLON.Light ? "LightProperties"
  42923. : target instanceof BABYLON.Camera ? "CameraProperties"
  42924. : "SceneProperties",
  42925. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  42926. };
  42927. };
  42928. return Action;
  42929. }());
  42930. BABYLON.Action = Action;
  42931. })(BABYLON || (BABYLON = {}));
  42932. //# sourceMappingURL=babylon.action.js.map
  42933. var BABYLON;
  42934. (function (BABYLON) {
  42935. /**
  42936. * ActionEvent is the event beint sent when an action is triggered.
  42937. */
  42938. var ActionEvent = /** @class */ (function () {
  42939. /**
  42940. * @param source The mesh or sprite that triggered the action.
  42941. * @param pointerX The X mouse cursor position at the time of the event
  42942. * @param pointerY The Y mouse cursor position at the time of the event
  42943. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  42944. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  42945. */
  42946. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  42947. this.source = source;
  42948. this.pointerX = pointerX;
  42949. this.pointerY = pointerY;
  42950. this.meshUnderPointer = meshUnderPointer;
  42951. this.sourceEvent = sourceEvent;
  42952. this.additionalData = additionalData;
  42953. }
  42954. /**
  42955. * Helper function to auto-create an ActionEvent from a source mesh.
  42956. * @param source The source mesh that triggered the event
  42957. * @param evt {Event} The original (browser) event
  42958. */
  42959. ActionEvent.CreateNew = function (source, evt, additionalData) {
  42960. var scene = source.getScene();
  42961. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  42962. };
  42963. /**
  42964. * Helper function to auto-create an ActionEvent from a source mesh.
  42965. * @param source The source sprite that triggered the event
  42966. * @param scene Scene associated with the sprite
  42967. * @param evt {Event} The original (browser) event
  42968. */
  42969. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  42970. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  42971. };
  42972. /**
  42973. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  42974. * @param scene the scene where the event occurred
  42975. * @param evt {Event} The original (browser) event
  42976. */
  42977. ActionEvent.CreateNewFromScene = function (scene, evt) {
  42978. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  42979. };
  42980. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  42981. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  42982. };
  42983. return ActionEvent;
  42984. }());
  42985. BABYLON.ActionEvent = ActionEvent;
  42986. /**
  42987. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  42988. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  42989. */
  42990. var ActionManager = /** @class */ (function () {
  42991. function ActionManager(scene) {
  42992. // Members
  42993. this.actions = new Array();
  42994. this.hoverCursor = '';
  42995. this._scene = scene;
  42996. scene._actionManagers.push(this);
  42997. }
  42998. Object.defineProperty(ActionManager, "NothingTrigger", {
  42999. get: function () {
  43000. return ActionManager._NothingTrigger;
  43001. },
  43002. enumerable: true,
  43003. configurable: true
  43004. });
  43005. Object.defineProperty(ActionManager, "OnPickTrigger", {
  43006. get: function () {
  43007. return ActionManager._OnPickTrigger;
  43008. },
  43009. enumerable: true,
  43010. configurable: true
  43011. });
  43012. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  43013. get: function () {
  43014. return ActionManager._OnLeftPickTrigger;
  43015. },
  43016. enumerable: true,
  43017. configurable: true
  43018. });
  43019. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  43020. get: function () {
  43021. return ActionManager._OnRightPickTrigger;
  43022. },
  43023. enumerable: true,
  43024. configurable: true
  43025. });
  43026. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  43027. get: function () {
  43028. return ActionManager._OnCenterPickTrigger;
  43029. },
  43030. enumerable: true,
  43031. configurable: true
  43032. });
  43033. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  43034. get: function () {
  43035. return ActionManager._OnPickDownTrigger;
  43036. },
  43037. enumerable: true,
  43038. configurable: true
  43039. });
  43040. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  43041. get: function () {
  43042. return ActionManager._OnDoublePickTrigger;
  43043. },
  43044. enumerable: true,
  43045. configurable: true
  43046. });
  43047. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  43048. get: function () {
  43049. return ActionManager._OnPickUpTrigger;
  43050. },
  43051. enumerable: true,
  43052. configurable: true
  43053. });
  43054. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  43055. /// This trigger will only be raised if you also declared a OnPickDown
  43056. get: function () {
  43057. return ActionManager._OnPickOutTrigger;
  43058. },
  43059. enumerable: true,
  43060. configurable: true
  43061. });
  43062. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  43063. get: function () {
  43064. return ActionManager._OnLongPressTrigger;
  43065. },
  43066. enumerable: true,
  43067. configurable: true
  43068. });
  43069. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  43070. get: function () {
  43071. return ActionManager._OnPointerOverTrigger;
  43072. },
  43073. enumerable: true,
  43074. configurable: true
  43075. });
  43076. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  43077. get: function () {
  43078. return ActionManager._OnPointerOutTrigger;
  43079. },
  43080. enumerable: true,
  43081. configurable: true
  43082. });
  43083. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  43084. get: function () {
  43085. return ActionManager._OnEveryFrameTrigger;
  43086. },
  43087. enumerable: true,
  43088. configurable: true
  43089. });
  43090. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  43091. get: function () {
  43092. return ActionManager._OnIntersectionEnterTrigger;
  43093. },
  43094. enumerable: true,
  43095. configurable: true
  43096. });
  43097. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  43098. get: function () {
  43099. return ActionManager._OnIntersectionExitTrigger;
  43100. },
  43101. enumerable: true,
  43102. configurable: true
  43103. });
  43104. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  43105. get: function () {
  43106. return ActionManager._OnKeyDownTrigger;
  43107. },
  43108. enumerable: true,
  43109. configurable: true
  43110. });
  43111. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  43112. get: function () {
  43113. return ActionManager._OnKeyUpTrigger;
  43114. },
  43115. enumerable: true,
  43116. configurable: true
  43117. });
  43118. // Methods
  43119. ActionManager.prototype.dispose = function () {
  43120. var index = this._scene._actionManagers.indexOf(this);
  43121. for (var i = 0; i < this.actions.length; i++) {
  43122. var action = this.actions[i];
  43123. ActionManager.Triggers[action.trigger]--;
  43124. if (ActionManager.Triggers[action.trigger] === 0) {
  43125. delete ActionManager.Triggers[action.trigger];
  43126. }
  43127. }
  43128. if (index > -1) {
  43129. this._scene._actionManagers.splice(index, 1);
  43130. }
  43131. };
  43132. ActionManager.prototype.getScene = function () {
  43133. return this._scene;
  43134. };
  43135. /**
  43136. * Does this action manager handles actions of any of the given triggers
  43137. * @param {number[]} triggers - the triggers to be tested
  43138. * @return {boolean} whether one (or more) of the triggers is handeled
  43139. */
  43140. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  43141. for (var index = 0; index < this.actions.length; index++) {
  43142. var action = this.actions[index];
  43143. if (triggers.indexOf(action.trigger) > -1) {
  43144. return true;
  43145. }
  43146. }
  43147. return false;
  43148. };
  43149. /**
  43150. * Does this action manager handles actions of a given trigger
  43151. * @param {number} trigger - the trigger to be tested
  43152. * @return {boolean} whether the trigger is handeled
  43153. */
  43154. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  43155. for (var index = 0; index < this.actions.length; index++) {
  43156. var action = this.actions[index];
  43157. if (action.trigger === trigger) {
  43158. return true;
  43159. }
  43160. }
  43161. return false;
  43162. };
  43163. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  43164. /**
  43165. * Does this action manager has pointer triggers
  43166. * @return {boolean} whether or not it has pointer triggers
  43167. */
  43168. get: function () {
  43169. for (var index = 0; index < this.actions.length; index++) {
  43170. var action = this.actions[index];
  43171. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  43172. return true;
  43173. }
  43174. }
  43175. return false;
  43176. },
  43177. enumerable: true,
  43178. configurable: true
  43179. });
  43180. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  43181. /**
  43182. * Does this action manager has pick triggers
  43183. * @return {boolean} whether or not it has pick triggers
  43184. */
  43185. get: function () {
  43186. for (var index = 0; index < this.actions.length; index++) {
  43187. var action = this.actions[index];
  43188. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  43189. return true;
  43190. }
  43191. }
  43192. return false;
  43193. },
  43194. enumerable: true,
  43195. configurable: true
  43196. });
  43197. Object.defineProperty(ActionManager, "HasTriggers", {
  43198. /**
  43199. * Does exist one action manager with at least one trigger
  43200. * @return {boolean} whether or not it exists one action manager with one trigger
  43201. **/
  43202. get: function () {
  43203. for (var t in ActionManager.Triggers) {
  43204. if (ActionManager.Triggers.hasOwnProperty(t)) {
  43205. return true;
  43206. }
  43207. }
  43208. return false;
  43209. },
  43210. enumerable: true,
  43211. configurable: true
  43212. });
  43213. Object.defineProperty(ActionManager, "HasPickTriggers", {
  43214. /**
  43215. * Does exist one action manager with at least one pick trigger
  43216. * @return {boolean} whether or not it exists one action manager with one pick trigger
  43217. **/
  43218. get: function () {
  43219. for (var t in ActionManager.Triggers) {
  43220. if (ActionManager.Triggers.hasOwnProperty(t)) {
  43221. var t_int = parseInt(t);
  43222. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  43223. return true;
  43224. }
  43225. }
  43226. }
  43227. return false;
  43228. },
  43229. enumerable: true,
  43230. configurable: true
  43231. });
  43232. /**
  43233. * Does exist one action manager that handles actions of a given trigger
  43234. * @param {number} trigger - the trigger to be tested
  43235. * @return {boolean} whether the trigger is handeled by at least one action manager
  43236. **/
  43237. ActionManager.HasSpecificTrigger = function (trigger) {
  43238. for (var t in ActionManager.Triggers) {
  43239. if (ActionManager.Triggers.hasOwnProperty(t)) {
  43240. var t_int = parseInt(t);
  43241. if (t_int === trigger) {
  43242. return true;
  43243. }
  43244. }
  43245. }
  43246. return false;
  43247. };
  43248. /**
  43249. * Registers an action to this action manager
  43250. * @param {BABYLON.Action} action - the action to be registered
  43251. * @return {BABYLON.Action} the action amended (prepared) after registration
  43252. */
  43253. ActionManager.prototype.registerAction = function (action) {
  43254. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  43255. if (this.getScene().actionManager !== this) {
  43256. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  43257. return null;
  43258. }
  43259. }
  43260. this.actions.push(action);
  43261. if (ActionManager.Triggers[action.trigger]) {
  43262. ActionManager.Triggers[action.trigger]++;
  43263. }
  43264. else {
  43265. ActionManager.Triggers[action.trigger] = 1;
  43266. }
  43267. action._actionManager = this;
  43268. action._prepare();
  43269. return action;
  43270. };
  43271. /**
  43272. * Process a specific trigger
  43273. * @param {number} trigger - the trigger to process
  43274. * @param evt {BABYLON.ActionEvent} the event details to be processed
  43275. */
  43276. ActionManager.prototype.processTrigger = function (trigger, evt) {
  43277. for (var index = 0; index < this.actions.length; index++) {
  43278. var action = this.actions[index];
  43279. if (action.trigger === trigger) {
  43280. if (evt) {
  43281. if (trigger === ActionManager.OnKeyUpTrigger
  43282. || trigger === ActionManager.OnKeyDownTrigger) {
  43283. var parameter = action.getTriggerParameter();
  43284. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  43285. if (!parameter.toLowerCase) {
  43286. continue;
  43287. }
  43288. var lowerCase = parameter.toLowerCase();
  43289. if (lowerCase !== evt.sourceEvent.key) {
  43290. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  43291. var actualkey = String.fromCharCode(unicode).toLowerCase();
  43292. if (actualkey !== lowerCase) {
  43293. continue;
  43294. }
  43295. }
  43296. }
  43297. }
  43298. }
  43299. action._executeCurrent(evt);
  43300. }
  43301. }
  43302. };
  43303. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  43304. var properties = propertyPath.split(".");
  43305. for (var index = 0; index < properties.length - 1; index++) {
  43306. target = target[properties[index]];
  43307. }
  43308. return target;
  43309. };
  43310. ActionManager.prototype._getProperty = function (propertyPath) {
  43311. var properties = propertyPath.split(".");
  43312. return properties[properties.length - 1];
  43313. };
  43314. ActionManager.prototype.serialize = function (name) {
  43315. var root = {
  43316. children: new Array(),
  43317. name: name,
  43318. type: 3,
  43319. properties: new Array() // Empty for root but required
  43320. };
  43321. for (var i = 0; i < this.actions.length; i++) {
  43322. var triggerObject = {
  43323. type: 0,
  43324. children: new Array(),
  43325. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  43326. properties: new Array()
  43327. };
  43328. var triggerOptions = this.actions[i].triggerOptions;
  43329. if (triggerOptions && typeof triggerOptions !== "number") {
  43330. if (triggerOptions.parameter instanceof BABYLON.Node) {
  43331. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  43332. }
  43333. else {
  43334. var parameter = {};
  43335. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  43336. if (triggerOptions.parameter.mesh) {
  43337. parameter._meshId = triggerOptions.parameter.mesh.id;
  43338. }
  43339. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  43340. }
  43341. }
  43342. // Serialize child action, recursively
  43343. this.actions[i].serialize(triggerObject);
  43344. // Add serialized trigger
  43345. root.children.push(triggerObject);
  43346. }
  43347. return root;
  43348. };
  43349. ActionManager.Parse = function (parsedActions, object, scene) {
  43350. var actionManager = new ActionManager(scene);
  43351. if (object === null)
  43352. scene.actionManager = actionManager;
  43353. else
  43354. object.actionManager = actionManager;
  43355. // instanciate a new object
  43356. var instanciate = function (name, params) {
  43357. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  43358. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  43359. newInstance.constructor.apply(newInstance, params);
  43360. return newInstance;
  43361. };
  43362. var parseParameter = function (name, value, target, propertyPath) {
  43363. if (propertyPath === null) {
  43364. // String, boolean or float
  43365. var floatValue = parseFloat(value);
  43366. if (value === "true" || value === "false")
  43367. return value === "true";
  43368. else
  43369. return isNaN(floatValue) ? value : floatValue;
  43370. }
  43371. var effectiveTarget = propertyPath.split(".");
  43372. var values = value.split(",");
  43373. // Get effective Target
  43374. for (var i = 0; i < effectiveTarget.length; i++) {
  43375. target = target[effectiveTarget[i]];
  43376. }
  43377. // Return appropriate value with its type
  43378. if (typeof (target) === "boolean")
  43379. return values[0] === "true";
  43380. if (typeof (target) === "string")
  43381. return values[0];
  43382. // Parameters with multiple values such as Vector3 etc.
  43383. var split = new Array();
  43384. for (var i = 0; i < values.length; i++)
  43385. split.push(parseFloat(values[i]));
  43386. if (target instanceof BABYLON.Vector3)
  43387. return BABYLON.Vector3.FromArray(split);
  43388. if (target instanceof BABYLON.Vector4)
  43389. return BABYLON.Vector4.FromArray(split);
  43390. if (target instanceof BABYLON.Color3)
  43391. return BABYLON.Color3.FromArray(split);
  43392. if (target instanceof BABYLON.Color4)
  43393. return BABYLON.Color4.FromArray(split);
  43394. return parseFloat(values[0]);
  43395. };
  43396. // traverse graph per trigger
  43397. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  43398. if (combineArray === void 0) { combineArray = null; }
  43399. if (parsedAction.detached)
  43400. return;
  43401. var parameters = new Array();
  43402. var target = null;
  43403. var propertyPath = null;
  43404. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  43405. // Parameters
  43406. if (parsedAction.type === 2)
  43407. parameters.push(actionManager);
  43408. else
  43409. parameters.push(trigger);
  43410. if (combine) {
  43411. var actions = new Array();
  43412. for (var j = 0; j < parsedAction.combine.length; j++) {
  43413. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  43414. }
  43415. parameters.push(actions);
  43416. }
  43417. else {
  43418. for (var i = 0; i < parsedAction.properties.length; i++) {
  43419. var value = parsedAction.properties[i].value;
  43420. var name = parsedAction.properties[i].name;
  43421. var targetType = parsedAction.properties[i].targetType;
  43422. if (name === "target")
  43423. if (targetType !== null && targetType === "SceneProperties")
  43424. value = target = scene;
  43425. else
  43426. value = target = scene.getNodeByName(value);
  43427. else if (name === "parent")
  43428. value = scene.getNodeByName(value);
  43429. else if (name === "sound")
  43430. value = scene.getSoundByName(value);
  43431. else if (name !== "propertyPath") {
  43432. if (parsedAction.type === 2 && name === "operator")
  43433. value = BABYLON.ValueCondition[value];
  43434. else
  43435. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  43436. }
  43437. else {
  43438. propertyPath = value;
  43439. }
  43440. parameters.push(value);
  43441. }
  43442. }
  43443. if (combineArray === null) {
  43444. parameters.push(condition);
  43445. }
  43446. else {
  43447. parameters.push(null);
  43448. }
  43449. // If interpolate value action
  43450. if (parsedAction.name === "InterpolateValueAction") {
  43451. var param = parameters[parameters.length - 2];
  43452. parameters[parameters.length - 1] = param;
  43453. parameters[parameters.length - 2] = condition;
  43454. }
  43455. // Action or condition(s) and not CombineAction
  43456. var newAction = instanciate(parsedAction.name, parameters);
  43457. if (newAction instanceof BABYLON.Condition && condition !== null) {
  43458. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  43459. if (action)
  43460. action.then(nothing);
  43461. else
  43462. actionManager.registerAction(nothing);
  43463. action = nothing;
  43464. }
  43465. if (combineArray === null) {
  43466. if (newAction instanceof BABYLON.Condition) {
  43467. condition = newAction;
  43468. newAction = action;
  43469. }
  43470. else {
  43471. condition = null;
  43472. if (action)
  43473. action.then(newAction);
  43474. else
  43475. actionManager.registerAction(newAction);
  43476. }
  43477. }
  43478. else {
  43479. combineArray.push(newAction);
  43480. }
  43481. for (var i = 0; i < parsedAction.children.length; i++)
  43482. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  43483. };
  43484. // triggers
  43485. for (var i = 0; i < parsedActions.children.length; i++) {
  43486. var triggerParams;
  43487. var trigger = parsedActions.children[i];
  43488. if (trigger.properties.length > 0) {
  43489. var param = trigger.properties[0].value;
  43490. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  43491. if (value._meshId) {
  43492. value.mesh = scene.getMeshByID(value._meshId);
  43493. }
  43494. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  43495. }
  43496. else
  43497. triggerParams = ActionManager[trigger.name];
  43498. for (var j = 0; j < trigger.children.length; j++) {
  43499. if (!trigger.detached)
  43500. traverse(trigger.children[j], triggerParams, null, null);
  43501. }
  43502. }
  43503. };
  43504. ActionManager.GetTriggerName = function (trigger) {
  43505. switch (trigger) {
  43506. case 0: return "NothingTrigger";
  43507. case 1: return "OnPickTrigger";
  43508. case 2: return "OnLeftPickTrigger";
  43509. case 3: return "OnRightPickTrigger";
  43510. case 4: return "OnCenterPickTrigger";
  43511. case 5: return "OnPickDownTrigger";
  43512. case 6: return "OnPickUpTrigger";
  43513. case 7: return "OnLongPressTrigger";
  43514. case 8: return "OnPointerOverTrigger";
  43515. case 9: return "OnPointerOutTrigger";
  43516. case 10: return "OnEveryFrameTrigger";
  43517. case 11: return "OnIntersectionEnterTrigger";
  43518. case 12: return "OnIntersectionExitTrigger";
  43519. case 13: return "OnKeyDownTrigger";
  43520. case 14: return "OnKeyUpTrigger";
  43521. case 15: return "OnPickOutTrigger";
  43522. default: return "";
  43523. }
  43524. };
  43525. // Statics
  43526. ActionManager._NothingTrigger = 0;
  43527. ActionManager._OnPickTrigger = 1;
  43528. ActionManager._OnLeftPickTrigger = 2;
  43529. ActionManager._OnRightPickTrigger = 3;
  43530. ActionManager._OnCenterPickTrigger = 4;
  43531. ActionManager._OnPickDownTrigger = 5;
  43532. ActionManager._OnDoublePickTrigger = 6;
  43533. ActionManager._OnPickUpTrigger = 7;
  43534. ActionManager._OnLongPressTrigger = 8;
  43535. ActionManager._OnPointerOverTrigger = 9;
  43536. ActionManager._OnPointerOutTrigger = 10;
  43537. ActionManager._OnEveryFrameTrigger = 11;
  43538. ActionManager._OnIntersectionEnterTrigger = 12;
  43539. ActionManager._OnIntersectionExitTrigger = 13;
  43540. ActionManager._OnKeyDownTrigger = 14;
  43541. ActionManager._OnKeyUpTrigger = 15;
  43542. ActionManager._OnPickOutTrigger = 16;
  43543. ActionManager.Triggers = {};
  43544. return ActionManager;
  43545. }());
  43546. BABYLON.ActionManager = ActionManager;
  43547. })(BABYLON || (BABYLON = {}));
  43548. //# sourceMappingURL=babylon.actionManager.js.map
  43549. var BABYLON;
  43550. (function (BABYLON) {
  43551. var InterpolateValueAction = /** @class */ (function (_super) {
  43552. __extends(InterpolateValueAction, _super);
  43553. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  43554. if (duration === void 0) { duration = 1000; }
  43555. var _this = _super.call(this, triggerOptions, condition) || this;
  43556. _this.propertyPath = propertyPath;
  43557. _this.value = value;
  43558. _this.duration = duration;
  43559. _this.stopOtherAnimations = stopOtherAnimations;
  43560. _this.onInterpolationDone = onInterpolationDone;
  43561. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  43562. _this._target = _this._effectiveTarget = target;
  43563. return _this;
  43564. }
  43565. InterpolateValueAction.prototype._prepare = function () {
  43566. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43567. this._property = this._getProperty(this.propertyPath);
  43568. };
  43569. InterpolateValueAction.prototype.execute = function () {
  43570. var _this = this;
  43571. var scene = this._actionManager.getScene();
  43572. var keys = [
  43573. {
  43574. frame: 0,
  43575. value: this._effectiveTarget[this._property]
  43576. }, {
  43577. frame: 100,
  43578. value: this.value
  43579. }
  43580. ];
  43581. var dataType;
  43582. if (typeof this.value === "number") {
  43583. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  43584. }
  43585. else if (this.value instanceof BABYLON.Color3) {
  43586. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  43587. }
  43588. else if (this.value instanceof BABYLON.Vector3) {
  43589. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  43590. }
  43591. else if (this.value instanceof BABYLON.Matrix) {
  43592. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  43593. }
  43594. else if (this.value instanceof BABYLON.Quaternion) {
  43595. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  43596. }
  43597. else {
  43598. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  43599. return;
  43600. }
  43601. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  43602. animation.setKeys(keys);
  43603. if (this.stopOtherAnimations) {
  43604. scene.stopAnimation(this._effectiveTarget);
  43605. }
  43606. var wrapper = function () {
  43607. _this.onInterpolationDoneObservable.notifyObservers(_this);
  43608. if (_this.onInterpolationDone) {
  43609. _this.onInterpolationDone();
  43610. }
  43611. };
  43612. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  43613. };
  43614. InterpolateValueAction.prototype.serialize = function (parent) {
  43615. return _super.prototype._serialize.call(this, {
  43616. name: "InterpolateValueAction",
  43617. properties: [
  43618. BABYLON.Action._GetTargetProperty(this._target),
  43619. { name: "propertyPath", value: this.propertyPath },
  43620. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  43621. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  43622. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  43623. ]
  43624. }, parent);
  43625. };
  43626. return InterpolateValueAction;
  43627. }(BABYLON.Action));
  43628. BABYLON.InterpolateValueAction = InterpolateValueAction;
  43629. })(BABYLON || (BABYLON = {}));
  43630. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  43631. var BABYLON;
  43632. (function (BABYLON) {
  43633. var SwitchBooleanAction = /** @class */ (function (_super) {
  43634. __extends(SwitchBooleanAction, _super);
  43635. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  43636. var _this = _super.call(this, triggerOptions, condition) || this;
  43637. _this.propertyPath = propertyPath;
  43638. _this._target = _this._effectiveTarget = target;
  43639. return _this;
  43640. }
  43641. SwitchBooleanAction.prototype._prepare = function () {
  43642. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43643. this._property = this._getProperty(this.propertyPath);
  43644. };
  43645. SwitchBooleanAction.prototype.execute = function () {
  43646. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  43647. };
  43648. SwitchBooleanAction.prototype.serialize = function (parent) {
  43649. return _super.prototype._serialize.call(this, {
  43650. name: "SwitchBooleanAction",
  43651. properties: [
  43652. BABYLON.Action._GetTargetProperty(this._target),
  43653. { name: "propertyPath", value: this.propertyPath }
  43654. ]
  43655. }, parent);
  43656. };
  43657. return SwitchBooleanAction;
  43658. }(BABYLON.Action));
  43659. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  43660. var SetStateAction = /** @class */ (function (_super) {
  43661. __extends(SetStateAction, _super);
  43662. function SetStateAction(triggerOptions, target, value, condition) {
  43663. var _this = _super.call(this, triggerOptions, condition) || this;
  43664. _this.value = value;
  43665. _this._target = target;
  43666. return _this;
  43667. }
  43668. SetStateAction.prototype.execute = function () {
  43669. this._target.state = this.value;
  43670. };
  43671. SetStateAction.prototype.serialize = function (parent) {
  43672. return _super.prototype._serialize.call(this, {
  43673. name: "SetStateAction",
  43674. properties: [
  43675. BABYLON.Action._GetTargetProperty(this._target),
  43676. { name: "value", value: this.value }
  43677. ]
  43678. }, parent);
  43679. };
  43680. return SetStateAction;
  43681. }(BABYLON.Action));
  43682. BABYLON.SetStateAction = SetStateAction;
  43683. var SetValueAction = /** @class */ (function (_super) {
  43684. __extends(SetValueAction, _super);
  43685. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  43686. var _this = _super.call(this, triggerOptions, condition) || this;
  43687. _this.propertyPath = propertyPath;
  43688. _this.value = value;
  43689. _this._target = _this._effectiveTarget = target;
  43690. return _this;
  43691. }
  43692. SetValueAction.prototype._prepare = function () {
  43693. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43694. this._property = this._getProperty(this.propertyPath);
  43695. };
  43696. SetValueAction.prototype.execute = function () {
  43697. this._effectiveTarget[this._property] = this.value;
  43698. if (this._target.markAsDirty) {
  43699. this._target.markAsDirty(this._property);
  43700. }
  43701. };
  43702. SetValueAction.prototype.serialize = function (parent) {
  43703. return _super.prototype._serialize.call(this, {
  43704. name: "SetValueAction",
  43705. properties: [
  43706. BABYLON.Action._GetTargetProperty(this._target),
  43707. { name: "propertyPath", value: this.propertyPath },
  43708. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  43709. ]
  43710. }, parent);
  43711. };
  43712. return SetValueAction;
  43713. }(BABYLON.Action));
  43714. BABYLON.SetValueAction = SetValueAction;
  43715. var IncrementValueAction = /** @class */ (function (_super) {
  43716. __extends(IncrementValueAction, _super);
  43717. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  43718. var _this = _super.call(this, triggerOptions, condition) || this;
  43719. _this.propertyPath = propertyPath;
  43720. _this.value = value;
  43721. _this._target = _this._effectiveTarget = target;
  43722. return _this;
  43723. }
  43724. IncrementValueAction.prototype._prepare = function () {
  43725. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43726. this._property = this._getProperty(this.propertyPath);
  43727. if (typeof this._effectiveTarget[this._property] !== "number") {
  43728. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  43729. }
  43730. };
  43731. IncrementValueAction.prototype.execute = function () {
  43732. this._effectiveTarget[this._property] += this.value;
  43733. if (this._target.markAsDirty) {
  43734. this._target.markAsDirty(this._property);
  43735. }
  43736. };
  43737. IncrementValueAction.prototype.serialize = function (parent) {
  43738. return _super.prototype._serialize.call(this, {
  43739. name: "IncrementValueAction",
  43740. properties: [
  43741. BABYLON.Action._GetTargetProperty(this._target),
  43742. { name: "propertyPath", value: this.propertyPath },
  43743. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  43744. ]
  43745. }, parent);
  43746. };
  43747. return IncrementValueAction;
  43748. }(BABYLON.Action));
  43749. BABYLON.IncrementValueAction = IncrementValueAction;
  43750. var PlayAnimationAction = /** @class */ (function (_super) {
  43751. __extends(PlayAnimationAction, _super);
  43752. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  43753. var _this = _super.call(this, triggerOptions, condition) || this;
  43754. _this.from = from;
  43755. _this.to = to;
  43756. _this.loop = loop;
  43757. _this._target = target;
  43758. return _this;
  43759. }
  43760. PlayAnimationAction.prototype._prepare = function () {
  43761. };
  43762. PlayAnimationAction.prototype.execute = function () {
  43763. var scene = this._actionManager.getScene();
  43764. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  43765. };
  43766. PlayAnimationAction.prototype.serialize = function (parent) {
  43767. return _super.prototype._serialize.call(this, {
  43768. name: "PlayAnimationAction",
  43769. properties: [
  43770. BABYLON.Action._GetTargetProperty(this._target),
  43771. { name: "from", value: String(this.from) },
  43772. { name: "to", value: String(this.to) },
  43773. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  43774. ]
  43775. }, parent);
  43776. };
  43777. return PlayAnimationAction;
  43778. }(BABYLON.Action));
  43779. BABYLON.PlayAnimationAction = PlayAnimationAction;
  43780. var StopAnimationAction = /** @class */ (function (_super) {
  43781. __extends(StopAnimationAction, _super);
  43782. function StopAnimationAction(triggerOptions, target, condition) {
  43783. var _this = _super.call(this, triggerOptions, condition) || this;
  43784. _this._target = target;
  43785. return _this;
  43786. }
  43787. StopAnimationAction.prototype._prepare = function () {
  43788. };
  43789. StopAnimationAction.prototype.execute = function () {
  43790. var scene = this._actionManager.getScene();
  43791. scene.stopAnimation(this._target);
  43792. };
  43793. StopAnimationAction.prototype.serialize = function (parent) {
  43794. return _super.prototype._serialize.call(this, {
  43795. name: "StopAnimationAction",
  43796. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  43797. }, parent);
  43798. };
  43799. return StopAnimationAction;
  43800. }(BABYLON.Action));
  43801. BABYLON.StopAnimationAction = StopAnimationAction;
  43802. var DoNothingAction = /** @class */ (function (_super) {
  43803. __extends(DoNothingAction, _super);
  43804. function DoNothingAction(triggerOptions, condition) {
  43805. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  43806. return _super.call(this, triggerOptions, condition) || this;
  43807. }
  43808. DoNothingAction.prototype.execute = function () {
  43809. };
  43810. DoNothingAction.prototype.serialize = function (parent) {
  43811. return _super.prototype._serialize.call(this, {
  43812. name: "DoNothingAction",
  43813. properties: []
  43814. }, parent);
  43815. };
  43816. return DoNothingAction;
  43817. }(BABYLON.Action));
  43818. BABYLON.DoNothingAction = DoNothingAction;
  43819. var CombineAction = /** @class */ (function (_super) {
  43820. __extends(CombineAction, _super);
  43821. function CombineAction(triggerOptions, children, condition) {
  43822. var _this = _super.call(this, triggerOptions, condition) || this;
  43823. _this.children = children;
  43824. return _this;
  43825. }
  43826. CombineAction.prototype._prepare = function () {
  43827. for (var index = 0; index < this.children.length; index++) {
  43828. this.children[index]._actionManager = this._actionManager;
  43829. this.children[index]._prepare();
  43830. }
  43831. };
  43832. CombineAction.prototype.execute = function (evt) {
  43833. for (var index = 0; index < this.children.length; index++) {
  43834. this.children[index].execute(evt);
  43835. }
  43836. };
  43837. CombineAction.prototype.serialize = function (parent) {
  43838. var serializationObject = _super.prototype._serialize.call(this, {
  43839. name: "CombineAction",
  43840. properties: [],
  43841. combine: []
  43842. }, parent);
  43843. for (var i = 0; i < this.children.length; i++) {
  43844. serializationObject.combine.push(this.children[i].serialize(null));
  43845. }
  43846. return serializationObject;
  43847. };
  43848. return CombineAction;
  43849. }(BABYLON.Action));
  43850. BABYLON.CombineAction = CombineAction;
  43851. var ExecuteCodeAction = /** @class */ (function (_super) {
  43852. __extends(ExecuteCodeAction, _super);
  43853. function ExecuteCodeAction(triggerOptions, func, condition) {
  43854. var _this = _super.call(this, triggerOptions, condition) || this;
  43855. _this.func = func;
  43856. return _this;
  43857. }
  43858. ExecuteCodeAction.prototype.execute = function (evt) {
  43859. this.func(evt);
  43860. };
  43861. return ExecuteCodeAction;
  43862. }(BABYLON.Action));
  43863. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  43864. var SetParentAction = /** @class */ (function (_super) {
  43865. __extends(SetParentAction, _super);
  43866. function SetParentAction(triggerOptions, target, parent, condition) {
  43867. var _this = _super.call(this, triggerOptions, condition) || this;
  43868. _this._target = target;
  43869. _this._parent = parent;
  43870. return _this;
  43871. }
  43872. SetParentAction.prototype._prepare = function () {
  43873. };
  43874. SetParentAction.prototype.execute = function () {
  43875. if (this._target.parent === this._parent) {
  43876. return;
  43877. }
  43878. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  43879. invertParentWorldMatrix.invert();
  43880. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  43881. this._target.parent = this._parent;
  43882. };
  43883. SetParentAction.prototype.serialize = function (parent) {
  43884. return _super.prototype._serialize.call(this, {
  43885. name: "SetParentAction",
  43886. properties: [
  43887. BABYLON.Action._GetTargetProperty(this._target),
  43888. BABYLON.Action._GetTargetProperty(this._parent),
  43889. ]
  43890. }, parent);
  43891. };
  43892. return SetParentAction;
  43893. }(BABYLON.Action));
  43894. BABYLON.SetParentAction = SetParentAction;
  43895. var PlaySoundAction = /** @class */ (function (_super) {
  43896. __extends(PlaySoundAction, _super);
  43897. function PlaySoundAction(triggerOptions, sound, condition) {
  43898. var _this = _super.call(this, triggerOptions, condition) || this;
  43899. _this._sound = sound;
  43900. return _this;
  43901. }
  43902. PlaySoundAction.prototype._prepare = function () {
  43903. };
  43904. PlaySoundAction.prototype.execute = function () {
  43905. if (this._sound !== undefined)
  43906. this._sound.play();
  43907. };
  43908. PlaySoundAction.prototype.serialize = function (parent) {
  43909. return _super.prototype._serialize.call(this, {
  43910. name: "PlaySoundAction",
  43911. properties: [{ name: "sound", value: this._sound.name }]
  43912. }, parent);
  43913. };
  43914. return PlaySoundAction;
  43915. }(BABYLON.Action));
  43916. BABYLON.PlaySoundAction = PlaySoundAction;
  43917. var StopSoundAction = /** @class */ (function (_super) {
  43918. __extends(StopSoundAction, _super);
  43919. function StopSoundAction(triggerOptions, sound, condition) {
  43920. var _this = _super.call(this, triggerOptions, condition) || this;
  43921. _this._sound = sound;
  43922. return _this;
  43923. }
  43924. StopSoundAction.prototype._prepare = function () {
  43925. };
  43926. StopSoundAction.prototype.execute = function () {
  43927. if (this._sound !== undefined)
  43928. this._sound.stop();
  43929. };
  43930. StopSoundAction.prototype.serialize = function (parent) {
  43931. return _super.prototype._serialize.call(this, {
  43932. name: "StopSoundAction",
  43933. properties: [{ name: "sound", value: this._sound.name }]
  43934. }, parent);
  43935. };
  43936. return StopSoundAction;
  43937. }(BABYLON.Action));
  43938. BABYLON.StopSoundAction = StopSoundAction;
  43939. })(BABYLON || (BABYLON = {}));
  43940. //# sourceMappingURL=babylon.directActions.js.map
  43941. var BABYLON;
  43942. (function (BABYLON) {
  43943. var SpriteManager = /** @class */ (function () {
  43944. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  43945. if (epsilon === void 0) { epsilon = 0.01; }
  43946. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43947. this.name = name;
  43948. this.sprites = new Array();
  43949. this.renderingGroupId = 0;
  43950. this.layerMask = 0x0FFFFFFF;
  43951. this.fogEnabled = true;
  43952. this.isPickable = false;
  43953. /**
  43954. * An event triggered when the manager is disposed.
  43955. * @type {BABYLON.Observable}
  43956. */
  43957. this.onDisposeObservable = new BABYLON.Observable();
  43958. this._vertexBuffers = {};
  43959. this._capacity = capacity;
  43960. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  43961. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43962. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43963. if (cellSize.width && cellSize.height) {
  43964. this.cellWidth = cellSize.width;
  43965. this.cellHeight = cellSize.height;
  43966. }
  43967. else if (cellSize !== undefined) {
  43968. this.cellWidth = cellSize;
  43969. this.cellHeight = cellSize;
  43970. }
  43971. else {
  43972. return;
  43973. }
  43974. this._epsilon = epsilon;
  43975. this._scene = scene;
  43976. this._scene.spriteManagers.push(this);
  43977. var indices = [];
  43978. var index = 0;
  43979. for (var count = 0; count < capacity; count++) {
  43980. indices.push(index);
  43981. indices.push(index + 1);
  43982. indices.push(index + 2);
  43983. indices.push(index);
  43984. indices.push(index + 2);
  43985. indices.push(index + 3);
  43986. index += 4;
  43987. }
  43988. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  43989. // VBO
  43990. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  43991. this._vertexData = new Float32Array(capacity * 16 * 4);
  43992. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  43993. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  43994. var options = this._buffer.createVertexBuffer("options", 4, 4);
  43995. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  43996. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  43997. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  43998. this._vertexBuffers["options"] = options;
  43999. this._vertexBuffers["cellInfo"] = cellInfo;
  44000. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  44001. // Effects
  44002. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  44003. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  44004. }
  44005. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  44006. set: function (callback) {
  44007. if (this._onDisposeObserver) {
  44008. this.onDisposeObservable.remove(this._onDisposeObserver);
  44009. }
  44010. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  44011. },
  44012. enumerable: true,
  44013. configurable: true
  44014. });
  44015. Object.defineProperty(SpriteManager.prototype, "texture", {
  44016. get: function () {
  44017. return this._spriteTexture;
  44018. },
  44019. set: function (value) {
  44020. this._spriteTexture = value;
  44021. },
  44022. enumerable: true,
  44023. configurable: true
  44024. });
  44025. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  44026. var arrayOffset = index * 16;
  44027. if (offsetX === 0)
  44028. offsetX = this._epsilon;
  44029. else if (offsetX === 1)
  44030. offsetX = 1 - this._epsilon;
  44031. if (offsetY === 0)
  44032. offsetY = this._epsilon;
  44033. else if (offsetY === 1)
  44034. offsetY = 1 - this._epsilon;
  44035. this._vertexData[arrayOffset] = sprite.position.x;
  44036. this._vertexData[arrayOffset + 1] = sprite.position.y;
  44037. this._vertexData[arrayOffset + 2] = sprite.position.z;
  44038. this._vertexData[arrayOffset + 3] = sprite.angle;
  44039. this._vertexData[arrayOffset + 4] = sprite.width;
  44040. this._vertexData[arrayOffset + 5] = sprite.height;
  44041. this._vertexData[arrayOffset + 6] = offsetX;
  44042. this._vertexData[arrayOffset + 7] = offsetY;
  44043. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  44044. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  44045. var offset = (sprite.cellIndex / rowSize) >> 0;
  44046. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  44047. this._vertexData[arrayOffset + 11] = offset;
  44048. // Color
  44049. this._vertexData[arrayOffset + 12] = sprite.color.r;
  44050. this._vertexData[arrayOffset + 13] = sprite.color.g;
  44051. this._vertexData[arrayOffset + 14] = sprite.color.b;
  44052. this._vertexData[arrayOffset + 15] = sprite.color.a;
  44053. };
  44054. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  44055. var count = Math.min(this._capacity, this.sprites.length);
  44056. var min = BABYLON.Vector3.Zero();
  44057. var max = BABYLON.Vector3.Zero();
  44058. var distance = Number.MAX_VALUE;
  44059. var currentSprite = null;
  44060. var cameraSpacePosition = BABYLON.Vector3.Zero();
  44061. var cameraView = camera.getViewMatrix();
  44062. for (var index = 0; index < count; index++) {
  44063. var sprite = this.sprites[index];
  44064. if (!sprite) {
  44065. continue;
  44066. }
  44067. if (predicate) {
  44068. if (!predicate(sprite)) {
  44069. continue;
  44070. }
  44071. }
  44072. else if (!sprite.isPickable) {
  44073. continue;
  44074. }
  44075. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  44076. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  44077. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  44078. if (ray.intersectsBoxMinMax(min, max)) {
  44079. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  44080. if (distance > currentDistance) {
  44081. distance = currentDistance;
  44082. currentSprite = sprite;
  44083. if (fastCheck) {
  44084. break;
  44085. }
  44086. }
  44087. }
  44088. }
  44089. if (currentSprite) {
  44090. var result = new BABYLON.PickingInfo();
  44091. result.hit = true;
  44092. result.pickedSprite = currentSprite;
  44093. result.distance = distance;
  44094. return result;
  44095. }
  44096. return null;
  44097. };
  44098. SpriteManager.prototype.render = function () {
  44099. // Check
  44100. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  44101. return;
  44102. var engine = this._scene.getEngine();
  44103. var baseSize = this._spriteTexture.getBaseSize();
  44104. // Sprites
  44105. var deltaTime = engine.getDeltaTime();
  44106. var max = Math.min(this._capacity, this.sprites.length);
  44107. var rowSize = baseSize.width / this.cellWidth;
  44108. var offset = 0;
  44109. for (var index = 0; index < max; index++) {
  44110. var sprite = this.sprites[index];
  44111. if (!sprite) {
  44112. continue;
  44113. }
  44114. sprite._animate(deltaTime);
  44115. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  44116. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  44117. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  44118. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  44119. }
  44120. this._buffer.update(this._vertexData);
  44121. // Render
  44122. var effect = this._effectBase;
  44123. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  44124. effect = this._effectFog;
  44125. }
  44126. engine.enableEffect(effect);
  44127. var viewMatrix = this._scene.getViewMatrix();
  44128. effect.setTexture("diffuseSampler", this._spriteTexture);
  44129. effect.setMatrix("view", viewMatrix);
  44130. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  44131. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  44132. // Fog
  44133. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  44134. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  44135. effect.setColor3("vFogColor", this._scene.fogColor);
  44136. }
  44137. // VBOs
  44138. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  44139. // Draw order
  44140. engine.setDepthFunctionToLessOrEqual();
  44141. effect.setBool("alphaTest", true);
  44142. engine.setColorWrite(false);
  44143. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  44144. engine.setColorWrite(true);
  44145. effect.setBool("alphaTest", false);
  44146. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  44147. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  44148. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  44149. };
  44150. SpriteManager.prototype.dispose = function () {
  44151. if (this._buffer) {
  44152. this._buffer.dispose();
  44153. this._buffer = null;
  44154. }
  44155. if (this._indexBuffer) {
  44156. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  44157. this._indexBuffer = null;
  44158. }
  44159. if (this._spriteTexture) {
  44160. this._spriteTexture.dispose();
  44161. this._spriteTexture = null;
  44162. }
  44163. // Remove from scene
  44164. var index = this._scene.spriteManagers.indexOf(this);
  44165. this._scene.spriteManagers.splice(index, 1);
  44166. // Callback
  44167. this.onDisposeObservable.notifyObservers(this);
  44168. this.onDisposeObservable.clear();
  44169. };
  44170. return SpriteManager;
  44171. }());
  44172. BABYLON.SpriteManager = SpriteManager;
  44173. })(BABYLON || (BABYLON = {}));
  44174. //# sourceMappingURL=babylon.spriteManager.js.map
  44175. var BABYLON;
  44176. (function (BABYLON) {
  44177. var Sprite = /** @class */ (function () {
  44178. function Sprite(name, manager) {
  44179. this.name = name;
  44180. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44181. this.width = 1.0;
  44182. this.height = 1.0;
  44183. this.angle = 0;
  44184. this.cellIndex = 0;
  44185. this.invertU = 0;
  44186. this.invertV = 0;
  44187. this.animations = new Array();
  44188. this.isPickable = false;
  44189. this._animationStarted = false;
  44190. this._loopAnimation = false;
  44191. this._fromIndex = 0;
  44192. this._toIndex = 0;
  44193. this._delay = 0;
  44194. this._direction = 1;
  44195. this._time = 0;
  44196. this._manager = manager;
  44197. this._manager.sprites.push(this);
  44198. this.position = BABYLON.Vector3.Zero();
  44199. }
  44200. Object.defineProperty(Sprite.prototype, "size", {
  44201. get: function () {
  44202. return this.width;
  44203. },
  44204. set: function (value) {
  44205. this.width = value;
  44206. this.height = value;
  44207. },
  44208. enumerable: true,
  44209. configurable: true
  44210. });
  44211. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  44212. this._fromIndex = from;
  44213. this._toIndex = to;
  44214. this._loopAnimation = loop;
  44215. this._delay = delay;
  44216. this._animationStarted = true;
  44217. this._direction = from < to ? 1 : -1;
  44218. this.cellIndex = from;
  44219. this._time = 0;
  44220. this._onAnimationEnd = onAnimationEnd;
  44221. };
  44222. Sprite.prototype.stopAnimation = function () {
  44223. this._animationStarted = false;
  44224. };
  44225. Sprite.prototype._animate = function (deltaTime) {
  44226. if (!this._animationStarted)
  44227. return;
  44228. this._time += deltaTime;
  44229. if (this._time > this._delay) {
  44230. this._time = this._time % this._delay;
  44231. this.cellIndex += this._direction;
  44232. if (this.cellIndex > this._toIndex) {
  44233. if (this._loopAnimation) {
  44234. this.cellIndex = this._fromIndex;
  44235. }
  44236. else {
  44237. this.cellIndex = this._toIndex;
  44238. this._animationStarted = false;
  44239. if (this._onAnimationEnd) {
  44240. this._onAnimationEnd();
  44241. }
  44242. if (this.disposeWhenFinishedAnimating) {
  44243. this.dispose();
  44244. }
  44245. }
  44246. }
  44247. }
  44248. };
  44249. Sprite.prototype.dispose = function () {
  44250. for (var i = 0; i < this._manager.sprites.length; i++) {
  44251. if (this._manager.sprites[i] == this) {
  44252. this._manager.sprites.splice(i, 1);
  44253. }
  44254. }
  44255. };
  44256. return Sprite;
  44257. }());
  44258. BABYLON.Sprite = Sprite;
  44259. })(BABYLON || (BABYLON = {}));
  44260. //# sourceMappingURL=babylon.sprite.js.map
  44261. var BABYLON;
  44262. (function (BABYLON) {
  44263. var IntersectionInfo = /** @class */ (function () {
  44264. function IntersectionInfo(bu, bv, distance) {
  44265. this.bu = bu;
  44266. this.bv = bv;
  44267. this.distance = distance;
  44268. this.faceId = 0;
  44269. this.subMeshId = 0;
  44270. }
  44271. return IntersectionInfo;
  44272. }());
  44273. BABYLON.IntersectionInfo = IntersectionInfo;
  44274. var PickingInfo = /** @class */ (function () {
  44275. function PickingInfo() {
  44276. this.hit = false;
  44277. this.distance = 0;
  44278. this.pickedPoint = null;
  44279. this.pickedMesh = null;
  44280. this.bu = 0;
  44281. this.bv = 0;
  44282. this.faceId = -1;
  44283. this.subMeshId = 0;
  44284. this.pickedSprite = null;
  44285. }
  44286. // Methods
  44287. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  44288. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  44289. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  44290. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44291. return null;
  44292. }
  44293. var indices = this.pickedMesh.getIndices();
  44294. if (!indices) {
  44295. return null;
  44296. }
  44297. var result;
  44298. if (useVerticesNormals) {
  44299. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  44300. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  44301. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  44302. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  44303. normal0 = normal0.scale(this.bu);
  44304. normal1 = normal1.scale(this.bv);
  44305. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  44306. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  44307. }
  44308. else {
  44309. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44310. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  44311. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  44312. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  44313. var p1p2 = vertex1.subtract(vertex2);
  44314. var p3p2 = vertex3.subtract(vertex2);
  44315. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  44316. }
  44317. if (useWorldCoordinates) {
  44318. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  44319. }
  44320. return BABYLON.Vector3.Normalize(result);
  44321. };
  44322. PickingInfo.prototype.getTextureCoordinates = function () {
  44323. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  44324. return null;
  44325. }
  44326. var indices = this.pickedMesh.getIndices();
  44327. if (!indices) {
  44328. return null;
  44329. }
  44330. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  44331. if (!uvs) {
  44332. return null;
  44333. }
  44334. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  44335. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  44336. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  44337. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  44338. uv1 = uv1.scale(this.bu);
  44339. uv2 = uv2.scale(this.bv);
  44340. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  44341. };
  44342. return PickingInfo;
  44343. }());
  44344. BABYLON.PickingInfo = PickingInfo;
  44345. })(BABYLON || (BABYLON = {}));
  44346. //# sourceMappingURL=babylon.pickingInfo.js.map
  44347. var BABYLON;
  44348. (function (BABYLON) {
  44349. var Ray = /** @class */ (function () {
  44350. function Ray(origin, direction, length) {
  44351. if (length === void 0) { length = Number.MAX_VALUE; }
  44352. this.origin = origin;
  44353. this.direction = direction;
  44354. this.length = length;
  44355. }
  44356. // Methods
  44357. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  44358. var d = 0.0;
  44359. var maxValue = Number.MAX_VALUE;
  44360. var inv;
  44361. var min;
  44362. var max;
  44363. var temp;
  44364. if (Math.abs(this.direction.x) < 0.0000001) {
  44365. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  44366. return false;
  44367. }
  44368. }
  44369. else {
  44370. inv = 1.0 / this.direction.x;
  44371. min = (minimum.x - this.origin.x) * inv;
  44372. max = (maximum.x - this.origin.x) * inv;
  44373. if (max === -Infinity) {
  44374. max = Infinity;
  44375. }
  44376. if (min > max) {
  44377. temp = min;
  44378. min = max;
  44379. max = temp;
  44380. }
  44381. d = Math.max(min, d);
  44382. maxValue = Math.min(max, maxValue);
  44383. if (d > maxValue) {
  44384. return false;
  44385. }
  44386. }
  44387. if (Math.abs(this.direction.y) < 0.0000001) {
  44388. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  44389. return false;
  44390. }
  44391. }
  44392. else {
  44393. inv = 1.0 / this.direction.y;
  44394. min = (minimum.y - this.origin.y) * inv;
  44395. max = (maximum.y - this.origin.y) * inv;
  44396. if (max === -Infinity) {
  44397. max = Infinity;
  44398. }
  44399. if (min > max) {
  44400. temp = min;
  44401. min = max;
  44402. max = temp;
  44403. }
  44404. d = Math.max(min, d);
  44405. maxValue = Math.min(max, maxValue);
  44406. if (d > maxValue) {
  44407. return false;
  44408. }
  44409. }
  44410. if (Math.abs(this.direction.z) < 0.0000001) {
  44411. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  44412. return false;
  44413. }
  44414. }
  44415. else {
  44416. inv = 1.0 / this.direction.z;
  44417. min = (minimum.z - this.origin.z) * inv;
  44418. max = (maximum.z - this.origin.z) * inv;
  44419. if (max === -Infinity) {
  44420. max = Infinity;
  44421. }
  44422. if (min > max) {
  44423. temp = min;
  44424. min = max;
  44425. max = temp;
  44426. }
  44427. d = Math.max(min, d);
  44428. maxValue = Math.min(max, maxValue);
  44429. if (d > maxValue) {
  44430. return false;
  44431. }
  44432. }
  44433. return true;
  44434. };
  44435. Ray.prototype.intersectsBox = function (box) {
  44436. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  44437. };
  44438. Ray.prototype.intersectsSphere = function (sphere) {
  44439. var x = sphere.center.x - this.origin.x;
  44440. var y = sphere.center.y - this.origin.y;
  44441. var z = sphere.center.z - this.origin.z;
  44442. var pyth = (x * x) + (y * y) + (z * z);
  44443. var rr = sphere.radius * sphere.radius;
  44444. if (pyth <= rr) {
  44445. return true;
  44446. }
  44447. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  44448. if (dot < 0.0) {
  44449. return false;
  44450. }
  44451. var temp = pyth - (dot * dot);
  44452. return temp <= rr;
  44453. };
  44454. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  44455. if (!this._edge1) {
  44456. this._edge1 = BABYLON.Vector3.Zero();
  44457. this._edge2 = BABYLON.Vector3.Zero();
  44458. this._pvec = BABYLON.Vector3.Zero();
  44459. this._tvec = BABYLON.Vector3.Zero();
  44460. this._qvec = BABYLON.Vector3.Zero();
  44461. }
  44462. vertex1.subtractToRef(vertex0, this._edge1);
  44463. vertex2.subtractToRef(vertex0, this._edge2);
  44464. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  44465. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  44466. if (det === 0) {
  44467. return null;
  44468. }
  44469. var invdet = 1 / det;
  44470. this.origin.subtractToRef(vertex0, this._tvec);
  44471. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  44472. if (bu < 0 || bu > 1.0) {
  44473. return null;
  44474. }
  44475. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  44476. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  44477. if (bv < 0 || bu + bv > 1.0) {
  44478. return null;
  44479. }
  44480. //check if the distance is longer than the predefined length.
  44481. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  44482. if (distance > this.length) {
  44483. return null;
  44484. }
  44485. return new BABYLON.IntersectionInfo(bu, bv, distance);
  44486. };
  44487. Ray.prototype.intersectsPlane = function (plane) {
  44488. var distance;
  44489. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  44490. if (Math.abs(result1) < 9.99999997475243E-07) {
  44491. return null;
  44492. }
  44493. else {
  44494. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  44495. distance = (-plane.d - result2) / result1;
  44496. if (distance < 0.0) {
  44497. if (distance < -9.99999997475243E-07) {
  44498. return null;
  44499. }
  44500. else {
  44501. return 0;
  44502. }
  44503. }
  44504. return distance;
  44505. }
  44506. };
  44507. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  44508. var tm = BABYLON.Tmp.Matrix[0];
  44509. mesh.getWorldMatrix().invertToRef(tm);
  44510. if (this._tmpRay) {
  44511. Ray.TransformToRef(this, tm, this._tmpRay);
  44512. }
  44513. else {
  44514. this._tmpRay = Ray.Transform(this, tm);
  44515. }
  44516. return mesh.intersects(this._tmpRay, fastCheck);
  44517. };
  44518. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  44519. if (results) {
  44520. results.length = 0;
  44521. }
  44522. else {
  44523. results = [];
  44524. }
  44525. for (var i = 0; i < meshes.length; i++) {
  44526. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  44527. if (pickInfo.hit) {
  44528. results.push(pickInfo);
  44529. }
  44530. }
  44531. results.sort(this._comparePickingInfo);
  44532. return results;
  44533. };
  44534. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  44535. if (pickingInfoA.distance < pickingInfoB.distance) {
  44536. return -1;
  44537. }
  44538. else if (pickingInfoA.distance > pickingInfoB.distance) {
  44539. return 1;
  44540. }
  44541. else {
  44542. return 0;
  44543. }
  44544. };
  44545. /**
  44546. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  44547. * @param sega the first point of the segment to test the intersection against
  44548. * @param segb the second point of the segment to test the intersection against
  44549. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  44550. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  44551. */
  44552. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  44553. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  44554. var u = segb.subtract(sega);
  44555. var v = rsegb.subtract(this.origin);
  44556. var w = sega.subtract(this.origin);
  44557. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  44558. var b = BABYLON.Vector3.Dot(u, v);
  44559. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  44560. var d = BABYLON.Vector3.Dot(u, w);
  44561. var e = BABYLON.Vector3.Dot(v, w);
  44562. var D = a * c - b * b; // always >= 0
  44563. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  44564. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  44565. // compute the line parameters of the two closest points
  44566. if (D < Ray.smallnum) {
  44567. sN = 0.0; // force using point P0 on segment S1
  44568. sD = 1.0; // to prevent possible division by 0.0 later
  44569. tN = e;
  44570. tD = c;
  44571. }
  44572. else {
  44573. sN = (b * e - c * d);
  44574. tN = (a * e - b * d);
  44575. if (sN < 0.0) {
  44576. sN = 0.0;
  44577. tN = e;
  44578. tD = c;
  44579. }
  44580. else if (sN > sD) {
  44581. sN = sD;
  44582. tN = e + b;
  44583. tD = c;
  44584. }
  44585. }
  44586. if (tN < 0.0) {
  44587. tN = 0.0;
  44588. // recompute sc for this edge
  44589. if (-d < 0.0) {
  44590. sN = 0.0;
  44591. }
  44592. else if (-d > a)
  44593. sN = sD;
  44594. else {
  44595. sN = -d;
  44596. sD = a;
  44597. }
  44598. }
  44599. else if (tN > tD) {
  44600. tN = tD;
  44601. // recompute sc for this edge
  44602. if ((-d + b) < 0.0) {
  44603. sN = 0;
  44604. }
  44605. else if ((-d + b) > a) {
  44606. sN = sD;
  44607. }
  44608. else {
  44609. sN = (-d + b);
  44610. sD = a;
  44611. }
  44612. }
  44613. // finally do the division to get sc and tc
  44614. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  44615. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  44616. // get the difference of the two closest points
  44617. var qtc = v.multiplyByFloats(tc, tc, tc);
  44618. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  44619. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  44620. if (isIntersected) {
  44621. return qtc.length();
  44622. }
  44623. return -1;
  44624. };
  44625. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  44626. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  44627. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  44628. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  44629. this.direction.normalize();
  44630. return this;
  44631. };
  44632. // Statics
  44633. Ray.Zero = function () {
  44634. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  44635. };
  44636. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  44637. var result = Ray.Zero();
  44638. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  44639. };
  44640. /**
  44641. * 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
  44642. * transformed to the given world matrix.
  44643. * @param origin The origin point
  44644. * @param end The end point
  44645. * @param world a matrix to transform the ray to. Default is the identity matrix.
  44646. */
  44647. Ray.CreateNewFromTo = function (origin, end, world) {
  44648. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  44649. var direction = end.subtract(origin);
  44650. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  44651. direction.normalize();
  44652. return Ray.Transform(new Ray(origin, direction, length), world);
  44653. };
  44654. Ray.Transform = function (ray, matrix) {
  44655. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  44656. Ray.TransformToRef(ray, matrix, result);
  44657. return result;
  44658. };
  44659. Ray.TransformToRef = function (ray, matrix, result) {
  44660. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  44661. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  44662. result.length = ray.length;
  44663. var dir = result.direction;
  44664. var len = dir.length();
  44665. if (!(len === 0 || len === 1)) {
  44666. var num = 1.0 / len;
  44667. dir.x *= num;
  44668. dir.y *= num;
  44669. dir.z *= num;
  44670. result.length *= len;
  44671. }
  44672. };
  44673. Ray.smallnum = 0.00000001;
  44674. Ray.rayl = 10e8;
  44675. return Ray;
  44676. }());
  44677. BABYLON.Ray = Ray;
  44678. })(BABYLON || (BABYLON = {}));
  44679. //# sourceMappingURL=babylon.ray.js.map
  44680. var BABYLON;
  44681. (function (BABYLON) {
  44682. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  44683. if (boxMin.x > sphereCenter.x + sphereRadius)
  44684. return false;
  44685. if (sphereCenter.x - sphereRadius > boxMax.x)
  44686. return false;
  44687. if (boxMin.y > sphereCenter.y + sphereRadius)
  44688. return false;
  44689. if (sphereCenter.y - sphereRadius > boxMax.y)
  44690. return false;
  44691. if (boxMin.z > sphereCenter.z + sphereRadius)
  44692. return false;
  44693. if (sphereCenter.z - sphereRadius > boxMax.z)
  44694. return false;
  44695. return true;
  44696. };
  44697. var getLowestRoot = (function () {
  44698. var result = { root: 0, found: false };
  44699. return function (a, b, c, maxR) {
  44700. result.root = 0;
  44701. result.found = false;
  44702. var determinant = b * b - 4.0 * a * c;
  44703. if (determinant < 0)
  44704. return result;
  44705. var sqrtD = Math.sqrt(determinant);
  44706. var r1 = (-b - sqrtD) / (2.0 * a);
  44707. var r2 = (-b + sqrtD) / (2.0 * a);
  44708. if (r1 > r2) {
  44709. var temp = r2;
  44710. r2 = r1;
  44711. r1 = temp;
  44712. }
  44713. if (r1 > 0 && r1 < maxR) {
  44714. result.root = r1;
  44715. result.found = true;
  44716. return result;
  44717. }
  44718. if (r2 > 0 && r2 < maxR) {
  44719. result.root = r2;
  44720. result.found = true;
  44721. return result;
  44722. }
  44723. return result;
  44724. };
  44725. })();
  44726. var Collider = /** @class */ (function () {
  44727. function Collider() {
  44728. this._collisionPoint = BABYLON.Vector3.Zero();
  44729. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  44730. this._tempVector = BABYLON.Vector3.Zero();
  44731. this._tempVector2 = BABYLON.Vector3.Zero();
  44732. this._tempVector3 = BABYLON.Vector3.Zero();
  44733. this._tempVector4 = BABYLON.Vector3.Zero();
  44734. this._edge = BABYLON.Vector3.Zero();
  44735. this._baseToVertex = BABYLON.Vector3.Zero();
  44736. this._destinationPoint = BABYLON.Vector3.Zero();
  44737. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  44738. this._displacementVector = BABYLON.Vector3.Zero();
  44739. this._radius = BABYLON.Vector3.One();
  44740. this._retry = 0;
  44741. this._basePointWorld = BABYLON.Vector3.Zero();
  44742. this._velocityWorld = BABYLON.Vector3.Zero();
  44743. this._normalizedVelocity = BABYLON.Vector3.Zero();
  44744. this._collisionMask = -1;
  44745. }
  44746. Object.defineProperty(Collider.prototype, "collisionMask", {
  44747. get: function () {
  44748. return this._collisionMask;
  44749. },
  44750. set: function (mask) {
  44751. this._collisionMask = !isNaN(mask) ? mask : -1;
  44752. },
  44753. enumerable: true,
  44754. configurable: true
  44755. });
  44756. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  44757. /**
  44758. * Gets the plane normal used to compute the sliding response (in local space)
  44759. */
  44760. get: function () {
  44761. return this._slidePlaneNormal;
  44762. },
  44763. enumerable: true,
  44764. configurable: true
  44765. });
  44766. // Methods
  44767. Collider.prototype._initialize = function (source, dir, e) {
  44768. this._velocity = dir;
  44769. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  44770. this._basePoint = source;
  44771. source.multiplyToRef(this._radius, this._basePointWorld);
  44772. dir.multiplyToRef(this._radius, this._velocityWorld);
  44773. this._velocityWorldLength = this._velocityWorld.length();
  44774. this._epsilon = e;
  44775. this.collisionFound = false;
  44776. };
  44777. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  44778. pa.subtractToRef(point, this._tempVector);
  44779. pb.subtractToRef(point, this._tempVector2);
  44780. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  44781. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  44782. if (d < 0)
  44783. return false;
  44784. pc.subtractToRef(point, this._tempVector3);
  44785. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  44786. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  44787. if (d < 0)
  44788. return false;
  44789. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  44790. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  44791. return d >= 0;
  44792. };
  44793. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  44794. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  44795. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  44796. if (distance > this._velocityWorldLength + max + sphereRadius) {
  44797. return false;
  44798. }
  44799. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  44800. return false;
  44801. return true;
  44802. };
  44803. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  44804. var t0;
  44805. var embeddedInPlane = false;
  44806. //defensive programming, actually not needed.
  44807. if (!trianglePlaneArray) {
  44808. trianglePlaneArray = [];
  44809. }
  44810. if (!trianglePlaneArray[faceIndex]) {
  44811. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  44812. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  44813. }
  44814. var trianglePlane = trianglePlaneArray[faceIndex];
  44815. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  44816. return;
  44817. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  44818. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  44819. if (normalDotVelocity == 0) {
  44820. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  44821. return;
  44822. embeddedInPlane = true;
  44823. t0 = 0;
  44824. }
  44825. else {
  44826. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  44827. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  44828. if (t0 > t1) {
  44829. var temp = t1;
  44830. t1 = t0;
  44831. t0 = temp;
  44832. }
  44833. if (t0 > 1.0 || t1 < 0.0)
  44834. return;
  44835. if (t0 < 0)
  44836. t0 = 0;
  44837. if (t0 > 1.0)
  44838. t0 = 1.0;
  44839. }
  44840. this._collisionPoint.copyFromFloats(0, 0, 0);
  44841. var found = false;
  44842. var t = 1.0;
  44843. if (!embeddedInPlane) {
  44844. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  44845. this._velocity.scaleToRef(t0, this._tempVector);
  44846. this._planeIntersectionPoint.addInPlace(this._tempVector);
  44847. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  44848. found = true;
  44849. t = t0;
  44850. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  44851. }
  44852. }
  44853. if (!found) {
  44854. var velocitySquaredLength = this._velocity.lengthSquared();
  44855. var a = velocitySquaredLength;
  44856. this._basePoint.subtractToRef(p1, this._tempVector);
  44857. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  44858. var c = this._tempVector.lengthSquared() - 1.0;
  44859. var lowestRoot = getLowestRoot(a, b, c, t);
  44860. if (lowestRoot.found) {
  44861. t = lowestRoot.root;
  44862. found = true;
  44863. this._collisionPoint.copyFrom(p1);
  44864. }
  44865. this._basePoint.subtractToRef(p2, this._tempVector);
  44866. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  44867. c = this._tempVector.lengthSquared() - 1.0;
  44868. lowestRoot = getLowestRoot(a, b, c, t);
  44869. if (lowestRoot.found) {
  44870. t = lowestRoot.root;
  44871. found = true;
  44872. this._collisionPoint.copyFrom(p2);
  44873. }
  44874. this._basePoint.subtractToRef(p3, this._tempVector);
  44875. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  44876. c = this._tempVector.lengthSquared() - 1.0;
  44877. lowestRoot = getLowestRoot(a, b, c, t);
  44878. if (lowestRoot.found) {
  44879. t = lowestRoot.root;
  44880. found = true;
  44881. this._collisionPoint.copyFrom(p3);
  44882. }
  44883. p2.subtractToRef(p1, this._edge);
  44884. p1.subtractToRef(this._basePoint, this._baseToVertex);
  44885. var edgeSquaredLength = this._edge.lengthSquared();
  44886. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  44887. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  44888. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  44889. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  44890. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  44891. lowestRoot = getLowestRoot(a, b, c, t);
  44892. if (lowestRoot.found) {
  44893. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  44894. if (f >= 0.0 && f <= 1.0) {
  44895. t = lowestRoot.root;
  44896. found = true;
  44897. this._edge.scaleInPlace(f);
  44898. p1.addToRef(this._edge, this._collisionPoint);
  44899. }
  44900. }
  44901. p3.subtractToRef(p2, this._edge);
  44902. p2.subtractToRef(this._basePoint, this._baseToVertex);
  44903. edgeSquaredLength = this._edge.lengthSquared();
  44904. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  44905. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  44906. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  44907. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  44908. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  44909. lowestRoot = getLowestRoot(a, b, c, t);
  44910. if (lowestRoot.found) {
  44911. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  44912. if (f >= 0.0 && f <= 1.0) {
  44913. t = lowestRoot.root;
  44914. found = true;
  44915. this._edge.scaleInPlace(f);
  44916. p2.addToRef(this._edge, this._collisionPoint);
  44917. }
  44918. }
  44919. p1.subtractToRef(p3, this._edge);
  44920. p3.subtractToRef(this._basePoint, this._baseToVertex);
  44921. edgeSquaredLength = this._edge.lengthSquared();
  44922. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  44923. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  44924. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  44925. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  44926. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  44927. lowestRoot = getLowestRoot(a, b, c, t);
  44928. if (lowestRoot.found) {
  44929. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  44930. if (f >= 0.0 && f <= 1.0) {
  44931. t = lowestRoot.root;
  44932. found = true;
  44933. this._edge.scaleInPlace(f);
  44934. p3.addToRef(this._edge, this._collisionPoint);
  44935. }
  44936. }
  44937. }
  44938. if (found) {
  44939. var distToCollision = t * this._velocity.length();
  44940. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  44941. if (!this.intersectionPoint) {
  44942. this.intersectionPoint = this._collisionPoint.clone();
  44943. }
  44944. else {
  44945. this.intersectionPoint.copyFrom(this._collisionPoint);
  44946. }
  44947. this._nearestDistance = distToCollision;
  44948. this.collisionFound = true;
  44949. }
  44950. }
  44951. };
  44952. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  44953. for (var i = indexStart; i < indexEnd; i += 3) {
  44954. var p1 = pts[indices[i] - decal];
  44955. var p2 = pts[indices[i + 1] - decal];
  44956. var p3 = pts[indices[i + 2] - decal];
  44957. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  44958. }
  44959. };
  44960. Collider.prototype._getResponse = function (pos, vel) {
  44961. pos.addToRef(vel, this._destinationPoint);
  44962. vel.scaleInPlace((this._nearestDistance / vel.length()));
  44963. this._basePoint.addToRef(vel, pos);
  44964. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  44965. this._slidePlaneNormal.normalize();
  44966. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  44967. pos.addInPlace(this._displacementVector);
  44968. this.intersectionPoint.addInPlace(this._displacementVector);
  44969. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  44970. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  44971. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  44972. };
  44973. return Collider;
  44974. }());
  44975. BABYLON.Collider = Collider;
  44976. })(BABYLON || (BABYLON = {}));
  44977. //# sourceMappingURL=babylon.collider.js.map
  44978. var BABYLON;
  44979. (function (BABYLON) {
  44980. //WebWorker code will be inserted to this variable.
  44981. BABYLON.CollisionWorker = "";
  44982. var WorkerTaskType;
  44983. (function (WorkerTaskType) {
  44984. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  44985. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  44986. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  44987. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  44988. var WorkerReplyType;
  44989. (function (WorkerReplyType) {
  44990. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  44991. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  44992. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  44993. var CollisionCoordinatorWorker = /** @class */ (function () {
  44994. function CollisionCoordinatorWorker() {
  44995. var _this = this;
  44996. this._scaledPosition = BABYLON.Vector3.Zero();
  44997. this._scaledVelocity = BABYLON.Vector3.Zero();
  44998. this.onMeshUpdated = function (transformNode) {
  44999. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  45000. };
  45001. this.onGeometryUpdated = function (geometry) {
  45002. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  45003. };
  45004. this._afterRender = function () {
  45005. if (!_this._init)
  45006. return;
  45007. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  45008. return;
  45009. }
  45010. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  45011. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  45012. if (_this._runningUpdated > 4) {
  45013. return;
  45014. }
  45015. ++_this._runningUpdated;
  45016. var payload = {
  45017. updatedMeshes: _this._addUpdateMeshesList,
  45018. updatedGeometries: _this._addUpdateGeometriesList,
  45019. removedGeometries: _this._toRemoveGeometryArray,
  45020. removedMeshes: _this._toRemoveMeshesArray
  45021. };
  45022. var message = {
  45023. payload: payload,
  45024. taskType: WorkerTaskType.UPDATE
  45025. };
  45026. var serializable = [];
  45027. for (var id in payload.updatedGeometries) {
  45028. if (payload.updatedGeometries.hasOwnProperty(id)) {
  45029. //prepare transferables
  45030. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  45031. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  45032. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  45033. }
  45034. }
  45035. _this._worker.postMessage(message, serializable);
  45036. _this._addUpdateMeshesList = {};
  45037. _this._addUpdateGeometriesList = {};
  45038. _this._toRemoveGeometryArray = [];
  45039. _this._toRemoveMeshesArray = [];
  45040. };
  45041. this._onMessageFromWorker = function (e) {
  45042. var returnData = e.data;
  45043. if (returnData.error != WorkerReplyType.SUCCESS) {
  45044. //TODO what errors can be returned from the worker?
  45045. BABYLON.Tools.Warn("error returned from worker!");
  45046. return;
  45047. }
  45048. switch (returnData.taskType) {
  45049. case WorkerTaskType.INIT:
  45050. _this._init = true;
  45051. //Update the worked with ALL of the scene's current state
  45052. _this._scene.meshes.forEach(function (mesh) {
  45053. _this.onMeshAdded(mesh);
  45054. });
  45055. _this._scene.getGeometries().forEach(function (geometry) {
  45056. _this.onGeometryAdded(geometry);
  45057. });
  45058. break;
  45059. case WorkerTaskType.UPDATE:
  45060. _this._runningUpdated--;
  45061. break;
  45062. case WorkerTaskType.COLLIDE:
  45063. var returnPayload = returnData.payload;
  45064. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  45065. return;
  45066. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  45067. if (callback) {
  45068. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  45069. if (mesh) {
  45070. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  45071. }
  45072. }
  45073. //cleanup
  45074. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  45075. break;
  45076. }
  45077. };
  45078. this._collisionsCallbackArray = [];
  45079. this._init = false;
  45080. this._runningUpdated = 0;
  45081. this._addUpdateMeshesList = {};
  45082. this._addUpdateGeometriesList = {};
  45083. this._toRemoveGeometryArray = [];
  45084. this._toRemoveMeshesArray = [];
  45085. }
  45086. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  45087. if (!this._init)
  45088. return;
  45089. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  45090. return;
  45091. position.divideToRef(collider._radius, this._scaledPosition);
  45092. displacement.divideToRef(collider._radius, this._scaledVelocity);
  45093. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  45094. var payload = {
  45095. collider: {
  45096. position: this._scaledPosition.asArray(),
  45097. velocity: this._scaledVelocity.asArray(),
  45098. radius: collider._radius.asArray()
  45099. },
  45100. collisionId: collisionIndex,
  45101. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  45102. maximumRetry: maximumRetry
  45103. };
  45104. var message = {
  45105. payload: payload,
  45106. taskType: WorkerTaskType.COLLIDE
  45107. };
  45108. this._worker.postMessage(message);
  45109. };
  45110. CollisionCoordinatorWorker.prototype.init = function (scene) {
  45111. this._scene = scene;
  45112. this._scene.registerAfterRender(this._afterRender);
  45113. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  45114. this._worker = new Worker(workerUrl);
  45115. this._worker.onmessage = this._onMessageFromWorker;
  45116. var message = {
  45117. payload: {},
  45118. taskType: WorkerTaskType.INIT
  45119. };
  45120. this._worker.postMessage(message);
  45121. };
  45122. CollisionCoordinatorWorker.prototype.destroy = function () {
  45123. this._scene.unregisterAfterRender(this._afterRender);
  45124. this._worker.terminate();
  45125. };
  45126. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  45127. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  45128. this.onMeshUpdated(mesh);
  45129. };
  45130. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  45131. this._toRemoveMeshesArray.push(mesh.uniqueId);
  45132. };
  45133. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  45134. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  45135. geometry.onGeometryUpdated = this.onGeometryUpdated;
  45136. this.onGeometryUpdated(geometry);
  45137. };
  45138. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  45139. this._toRemoveGeometryArray.push(geometry.id);
  45140. };
  45141. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  45142. var submeshes = [];
  45143. if (mesh.subMeshes) {
  45144. submeshes = mesh.subMeshes.map(function (sm, idx) {
  45145. var boundingInfo = sm.getBoundingInfo();
  45146. return {
  45147. position: idx,
  45148. verticesStart: sm.verticesStart,
  45149. verticesCount: sm.verticesCount,
  45150. indexStart: sm.indexStart,
  45151. indexCount: sm.indexCount,
  45152. hasMaterial: !!sm.getMaterial(),
  45153. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  45154. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  45155. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  45156. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  45157. };
  45158. });
  45159. }
  45160. var geometryId = null;
  45161. if (mesh instanceof BABYLON.Mesh) {
  45162. var geometry = mesh.geometry;
  45163. geometryId = geometry ? geometry.id : null;
  45164. }
  45165. else if (mesh instanceof BABYLON.InstancedMesh) {
  45166. var geometry = mesh.sourceMesh.geometry;
  45167. geometryId = geometry ? geometry.id : null;
  45168. }
  45169. var boundingInfo = mesh.getBoundingInfo();
  45170. return {
  45171. uniqueId: mesh.uniqueId,
  45172. id: mesh.id,
  45173. name: mesh.name,
  45174. geometryId: geometryId,
  45175. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  45176. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  45177. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  45178. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  45179. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  45180. subMeshes: submeshes,
  45181. checkCollisions: mesh.checkCollisions
  45182. };
  45183. };
  45184. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  45185. return {
  45186. id: geometry.id,
  45187. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  45188. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  45189. indices: new Uint32Array(geometry.getIndices() || []),
  45190. };
  45191. };
  45192. return CollisionCoordinatorWorker;
  45193. }());
  45194. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  45195. var CollisionCoordinatorLegacy = /** @class */ (function () {
  45196. function CollisionCoordinatorLegacy() {
  45197. this._scaledPosition = BABYLON.Vector3.Zero();
  45198. this._scaledVelocity = BABYLON.Vector3.Zero();
  45199. this._finalPosition = BABYLON.Vector3.Zero();
  45200. }
  45201. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  45202. position.divideToRef(collider._radius, this._scaledPosition);
  45203. displacement.divideToRef(collider._radius, this._scaledVelocity);
  45204. collider.collidedMesh = null;
  45205. collider._retry = 0;
  45206. collider._initialVelocity = this._scaledVelocity;
  45207. collider._initialPosition = this._scaledPosition;
  45208. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  45209. this._finalPosition.multiplyInPlace(collider._radius);
  45210. //run the callback
  45211. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  45212. };
  45213. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  45214. this._scene = scene;
  45215. };
  45216. CollisionCoordinatorLegacy.prototype.destroy = function () {
  45217. //Legacy need no destruction method.
  45218. };
  45219. //No update in legacy mode
  45220. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  45221. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  45222. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  45223. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  45224. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  45225. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  45226. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  45227. if (excludedMesh === void 0) { excludedMesh = null; }
  45228. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  45229. if (collider._retry >= maximumRetry) {
  45230. finalPosition.copyFrom(position);
  45231. return;
  45232. }
  45233. // Check if this is a mesh else camera or -1
  45234. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  45235. collider._initialize(position, velocity, closeDistance);
  45236. // Check all meshes
  45237. for (var index = 0; index < this._scene.meshes.length; index++) {
  45238. var mesh = this._scene.meshes[index];
  45239. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  45240. mesh._checkCollision(collider);
  45241. }
  45242. }
  45243. if (!collider.collisionFound) {
  45244. position.addToRef(velocity, finalPosition);
  45245. return;
  45246. }
  45247. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  45248. collider._getResponse(position, velocity);
  45249. }
  45250. if (velocity.length() <= closeDistance) {
  45251. finalPosition.copyFrom(position);
  45252. return;
  45253. }
  45254. collider._retry++;
  45255. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  45256. };
  45257. return CollisionCoordinatorLegacy;
  45258. }());
  45259. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  45260. })(BABYLON || (BABYLON = {}));
  45261. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  45262. var BABYLON;
  45263. (function (BABYLON) {
  45264. var Particle = /** @class */ (function () {
  45265. function Particle(particleSystem) {
  45266. this.particleSystem = particleSystem;
  45267. this.position = BABYLON.Vector3.Zero();
  45268. this.direction = BABYLON.Vector3.Zero();
  45269. this.color = new BABYLON.Color4(0, 0, 0, 0);
  45270. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  45271. this.lifeTime = 1.0;
  45272. this.age = 0;
  45273. this.size = 0;
  45274. this.angle = 0;
  45275. this.angularSpeed = 0;
  45276. this._currentFrameCounter = 0;
  45277. this.cellIndex = 0;
  45278. if (!this.particleSystem.isAnimationSheetEnabled) {
  45279. return;
  45280. }
  45281. this.cellIndex = this.particleSystem.startSpriteCellID;
  45282. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  45283. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  45284. }
  45285. else {
  45286. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  45287. }
  45288. }
  45289. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  45290. // (ageOffset / scaledUpdateSpeed) / available cells
  45291. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  45292. this._currentFrameCounter += scaledUpdateSpeed;
  45293. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  45294. this._currentFrameCounter = 0;
  45295. this.cellIndex++;
  45296. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  45297. this.cellIndex = this.particleSystem.endSpriteCellID;
  45298. }
  45299. }
  45300. };
  45301. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  45302. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  45303. this.cellIndex++;
  45304. this._currentFrameCounter = 0;
  45305. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  45306. if (this.particleSystem.spriteCellLoop) {
  45307. this.cellIndex = this.particleSystem.startSpriteCellID;
  45308. }
  45309. else {
  45310. this.cellIndex = this.particleSystem.endSpriteCellID;
  45311. }
  45312. }
  45313. }
  45314. else {
  45315. this._currentFrameCounter++;
  45316. }
  45317. };
  45318. Particle.prototype.copyTo = function (other) {
  45319. other.position.copyFrom(this.position);
  45320. other.direction.copyFrom(this.direction);
  45321. other.color.copyFrom(this.color);
  45322. other.colorStep.copyFrom(this.colorStep);
  45323. other.lifeTime = this.lifeTime;
  45324. other.age = this.age;
  45325. other.size = this.size;
  45326. other.angle = this.angle;
  45327. other.angularSpeed = this.angularSpeed;
  45328. other.particleSystem = this.particleSystem;
  45329. other.cellIndex = this.cellIndex;
  45330. };
  45331. return Particle;
  45332. }());
  45333. BABYLON.Particle = Particle;
  45334. })(BABYLON || (BABYLON = {}));
  45335. //# sourceMappingURL=babylon.particle.js.map
  45336. var BABYLON;
  45337. (function (BABYLON) {
  45338. var randomNumber = function (min, max) {
  45339. if (min === max) {
  45340. return (min);
  45341. }
  45342. var random = Math.random();
  45343. return ((random * (max - min)) + min);
  45344. };
  45345. var ParticleSystem = /** @class */ (function () {
  45346. // end of sheet animation
  45347. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  45348. if (customEffect === void 0) { customEffect = null; }
  45349. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  45350. if (epsilon === void 0) { epsilon = 0.01; }
  45351. var _this = this;
  45352. this.name = name;
  45353. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  45354. // Members
  45355. this.animations = [];
  45356. this.renderingGroupId = 0;
  45357. this.emitter = null;
  45358. this.emitRate = 10;
  45359. this.manualEmitCount = -1;
  45360. this.updateSpeed = 0.01;
  45361. this.targetStopDuration = 0;
  45362. this.disposeOnStop = false;
  45363. this.minEmitPower = 1;
  45364. this.maxEmitPower = 1;
  45365. this.minLifeTime = 1;
  45366. this.maxLifeTime = 1;
  45367. this.minSize = 1;
  45368. this.maxSize = 1;
  45369. this.minAngularSpeed = 0;
  45370. this.maxAngularSpeed = 0;
  45371. this.layerMask = 0x0FFFFFFF;
  45372. this.customShader = null;
  45373. this.preventAutoStart = false;
  45374. /**
  45375. * An event triggered when the system is disposed.
  45376. * @type {BABYLON.Observable}
  45377. */
  45378. this.onDisposeObservable = new BABYLON.Observable();
  45379. this.onAnimationEnd = null;
  45380. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  45381. this.forceDepthWrite = false;
  45382. this.gravity = BABYLON.Vector3.Zero();
  45383. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  45384. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  45385. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  45386. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  45387. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  45388. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  45389. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  45390. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  45391. this.particles = new Array();
  45392. this._stockParticles = new Array();
  45393. this._newPartsExcess = 0;
  45394. this._vertexBuffers = {};
  45395. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  45396. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  45397. this._scaledDirection = BABYLON.Vector3.Zero();
  45398. this._scaledGravity = BABYLON.Vector3.Zero();
  45399. this._currentRenderId = -1;
  45400. this._started = false;
  45401. this._stopped = false;
  45402. this._actualFrame = 0;
  45403. // sheet animation
  45404. this.startSpriteCellID = 0;
  45405. this.endSpriteCellID = 0;
  45406. this.spriteCellLoop = true;
  45407. this.spriteCellChangeSpeed = 0;
  45408. this.spriteCellWidth = 0;
  45409. this.spriteCellHeight = 0;
  45410. this._vertexBufferSize = 11;
  45411. this.appendParticleVertexes = null;
  45412. this.id = name;
  45413. this._capacity = capacity;
  45414. this._epsilon = epsilon;
  45415. if (_isAnimationSheetEnabled) {
  45416. this._vertexBufferSize = 12;
  45417. }
  45418. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  45419. this._customEffect = customEffect;
  45420. scene.particleSystems.push(this);
  45421. this._createIndexBuffer();
  45422. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  45423. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  45424. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  45425. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  45426. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  45427. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  45428. if (this._isAnimationSheetEnabled) {
  45429. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  45430. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  45431. }
  45432. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  45433. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  45434. this._vertexBuffers["options"] = options;
  45435. // Default behaviors
  45436. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  45437. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  45438. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  45439. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  45440. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  45441. };
  45442. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  45443. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  45444. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  45445. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  45446. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  45447. };
  45448. this.updateFunction = function (particles) {
  45449. for (var index = 0; index < particles.length; index++) {
  45450. var particle = particles[index];
  45451. particle.age += _this._scaledUpdateSpeed;
  45452. if (particle.age >= particle.lifeTime) {
  45453. _this.recycleParticle(particle);
  45454. index--;
  45455. continue;
  45456. }
  45457. else {
  45458. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  45459. particle.color.addInPlace(_this._scaledColorStep);
  45460. if (particle.color.a < 0)
  45461. particle.color.a = 0;
  45462. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  45463. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  45464. particle.position.addInPlace(_this._scaledDirection);
  45465. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  45466. particle.direction.addInPlace(_this._scaledGravity);
  45467. if (_this._isAnimationSheetEnabled) {
  45468. particle.updateCellIndex(_this._scaledUpdateSpeed);
  45469. }
  45470. }
  45471. }
  45472. };
  45473. }
  45474. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  45475. set: function (callback) {
  45476. if (this._onDisposeObserver) {
  45477. this.onDisposeObservable.remove(this._onDisposeObserver);
  45478. }
  45479. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  45480. },
  45481. enumerable: true,
  45482. configurable: true
  45483. });
  45484. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  45485. get: function () {
  45486. return this._isAnimationSheetEnabled;
  45487. },
  45488. enumerable: true,
  45489. configurable: true
  45490. });
  45491. ParticleSystem.prototype._createIndexBuffer = function () {
  45492. var indices = [];
  45493. var index = 0;
  45494. for (var count = 0; count < this._capacity; count++) {
  45495. indices.push(index);
  45496. indices.push(index + 1);
  45497. indices.push(index + 2);
  45498. indices.push(index);
  45499. indices.push(index + 2);
  45500. indices.push(index + 3);
  45501. index += 4;
  45502. }
  45503. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  45504. };
  45505. ParticleSystem.prototype.recycleParticle = function (particle) {
  45506. var lastParticle = this.particles.pop();
  45507. if (lastParticle !== particle) {
  45508. lastParticle.copyTo(particle);
  45509. this._stockParticles.push(lastParticle);
  45510. }
  45511. };
  45512. ParticleSystem.prototype.getCapacity = function () {
  45513. return this._capacity;
  45514. };
  45515. ParticleSystem.prototype.isAlive = function () {
  45516. return this._alive;
  45517. };
  45518. ParticleSystem.prototype.isStarted = function () {
  45519. return this._started;
  45520. };
  45521. ParticleSystem.prototype.start = function () {
  45522. this._started = true;
  45523. this._stopped = false;
  45524. this._actualFrame = 0;
  45525. };
  45526. ParticleSystem.prototype.stop = function () {
  45527. this._stopped = true;
  45528. };
  45529. // animation sheet
  45530. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  45531. var offset = index * this._vertexBufferSize;
  45532. this._vertexData[offset] = particle.position.x;
  45533. this._vertexData[offset + 1] = particle.position.y;
  45534. this._vertexData[offset + 2] = particle.position.z;
  45535. this._vertexData[offset + 3] = particle.color.r;
  45536. this._vertexData[offset + 4] = particle.color.g;
  45537. this._vertexData[offset + 5] = particle.color.b;
  45538. this._vertexData[offset + 6] = particle.color.a;
  45539. this._vertexData[offset + 7] = particle.angle;
  45540. this._vertexData[offset + 8] = particle.size;
  45541. this._vertexData[offset + 9] = offsetX;
  45542. this._vertexData[offset + 10] = offsetY;
  45543. };
  45544. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  45545. if (offsetX === 0)
  45546. offsetX = this._epsilon;
  45547. else if (offsetX === 1)
  45548. offsetX = 1 - this._epsilon;
  45549. if (offsetY === 0)
  45550. offsetY = this._epsilon;
  45551. else if (offsetY === 1)
  45552. offsetY = 1 - this._epsilon;
  45553. var offset = index * this._vertexBufferSize;
  45554. this._vertexData[offset] = particle.position.x;
  45555. this._vertexData[offset + 1] = particle.position.y;
  45556. this._vertexData[offset + 2] = particle.position.z;
  45557. this._vertexData[offset + 3] = particle.color.r;
  45558. this._vertexData[offset + 4] = particle.color.g;
  45559. this._vertexData[offset + 5] = particle.color.b;
  45560. this._vertexData[offset + 6] = particle.color.a;
  45561. this._vertexData[offset + 7] = particle.angle;
  45562. this._vertexData[offset + 8] = particle.size;
  45563. this._vertexData[offset + 9] = offsetX;
  45564. this._vertexData[offset + 10] = offsetY;
  45565. this._vertexData[offset + 11] = particle.cellIndex;
  45566. };
  45567. ParticleSystem.prototype._update = function (newParticles) {
  45568. // Update current
  45569. this._alive = this.particles.length > 0;
  45570. this.updateFunction(this.particles);
  45571. // Add new ones
  45572. var worldMatrix;
  45573. if (this.emitter.position) {
  45574. var emitterMesh = this.emitter;
  45575. worldMatrix = emitterMesh.getWorldMatrix();
  45576. }
  45577. else {
  45578. var emitterPosition = this.emitter;
  45579. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  45580. }
  45581. var particle;
  45582. for (var index = 0; index < newParticles; index++) {
  45583. if (this.particles.length === this._capacity) {
  45584. break;
  45585. }
  45586. if (this._stockParticles.length !== 0) {
  45587. particle = this._stockParticles.pop();
  45588. particle.age = 0;
  45589. particle.cellIndex = this.startSpriteCellID;
  45590. }
  45591. else {
  45592. particle = new BABYLON.Particle(this);
  45593. }
  45594. this.particles.push(particle);
  45595. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  45596. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  45597. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  45598. particle.size = randomNumber(this.minSize, this.maxSize);
  45599. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  45600. this.startPositionFunction(worldMatrix, particle.position, particle);
  45601. var step = randomNumber(0, 1.0);
  45602. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  45603. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  45604. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  45605. }
  45606. };
  45607. ParticleSystem.prototype._getEffect = function () {
  45608. if (this._customEffect) {
  45609. return this._customEffect;
  45610. }
  45611. ;
  45612. var defines = [];
  45613. if (this._scene.clipPlane) {
  45614. defines.push("#define CLIPPLANE");
  45615. }
  45616. if (this._isAnimationSheetEnabled) {
  45617. defines.push("#define ANIMATESHEET");
  45618. }
  45619. // Effect
  45620. var join = defines.join("\n");
  45621. if (this._cachedDefines !== join) {
  45622. this._cachedDefines = join;
  45623. var attributesNamesOrOptions;
  45624. var effectCreationOption;
  45625. if (this._isAnimationSheetEnabled) {
  45626. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  45627. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  45628. }
  45629. else {
  45630. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  45631. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  45632. }
  45633. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  45634. }
  45635. return this._effect;
  45636. };
  45637. ParticleSystem.prototype.animate = function () {
  45638. if (!this._started)
  45639. return;
  45640. var effect = this._getEffect();
  45641. // Check
  45642. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  45643. return;
  45644. if (this._currentRenderId === this._scene.getRenderId()) {
  45645. return;
  45646. }
  45647. this._currentRenderId = this._scene.getRenderId();
  45648. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  45649. // determine the number of particles we need to create
  45650. var newParticles;
  45651. if (this.manualEmitCount > -1) {
  45652. newParticles = this.manualEmitCount;
  45653. this._newPartsExcess = 0;
  45654. this.manualEmitCount = 0;
  45655. }
  45656. else {
  45657. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  45658. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  45659. }
  45660. if (this._newPartsExcess > 1.0) {
  45661. newParticles += this._newPartsExcess >> 0;
  45662. this._newPartsExcess -= this._newPartsExcess >> 0;
  45663. }
  45664. this._alive = false;
  45665. if (!this._stopped) {
  45666. this._actualFrame += this._scaledUpdateSpeed;
  45667. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  45668. this.stop();
  45669. }
  45670. else {
  45671. newParticles = 0;
  45672. }
  45673. this._update(newParticles);
  45674. // Stopped?
  45675. if (this._stopped) {
  45676. if (!this._alive) {
  45677. this._started = false;
  45678. if (this.onAnimationEnd) {
  45679. this.onAnimationEnd();
  45680. }
  45681. if (this.disposeOnStop) {
  45682. this._scene._toBeDisposed.push(this);
  45683. }
  45684. }
  45685. }
  45686. // Animation sheet
  45687. if (this._isAnimationSheetEnabled) {
  45688. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  45689. }
  45690. else {
  45691. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  45692. }
  45693. // Update VBO
  45694. var offset = 0;
  45695. for (var index = 0; index < this.particles.length; index++) {
  45696. var particle = this.particles[index];
  45697. this.appendParticleVertexes(offset, particle);
  45698. offset += 4;
  45699. }
  45700. if (this._vertexBuffer) {
  45701. this._vertexBuffer.update(this._vertexData);
  45702. }
  45703. };
  45704. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  45705. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  45706. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  45707. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  45708. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  45709. };
  45710. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  45711. this._appendParticleVertex(offset++, particle, 0, 0);
  45712. this._appendParticleVertex(offset++, particle, 1, 0);
  45713. this._appendParticleVertex(offset++, particle, 1, 1);
  45714. this._appendParticleVertex(offset++, particle, 0, 1);
  45715. };
  45716. ParticleSystem.prototype.rebuild = function () {
  45717. this._createIndexBuffer();
  45718. if (this._vertexBuffer) {
  45719. this._vertexBuffer._rebuild();
  45720. }
  45721. };
  45722. ParticleSystem.prototype.render = function () {
  45723. var effect = this._getEffect();
  45724. // Check
  45725. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  45726. return 0;
  45727. var engine = this._scene.getEngine();
  45728. // Render
  45729. engine.enableEffect(effect);
  45730. engine.setState(false);
  45731. var viewMatrix = this._scene.getViewMatrix();
  45732. effect.setTexture("diffuseSampler", this.particleTexture);
  45733. effect.setMatrix("view", viewMatrix);
  45734. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  45735. if (this._isAnimationSheetEnabled) {
  45736. var baseSize = this.particleTexture.getBaseSize();
  45737. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  45738. }
  45739. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  45740. if (this._scene.clipPlane) {
  45741. var clipPlane = this._scene.clipPlane;
  45742. var invView = viewMatrix.clone();
  45743. invView.invert();
  45744. effect.setMatrix("invView", invView);
  45745. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  45746. }
  45747. // VBOs
  45748. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  45749. // Draw order
  45750. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  45751. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  45752. }
  45753. else {
  45754. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  45755. }
  45756. if (this.forceDepthWrite) {
  45757. engine.setDepthWrite(true);
  45758. }
  45759. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this.particles.length * 6);
  45760. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  45761. return this.particles.length;
  45762. };
  45763. ParticleSystem.prototype.dispose = function () {
  45764. if (this._vertexBuffer) {
  45765. this._vertexBuffer.dispose();
  45766. this._vertexBuffer = null;
  45767. }
  45768. if (this._indexBuffer) {
  45769. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  45770. this._indexBuffer = null;
  45771. }
  45772. if (this.particleTexture) {
  45773. this.particleTexture.dispose();
  45774. this.particleTexture = null;
  45775. }
  45776. // Remove from scene
  45777. var index = this._scene.particleSystems.indexOf(this);
  45778. if (index > -1) {
  45779. this._scene.particleSystems.splice(index, 1);
  45780. }
  45781. // Callback
  45782. this.onDisposeObservable.notifyObservers(this);
  45783. this.onDisposeObservable.clear();
  45784. };
  45785. // Clone
  45786. ParticleSystem.prototype.clone = function (name, newEmitter) {
  45787. var custom = null;
  45788. var program = null;
  45789. if (this.customShader != null) {
  45790. program = this.customShader;
  45791. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  45792. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  45793. }
  45794. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  45795. result.customShader = program;
  45796. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  45797. if (newEmitter === undefined) {
  45798. newEmitter = this.emitter;
  45799. }
  45800. result.emitter = newEmitter;
  45801. if (this.particleTexture) {
  45802. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  45803. }
  45804. if (!this.preventAutoStart) {
  45805. result.start();
  45806. }
  45807. return result;
  45808. };
  45809. ParticleSystem.prototype.serialize = function () {
  45810. var serializationObject = {};
  45811. serializationObject.name = this.name;
  45812. serializationObject.id = this.id;
  45813. // Emitter
  45814. if (this.emitter.position) {
  45815. var emitterMesh = this.emitter;
  45816. serializationObject.emitterId = emitterMesh.id;
  45817. }
  45818. else {
  45819. var emitterPosition = this.emitter;
  45820. serializationObject.emitter = emitterPosition.asArray();
  45821. }
  45822. serializationObject.capacity = this.getCapacity();
  45823. if (this.particleTexture) {
  45824. serializationObject.textureName = this.particleTexture.name;
  45825. }
  45826. // Animations
  45827. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  45828. // Particle system
  45829. serializationObject.minAngularSpeed = this.minAngularSpeed;
  45830. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  45831. serializationObject.minSize = this.minSize;
  45832. serializationObject.maxSize = this.maxSize;
  45833. serializationObject.minEmitPower = this.minEmitPower;
  45834. serializationObject.maxEmitPower = this.maxEmitPower;
  45835. serializationObject.minLifeTime = this.minLifeTime;
  45836. serializationObject.maxLifeTime = this.maxLifeTime;
  45837. serializationObject.emitRate = this.emitRate;
  45838. serializationObject.minEmitBox = this.minEmitBox.asArray();
  45839. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  45840. serializationObject.gravity = this.gravity.asArray();
  45841. serializationObject.direction1 = this.direction1.asArray();
  45842. serializationObject.direction2 = this.direction2.asArray();
  45843. serializationObject.color1 = this.color1.asArray();
  45844. serializationObject.color2 = this.color2.asArray();
  45845. serializationObject.colorDead = this.colorDead.asArray();
  45846. serializationObject.updateSpeed = this.updateSpeed;
  45847. serializationObject.targetStopDuration = this.targetStopDuration;
  45848. serializationObject.textureMask = this.textureMask.asArray();
  45849. serializationObject.blendMode = this.blendMode;
  45850. serializationObject.customShader = this.customShader;
  45851. serializationObject.preventAutoStart = this.preventAutoStart;
  45852. serializationObject.startSpriteCellID = this.startSpriteCellID;
  45853. serializationObject.endSpriteCellID = this.endSpriteCellID;
  45854. serializationObject.spriteCellLoop = this.spriteCellLoop;
  45855. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  45856. serializationObject.spriteCellWidth = this.spriteCellWidth;
  45857. serializationObject.spriteCellHeight = this.spriteCellHeight;
  45858. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  45859. return serializationObject;
  45860. };
  45861. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  45862. var name = parsedParticleSystem.name;
  45863. var custom = null;
  45864. var program = null;
  45865. if (parsedParticleSystem.customShader) {
  45866. program = parsedParticleSystem.customShader;
  45867. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  45868. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  45869. }
  45870. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  45871. particleSystem.customShader = program;
  45872. if (parsedParticleSystem.id) {
  45873. particleSystem.id = parsedParticleSystem.id;
  45874. }
  45875. // Auto start
  45876. if (parsedParticleSystem.preventAutoStart) {
  45877. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  45878. }
  45879. // Texture
  45880. if (parsedParticleSystem.textureName) {
  45881. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  45882. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  45883. }
  45884. // Emitter
  45885. if (parsedParticleSystem.emitterId) {
  45886. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  45887. }
  45888. else {
  45889. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  45890. }
  45891. // Animations
  45892. if (parsedParticleSystem.animations) {
  45893. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  45894. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  45895. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  45896. }
  45897. }
  45898. if (parsedParticleSystem.autoAnimate) {
  45899. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  45900. }
  45901. // Particle system
  45902. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  45903. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  45904. particleSystem.minSize = parsedParticleSystem.minSize;
  45905. particleSystem.maxSize = parsedParticleSystem.maxSize;
  45906. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  45907. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  45908. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  45909. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  45910. particleSystem.emitRate = parsedParticleSystem.emitRate;
  45911. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  45912. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  45913. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  45914. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  45915. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  45916. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  45917. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  45918. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  45919. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  45920. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  45921. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  45922. particleSystem.blendMode = parsedParticleSystem.blendMode;
  45923. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  45924. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  45925. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  45926. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  45927. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  45928. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  45929. if (!particleSystem.preventAutoStart) {
  45930. particleSystem.start();
  45931. }
  45932. return particleSystem;
  45933. };
  45934. // Statics
  45935. ParticleSystem.BLENDMODE_ONEONE = 0;
  45936. ParticleSystem.BLENDMODE_STANDARD = 1;
  45937. return ParticleSystem;
  45938. }());
  45939. BABYLON.ParticleSystem = ParticleSystem;
  45940. })(BABYLON || (BABYLON = {}));
  45941. //# sourceMappingURL=babylon.particleSystem.js.map
  45942. var BABYLON;
  45943. (function (BABYLON) {
  45944. var SolidParticle = /** @class */ (function () {
  45945. /**
  45946. * Creates a Solid Particle object.
  45947. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  45948. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  45949. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  45950. * `indiceIndex` (integer) is the starting index of the particle indices in the SPS "indices" array.
  45951. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  45952. * `shapeId` (integer) is the model shape identifier in the SPS.
  45953. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  45954. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  45955. */
  45956. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  45957. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  45958. this.idx = 0; // particle global index
  45959. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  45960. this.position = BABYLON.Vector3.Zero(); // position
  45961. this.rotation = BABYLON.Vector3.Zero(); // rotation
  45962. this.scaling = BABYLON.Vector3.One(); // scaling
  45963. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  45964. this.velocity = BABYLON.Vector3.Zero(); // velocity
  45965. this.pivot = BABYLON.Vector3.Zero(); // pivot point in the particle local space
  45966. this.alive = true; // alive
  45967. this.isVisible = true; // visibility
  45968. this._pos = 0; // index of this particle in the global "positions" array
  45969. this._ind = 0; // index of this particle in the global "indices" array
  45970. this.shapeId = 0; // model shape id
  45971. this.idxInShape = 0; // index of the particle in its shape id
  45972. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  45973. this.idx = particleIndex;
  45974. this._pos = positionIndex;
  45975. this._ind = indiceIndex;
  45976. this._model = model;
  45977. this.shapeId = shapeId;
  45978. this.idxInShape = idxInShape;
  45979. this._sps = sps;
  45980. if (modelBoundingInfo) {
  45981. this._modelBoundingInfo = modelBoundingInfo;
  45982. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  45983. }
  45984. }
  45985. Object.defineProperty(SolidParticle.prototype, "scale", {
  45986. /**
  45987. * legacy support, changed scale to scaling
  45988. */
  45989. get: function () {
  45990. return this.scaling;
  45991. },
  45992. set: function (scale) {
  45993. this.scaling = scale;
  45994. },
  45995. enumerable: true,
  45996. configurable: true
  45997. });
  45998. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  45999. /**
  46000. * legacy support, changed quaternion to rotationQuaternion
  46001. */
  46002. get: function () {
  46003. return this.rotationQuaternion;
  46004. },
  46005. set: function (q) {
  46006. this.rotationQuaternion = q;
  46007. },
  46008. enumerable: true,
  46009. configurable: true
  46010. });
  46011. /**
  46012. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  46013. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  46014. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  46015. */
  46016. SolidParticle.prototype.intersectsMesh = function (target) {
  46017. if (!this._boundingInfo || !target._boundingInfo) {
  46018. return false;
  46019. }
  46020. if (this._sps._bSphereOnly) {
  46021. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  46022. }
  46023. return this._boundingInfo.intersects(target._boundingInfo, false);
  46024. };
  46025. return SolidParticle;
  46026. }());
  46027. BABYLON.SolidParticle = SolidParticle;
  46028. var ModelShape = /** @class */ (function () {
  46029. /**
  46030. * 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.
  46031. * SPS internal tool, don't use it manually.
  46032. */
  46033. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  46034. this._indicesLength = 0; // length of the shape in the model indices array
  46035. this.shapeID = id;
  46036. this._shape = shape;
  46037. this._indicesLength = indicesLength;
  46038. this._shapeUV = shapeUV;
  46039. this._positionFunction = posFunction;
  46040. this._vertexFunction = vtxFunction;
  46041. }
  46042. return ModelShape;
  46043. }());
  46044. BABYLON.ModelShape = ModelShape;
  46045. var DepthSortedParticle = /** @class */ (function () {
  46046. function DepthSortedParticle() {
  46047. this.ind = 0; // index of the particle in the "indices" array
  46048. this.indicesLength = 0; // length of the particle shape in the "indices" array
  46049. this.sqDistance = 0.0; // squared distance from the particle to the camera
  46050. }
  46051. return DepthSortedParticle;
  46052. }());
  46053. BABYLON.DepthSortedParticle = DepthSortedParticle;
  46054. })(BABYLON || (BABYLON = {}));
  46055. //# sourceMappingURL=babylon.solidParticle.js.map
  46056. var BABYLON;
  46057. (function (BABYLON) {
  46058. /**
  46059. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  46060. */
  46061. var SolidParticleSystem = /** @class */ (function () {
  46062. /**
  46063. * Creates a SPS (Solid Particle System) object.
  46064. * `name` (String) is the SPS name, this will be the underlying mesh name.
  46065. * `scene` (Scene) is the scene in which the SPS is added.
  46066. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  46067. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  46068. * `enableDepthSort` (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  46069. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  46070. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  46071. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  46072. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  46073. */
  46074. function SolidParticleSystem(name, scene, options) {
  46075. // public members
  46076. /**
  46077. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  46078. * Example : var p = SPS.particles[i];
  46079. */
  46080. this.particles = new Array();
  46081. /**
  46082. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  46083. */
  46084. this.nbParticles = 0;
  46085. /**
  46086. * If the particles must ever face the camera (default false). Useful for planar particles.
  46087. */
  46088. this.billboard = false;
  46089. /**
  46090. * Recompute normals when adding a shape
  46091. */
  46092. this.recomputeNormals = true;
  46093. /**
  46094. * This a counter ofr your own usage. It's not set by any SPS functions.
  46095. */
  46096. this.counter = 0;
  46097. /**
  46098. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  46099. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  46100. */
  46101. this.vars = {};
  46102. this._positions = new Array();
  46103. this._indices = new Array();
  46104. this._normals = new Array();
  46105. this._colors = new Array();
  46106. this._uvs = new Array();
  46107. this._index = 0; // indices index
  46108. this._updatable = true;
  46109. this._pickable = false;
  46110. this._isVisibilityBoxLocked = false;
  46111. this._alwaysVisible = false;
  46112. this._depthSort = false;
  46113. this._shapeCounter = 0;
  46114. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  46115. this._color = new BABYLON.Color4(0, 0, 0, 0);
  46116. this._computeParticleColor = true;
  46117. this._computeParticleTexture = true;
  46118. this._computeParticleRotation = true;
  46119. this._computeParticleVertex = false;
  46120. this._computeBoundingBox = false;
  46121. this._depthSortParticles = true;
  46122. this._cam_axisZ = BABYLON.Vector3.Zero();
  46123. this._cam_axisY = BABYLON.Vector3.Zero();
  46124. this._cam_axisX = BABYLON.Vector3.Zero();
  46125. this._axisZ = BABYLON.Axis.Z;
  46126. this._camDir = BABYLON.Vector3.Zero();
  46127. this._camInvertedPosition = BABYLON.Vector3.Zero();
  46128. this._rotMatrix = new BABYLON.Matrix();
  46129. this._invertMatrix = new BABYLON.Matrix();
  46130. this._rotated = BABYLON.Vector3.Zero();
  46131. this._quaternion = new BABYLON.Quaternion();
  46132. this._vertex = BABYLON.Vector3.Zero();
  46133. this._normal = BABYLON.Vector3.Zero();
  46134. this._yaw = 0.0;
  46135. this._pitch = 0.0;
  46136. this._roll = 0.0;
  46137. this._halfroll = 0.0;
  46138. this._halfpitch = 0.0;
  46139. this._halfyaw = 0.0;
  46140. this._sinRoll = 0.0;
  46141. this._cosRoll = 0.0;
  46142. this._sinPitch = 0.0;
  46143. this._cosPitch = 0.0;
  46144. this._sinYaw = 0.0;
  46145. this._cosYaw = 0.0;
  46146. this._mustUnrotateFixedNormals = false;
  46147. this._minimum = BABYLON.Tmp.Vector3[0];
  46148. this._maximum = BABYLON.Tmp.Vector3[1];
  46149. this._minBbox = BABYLON.Tmp.Vector3[4];
  46150. this._maxBbox = BABYLON.Tmp.Vector3[5];
  46151. this._particlesIntersect = false;
  46152. this._depthSortFunction = function (p1, p2) {
  46153. return (p2.sqDistance - p1.sqDistance);
  46154. };
  46155. this._needs32Bits = false;
  46156. this._bSphereOnly = false;
  46157. this._bSphereRadiusFactor = 1.0;
  46158. this.name = name;
  46159. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46160. this._camera = scene.activeCamera;
  46161. this._pickable = options ? options.isPickable : false;
  46162. this._depthSort = options ? options.enableDepthSort : false;
  46163. this._particlesIntersect = options ? options.particleIntersection : false;
  46164. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  46165. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  46166. if (options && options.updatable) {
  46167. this._updatable = options.updatable;
  46168. }
  46169. else {
  46170. this._updatable = true;
  46171. }
  46172. if (this._pickable) {
  46173. this.pickedParticles = [];
  46174. }
  46175. if (this._depthSort) {
  46176. this.depthSortedParticles = [];
  46177. }
  46178. }
  46179. /**
  46180. * Builds the SPS underlying mesh. Returns a standard Mesh.
  46181. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  46182. */
  46183. SolidParticleSystem.prototype.buildMesh = function () {
  46184. if (this.nbParticles === 0) {
  46185. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  46186. this.addShape(triangle, 1);
  46187. triangle.dispose();
  46188. }
  46189. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  46190. this._positions32 = new Float32Array(this._positions);
  46191. this._uvs32 = new Float32Array(this._uvs);
  46192. this._colors32 = new Float32Array(this._colors);
  46193. if (this.recomputeNormals) {
  46194. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  46195. }
  46196. this._normals32 = new Float32Array(this._normals);
  46197. this._fixedNormal32 = new Float32Array(this._normals);
  46198. if (this._mustUnrotateFixedNormals) {
  46199. this._unrotateFixedNormals();
  46200. }
  46201. var vertexData = new BABYLON.VertexData();
  46202. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  46203. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  46204. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  46205. if (this._uvs32) {
  46206. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  46207. ;
  46208. }
  46209. if (this._colors32) {
  46210. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  46211. }
  46212. var mesh = new BABYLON.Mesh(this.name, this._scene);
  46213. vertexData.applyToMesh(mesh, this._updatable);
  46214. this.mesh = mesh;
  46215. this.mesh.isPickable = this._pickable;
  46216. // free memory
  46217. if (!this._depthSort) {
  46218. this._indices = null;
  46219. }
  46220. this._positions = null;
  46221. this._normals = null;
  46222. this._uvs = null;
  46223. this._colors = null;
  46224. if (!this._updatable) {
  46225. this.particles.length = 0;
  46226. }
  46227. return mesh;
  46228. };
  46229. /**
  46230. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  46231. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  46232. * Thus the particles generated from `digest()` have their property `position` set yet.
  46233. * `mesh` ( Mesh ) is the mesh to be digested
  46234. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  46235. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  46236. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  46237. */
  46238. SolidParticleSystem.prototype.digest = function (mesh, options) {
  46239. var size = (options && options.facetNb) || 1;
  46240. var number = (options && options.number) || 0;
  46241. var delta = (options && options.delta) || 0;
  46242. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46243. var meshInd = mesh.getIndices();
  46244. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  46245. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  46246. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  46247. var f = 0; // facet counter
  46248. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  46249. // compute size from number
  46250. if (number) {
  46251. number = (number > totalFacets) ? totalFacets : number;
  46252. size = Math.round(totalFacets / number);
  46253. delta = 0;
  46254. }
  46255. else {
  46256. size = (size > totalFacets) ? totalFacets : size;
  46257. }
  46258. var facetPos = []; // submesh positions
  46259. var facetInd = []; // submesh indices
  46260. var facetUV = []; // submesh UV
  46261. var facetCol = []; // submesh colors
  46262. var barycenter = BABYLON.Tmp.Vector3[0];
  46263. var sizeO = size;
  46264. while (f < totalFacets) {
  46265. size = sizeO + Math.floor((1 + delta) * Math.random());
  46266. if (f > totalFacets - size) {
  46267. size = totalFacets - f;
  46268. }
  46269. // reset temp arrays
  46270. facetPos.length = 0;
  46271. facetInd.length = 0;
  46272. facetUV.length = 0;
  46273. facetCol.length = 0;
  46274. // iterate over "size" facets
  46275. var fi = 0;
  46276. for (var j = f * 3; j < (f + size) * 3; j++) {
  46277. facetInd.push(fi);
  46278. var i = meshInd[j];
  46279. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  46280. if (meshUV) {
  46281. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  46282. }
  46283. if (meshCol) {
  46284. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  46285. }
  46286. fi++;
  46287. }
  46288. // create a model shape for each single particle
  46289. var idx = this.nbParticles;
  46290. var shape = this._posToShape(facetPos);
  46291. var shapeUV = this._uvsToShapeUV(facetUV);
  46292. // compute the barycenter of the shape
  46293. var v;
  46294. for (v = 0; v < shape.length; v++) {
  46295. barycenter.addInPlace(shape[v]);
  46296. }
  46297. barycenter.scaleInPlace(1 / shape.length);
  46298. // shift the shape from its barycenter to the origin
  46299. for (v = 0; v < shape.length; v++) {
  46300. shape[v].subtractInPlace(barycenter);
  46301. }
  46302. var bInfo;
  46303. if (this._particlesIntersect) {
  46304. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  46305. }
  46306. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  46307. // add the particle in the SPS
  46308. var currentPos = this._positions.length;
  46309. var currentInd = this._indices.length;
  46310. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  46311. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  46312. // initialize the particle position
  46313. this.particles[this.nbParticles].position.addInPlace(barycenter);
  46314. this._index += shape.length;
  46315. idx++;
  46316. this.nbParticles++;
  46317. this._shapeCounter++;
  46318. f += size;
  46319. }
  46320. return this;
  46321. };
  46322. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  46323. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  46324. var index = 0;
  46325. var idx = 0;
  46326. for (var p = 0; p < this.particles.length; p++) {
  46327. this._particle = this.particles[p];
  46328. this._shape = this._particle._model._shape;
  46329. if (this._particle.rotationQuaternion) {
  46330. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  46331. }
  46332. else {
  46333. this._yaw = this._particle.rotation.y;
  46334. this._pitch = this._particle.rotation.x;
  46335. this._roll = this._particle.rotation.z;
  46336. this._quaternionRotationYPR();
  46337. }
  46338. this._quaternionToRotationMatrix();
  46339. this._rotMatrix.invertToRef(this._invertMatrix);
  46340. for (var pt = 0; pt < this._shape.length; pt++) {
  46341. idx = index + pt * 3;
  46342. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  46343. this._fixedNormal32[idx] = this._normal.x;
  46344. this._fixedNormal32[idx + 1] = this._normal.y;
  46345. this._fixedNormal32[idx + 2] = this._normal.z;
  46346. }
  46347. index = idx + 3;
  46348. }
  46349. };
  46350. //reset copy
  46351. SolidParticleSystem.prototype._resetCopy = function () {
  46352. this._copy.position.x = 0;
  46353. this._copy.position.y = 0;
  46354. this._copy.position.z = 0;
  46355. this._copy.rotation.x = 0;
  46356. this._copy.rotation.y = 0;
  46357. this._copy.rotation.z = 0;
  46358. this._copy.rotationQuaternion = null;
  46359. this._copy.scaling.x = 1.0;
  46360. this._copy.scaling.y = 1.0;
  46361. this._copy.scaling.z = 1.0;
  46362. this._copy.uvs.x = 0;
  46363. this._copy.uvs.y = 0;
  46364. this._copy.uvs.z = 1.0;
  46365. this._copy.uvs.w = 1.0;
  46366. this._copy.color = null;
  46367. };
  46368. // _meshBuilder : inserts the shape model in the global SPS mesh
  46369. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  46370. var i;
  46371. var u = 0;
  46372. var c = 0;
  46373. var n = 0;
  46374. this._resetCopy();
  46375. if (options && options.positionFunction) {
  46376. options.positionFunction(this._copy, idx, idxInShape);
  46377. this._mustUnrotateFixedNormals = true;
  46378. }
  46379. if (this._copy.rotationQuaternion) {
  46380. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  46381. }
  46382. else {
  46383. this._yaw = this._copy.rotation.y;
  46384. this._pitch = this._copy.rotation.x;
  46385. this._roll = this._copy.rotation.z;
  46386. this._quaternionRotationYPR();
  46387. }
  46388. this._quaternionToRotationMatrix();
  46389. for (i = 0; i < shape.length; i++) {
  46390. this._vertex.x = shape[i].x;
  46391. this._vertex.y = shape[i].y;
  46392. this._vertex.z = shape[i].z;
  46393. if (options && options.vertexFunction) {
  46394. options.vertexFunction(this._copy, this._vertex, i);
  46395. }
  46396. this._vertex.x *= this._copy.scaling.x;
  46397. this._vertex.y *= this._copy.scaling.y;
  46398. this._vertex.z *= this._copy.scaling.z;
  46399. this._vertex.x += this._copy.pivot.x;
  46400. this._vertex.y += this._copy.pivot.y;
  46401. this._vertex.z += this._copy.pivot.z;
  46402. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  46403. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  46404. if (meshUV) {
  46405. 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);
  46406. u += 2;
  46407. }
  46408. if (this._copy.color) {
  46409. this._color = this._copy.color;
  46410. }
  46411. else if (meshCol && meshCol[c] !== undefined) {
  46412. this._color.r = meshCol[c];
  46413. this._color.g = meshCol[c + 1];
  46414. this._color.b = meshCol[c + 2];
  46415. this._color.a = meshCol[c + 3];
  46416. }
  46417. else {
  46418. this._color.r = 1.0;
  46419. this._color.g = 1.0;
  46420. this._color.b = 1.0;
  46421. this._color.a = 1.0;
  46422. }
  46423. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  46424. c += 4;
  46425. if (!this.recomputeNormals && meshNor) {
  46426. this._normal.x = meshNor[n];
  46427. this._normal.y = meshNor[n + 1];
  46428. this._normal.z = meshNor[n + 2];
  46429. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  46430. normals.push(this._normal.x, this._normal.y, this._normal.z);
  46431. n += 3;
  46432. }
  46433. }
  46434. for (i = 0; i < meshInd.length; i++) {
  46435. var current_ind = p + meshInd[i];
  46436. indices.push(current_ind);
  46437. if (current_ind > 65535) {
  46438. this._needs32Bits = true;
  46439. }
  46440. }
  46441. if (this._pickable) {
  46442. var nbfaces = meshInd.length / 3;
  46443. for (i = 0; i < nbfaces; i++) {
  46444. this.pickedParticles.push({ idx: idx, faceId: i });
  46445. }
  46446. }
  46447. if (this._depthSort) {
  46448. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  46449. }
  46450. return this._copy;
  46451. };
  46452. // returns a shape array from positions array
  46453. SolidParticleSystem.prototype._posToShape = function (positions) {
  46454. var shape = [];
  46455. for (var i = 0; i < positions.length; i += 3) {
  46456. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  46457. }
  46458. return shape;
  46459. };
  46460. // returns a shapeUV array from a Vector4 uvs
  46461. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  46462. var shapeUV = [];
  46463. if (uvs) {
  46464. for (var i = 0; i < uvs.length; i++)
  46465. shapeUV.push(uvs[i]);
  46466. }
  46467. return shapeUV;
  46468. };
  46469. // adds a new particle object in the particles array
  46470. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  46471. if (bInfo === void 0) { bInfo = null; }
  46472. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  46473. this.particles.push(sp);
  46474. return sp;
  46475. };
  46476. /**
  46477. * Adds some particles to the SPS from the model shape. Returns the shape id.
  46478. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  46479. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  46480. * `nb` (positive integer) the number of particles to be created from this model
  46481. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  46482. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  46483. */
  46484. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  46485. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46486. var meshInd = mesh.getIndices();
  46487. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  46488. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  46489. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  46490. var bbInfo;
  46491. if (this._particlesIntersect) {
  46492. bbInfo = mesh.getBoundingInfo();
  46493. }
  46494. var shape = this._posToShape(meshPos);
  46495. var shapeUV = this._uvsToShapeUV(meshUV);
  46496. var posfunc = options ? options.positionFunction : null;
  46497. var vtxfunc = options ? options.vertexFunction : null;
  46498. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  46499. // particles
  46500. var sp;
  46501. var currentCopy;
  46502. var idx = this.nbParticles;
  46503. for (var i = 0; i < nb; i++) {
  46504. var currentPos = this._positions.length;
  46505. var currentInd = this._indices.length;
  46506. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  46507. if (this._updatable) {
  46508. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  46509. sp.position.copyFrom(currentCopy.position);
  46510. sp.rotation.copyFrom(currentCopy.rotation);
  46511. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  46512. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  46513. }
  46514. if (currentCopy.color && sp.color) {
  46515. sp.color.copyFrom(currentCopy.color);
  46516. }
  46517. sp.scaling.copyFrom(currentCopy.scaling);
  46518. sp.uvs.copyFrom(currentCopy.uvs);
  46519. }
  46520. this._index += shape.length;
  46521. idx++;
  46522. }
  46523. this.nbParticles += nb;
  46524. this._shapeCounter++;
  46525. return this._shapeCounter - 1;
  46526. };
  46527. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  46528. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  46529. this._resetCopy();
  46530. if (particle._model._positionFunction) {
  46531. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  46532. }
  46533. if (this._copy.rotationQuaternion) {
  46534. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  46535. }
  46536. else {
  46537. this._yaw = this._copy.rotation.y;
  46538. this._pitch = this._copy.rotation.x;
  46539. this._roll = this._copy.rotation.z;
  46540. this._quaternionRotationYPR();
  46541. }
  46542. this._quaternionToRotationMatrix();
  46543. this._shape = particle._model._shape;
  46544. for (var pt = 0; pt < this._shape.length; pt++) {
  46545. this._vertex.x = this._shape[pt].x;
  46546. this._vertex.y = this._shape[pt].y;
  46547. this._vertex.z = this._shape[pt].z;
  46548. if (particle._model._vertexFunction) {
  46549. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  46550. }
  46551. this._vertex.x *= this._copy.scaling.x;
  46552. this._vertex.y *= this._copy.scaling.y;
  46553. this._vertex.z *= this._copy.scaling.z;
  46554. this._vertex.x += this._copy.pivot.x;
  46555. this._vertex.y += this._copy.pivot.y;
  46556. this._vertex.z += this._copy.pivot.z;
  46557. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  46558. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  46559. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  46560. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  46561. }
  46562. particle.position.x = 0.0;
  46563. particle.position.y = 0.0;
  46564. particle.position.z = 0.0;
  46565. particle.rotation.x = 0.0;
  46566. particle.rotation.y = 0.0;
  46567. particle.rotation.z = 0.0;
  46568. particle.rotationQuaternion = null;
  46569. particle.scaling.x = 1.0;
  46570. particle.scaling.y = 1.0;
  46571. particle.scaling.z = 1.0;
  46572. };
  46573. /**
  46574. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  46575. * Returns the SPS.
  46576. */
  46577. SolidParticleSystem.prototype.rebuildMesh = function () {
  46578. for (var p = 0; p < this.particles.length; p++) {
  46579. this._rebuildParticle(this.particles[p]);
  46580. }
  46581. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  46582. return this;
  46583. };
  46584. /**
  46585. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  46586. * This method calls `updateParticle()` for each particle of the SPS.
  46587. * For an animated SPS, it is usually called within the render loop.
  46588. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  46589. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  46590. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  46591. * Returns the SPS.
  46592. */
  46593. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  46594. if (start === void 0) { start = 0; }
  46595. if (end === void 0) { end = this.nbParticles - 1; }
  46596. if (update === void 0) { update = true; }
  46597. if (!this._updatable) {
  46598. return this;
  46599. }
  46600. // custom beforeUpdate
  46601. this.beforeUpdateParticles(start, end, update);
  46602. this._cam_axisX.x = 1.0;
  46603. this._cam_axisX.y = 0.0;
  46604. this._cam_axisX.z = 0.0;
  46605. this._cam_axisY.x = 0.0;
  46606. this._cam_axisY.y = 1.0;
  46607. this._cam_axisY.z = 0.0;
  46608. this._cam_axisZ.x = 0.0;
  46609. this._cam_axisZ.y = 0.0;
  46610. this._cam_axisZ.z = 1.0;
  46611. // cases when the World Matrix is to be computed first
  46612. if (this.billboard || this._depthSort) {
  46613. this.mesh.computeWorldMatrix(true);
  46614. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  46615. }
  46616. // if the particles will always face the camera
  46617. if (this.billboard) {
  46618. // compute the camera position and un-rotate it by the current mesh rotation
  46619. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  46620. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  46621. this._cam_axisZ.normalize();
  46622. // same for camera up vector extracted from the cam view matrix
  46623. var view = this._camera.getViewMatrix(true);
  46624. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  46625. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  46626. this._cam_axisY.normalize();
  46627. this._cam_axisX.normalize();
  46628. }
  46629. // if depthSort, compute the camera global position in the mesh local system
  46630. if (this._depthSort) {
  46631. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  46632. }
  46633. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  46634. var idx = 0; // current position index in the global array positions32
  46635. var index = 0; // position start index in the global array positions32 of the current particle
  46636. var colidx = 0; // current color index in the global array colors32
  46637. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  46638. var uvidx = 0; // current uv index in the global array uvs32
  46639. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  46640. var pt = 0; // current index in the particle model shape
  46641. if (this.mesh.isFacetDataEnabled) {
  46642. this._computeBoundingBox = true;
  46643. }
  46644. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  46645. if (this._computeBoundingBox) {
  46646. if (start == 0 && end == this.nbParticles - 1) {
  46647. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  46648. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  46649. }
  46650. else {
  46651. if (this.mesh._boundingInfo) {
  46652. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  46653. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  46654. }
  46655. }
  46656. }
  46657. // particle loop
  46658. index = this.particles[start]._pos;
  46659. var vpos = (index / 3) | 0;
  46660. colorIndex = vpos * 4;
  46661. uvIndex = vpos * 2;
  46662. for (var p = start; p <= end; p++) {
  46663. this._particle = this.particles[p];
  46664. this._shape = this._particle._model._shape;
  46665. this._shapeUV = this._particle._model._shapeUV;
  46666. // call to custom user function to update the particle properties
  46667. this.updateParticle(this._particle);
  46668. // camera-particle distance for depth sorting
  46669. if (this._depthSort && this._depthSortParticles) {
  46670. var dsp = this.depthSortedParticles[p];
  46671. dsp.ind = this._particle._ind;
  46672. dsp.indicesLength = this._particle._model._indicesLength;
  46673. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  46674. }
  46675. // skip the computations for inactive or already invisible particles
  46676. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  46677. // increment indexes for the next particle
  46678. pt = this._shape.length;
  46679. index += pt * 3;
  46680. colorIndex += pt * 4;
  46681. uvIndex += pt * 2;
  46682. continue;
  46683. }
  46684. if (this._particle.isVisible) {
  46685. this._particle._stillInvisible = false; // un-mark permanent invisibility
  46686. // particle rotation matrix
  46687. if (this.billboard) {
  46688. this._particle.rotation.x = 0.0;
  46689. this._particle.rotation.y = 0.0;
  46690. }
  46691. if (this._computeParticleRotation || this.billboard) {
  46692. if (this._particle.rotationQuaternion) {
  46693. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  46694. }
  46695. else {
  46696. this._yaw = this._particle.rotation.y;
  46697. this._pitch = this._particle.rotation.x;
  46698. this._roll = this._particle.rotation.z;
  46699. this._quaternionRotationYPR();
  46700. }
  46701. this._quaternionToRotationMatrix();
  46702. }
  46703. // particle vertex loop
  46704. for (pt = 0; pt < this._shape.length; pt++) {
  46705. idx = index + pt * 3;
  46706. colidx = colorIndex + pt * 4;
  46707. uvidx = uvIndex + pt * 2;
  46708. this._vertex.x = this._shape[pt].x;
  46709. this._vertex.y = this._shape[pt].y;
  46710. this._vertex.z = this._shape[pt].z;
  46711. if (this._computeParticleVertex) {
  46712. this.updateParticleVertex(this._particle, this._vertex, pt);
  46713. }
  46714. // positions
  46715. this._vertex.x *= this._particle.scaling.x;
  46716. this._vertex.y *= this._particle.scaling.y;
  46717. this._vertex.z *= this._particle.scaling.z;
  46718. this._vertex.x += this._particle.pivot.x;
  46719. this._vertex.y += this._particle.pivot.y;
  46720. this._vertex.z += this._particle.pivot.z;
  46721. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  46722. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  46723. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  46724. 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;
  46725. 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;
  46726. 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;
  46727. if (this._computeBoundingBox) {
  46728. if (this._positions32[idx] < this._minimum.x) {
  46729. this._minimum.x = this._positions32[idx];
  46730. }
  46731. if (this._positions32[idx] > this._maximum.x) {
  46732. this._maximum.x = this._positions32[idx];
  46733. }
  46734. if (this._positions32[idx + 1] < this._minimum.y) {
  46735. this._minimum.y = this._positions32[idx + 1];
  46736. }
  46737. if (this._positions32[idx + 1] > this._maximum.y) {
  46738. this._maximum.y = this._positions32[idx + 1];
  46739. }
  46740. if (this._positions32[idx + 2] < this._minimum.z) {
  46741. this._minimum.z = this._positions32[idx + 2];
  46742. }
  46743. if (this._positions32[idx + 2] > this._maximum.z) {
  46744. this._maximum.z = this._positions32[idx + 2];
  46745. }
  46746. }
  46747. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  46748. if (!this._computeParticleVertex) {
  46749. this._normal.x = this._fixedNormal32[idx];
  46750. this._normal.y = this._fixedNormal32[idx + 1];
  46751. this._normal.z = this._fixedNormal32[idx + 2];
  46752. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  46753. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  46754. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  46755. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  46756. 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;
  46757. 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;
  46758. }
  46759. if (this._computeParticleColor && this._particle.color) {
  46760. this._colors32[colidx] = this._particle.color.r;
  46761. this._colors32[colidx + 1] = this._particle.color.g;
  46762. this._colors32[colidx + 2] = this._particle.color.b;
  46763. this._colors32[colidx + 3] = this._particle.color.a;
  46764. }
  46765. if (this._computeParticleTexture) {
  46766. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  46767. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  46768. }
  46769. }
  46770. }
  46771. else {
  46772. this._particle._stillInvisible = true; // mark the particle as invisible
  46773. for (pt = 0; pt < this._shape.length; pt++) {
  46774. idx = index + pt * 3;
  46775. colidx = colorIndex + pt * 4;
  46776. uvidx = uvIndex + pt * 2;
  46777. this._positions32[idx] = 0.0;
  46778. this._positions32[idx + 1] = 0.0;
  46779. this._positions32[idx + 2] = 0.0;
  46780. this._normals32[idx] = 0.0;
  46781. this._normals32[idx + 1] = 0.0;
  46782. this._normals32[idx + 2] = 0.0;
  46783. if (this._computeParticleColor && this._particle.color) {
  46784. this._colors32[colidx] = this._particle.color.r;
  46785. this._colors32[colidx + 1] = this._particle.color.g;
  46786. this._colors32[colidx + 2] = this._particle.color.b;
  46787. this._colors32[colidx + 3] = this._particle.color.a;
  46788. }
  46789. if (this._computeParticleTexture) {
  46790. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  46791. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  46792. }
  46793. }
  46794. }
  46795. // if the particle intersections must be computed : update the bbInfo
  46796. if (this._particlesIntersect) {
  46797. var bInfo = this._particle._boundingInfo;
  46798. var bBox = bInfo.boundingBox;
  46799. var bSphere = bInfo.boundingSphere;
  46800. if (!this._bSphereOnly) {
  46801. // place, scale and rotate the particle bbox within the SPS local system, then update it
  46802. for (var b = 0; b < bBox.vectors.length; b++) {
  46803. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  46804. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  46805. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  46806. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  46807. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  46808. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  46809. 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;
  46810. 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;
  46811. 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;
  46812. }
  46813. bBox._update(this.mesh._worldMatrix);
  46814. }
  46815. // place and scale the particle bouding sphere in the SPS local system, then update it
  46816. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  46817. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  46818. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  46819. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  46820. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  46821. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  46822. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  46823. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  46824. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  46825. 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));
  46826. bSphere._update(this.mesh._worldMatrix);
  46827. }
  46828. // increment indexes for the next particle
  46829. index = idx + 3;
  46830. colorIndex = colidx + 4;
  46831. uvIndex = uvidx + 2;
  46832. }
  46833. // if the VBO must be updated
  46834. if (update) {
  46835. if (this._computeParticleColor) {
  46836. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  46837. }
  46838. if (this._computeParticleTexture) {
  46839. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  46840. }
  46841. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  46842. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  46843. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  46844. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  46845. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  46846. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  46847. for (var i = 0; i < this._normals32.length; i++) {
  46848. this._fixedNormal32[i] = this._normals32[i];
  46849. }
  46850. }
  46851. if (!this.mesh.areNormalsFrozen) {
  46852. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  46853. }
  46854. }
  46855. if (this._depthSort && this._depthSortParticles) {
  46856. this.depthSortedParticles.sort(this._depthSortFunction);
  46857. var dspl = this.depthSortedParticles.length;
  46858. var sorted = 0;
  46859. var lind = 0;
  46860. var sind = 0;
  46861. var sid = 0;
  46862. for (sorted = 0; sorted < dspl; sorted++) {
  46863. lind = this.depthSortedParticles[sorted].indicesLength;
  46864. sind = this.depthSortedParticles[sorted].ind;
  46865. for (var i = 0; i < lind; i++) {
  46866. this._indices32[sid] = this._indices[sind + i];
  46867. sid++;
  46868. }
  46869. }
  46870. this.mesh.updateIndices(this._indices32);
  46871. }
  46872. }
  46873. if (this._computeBoundingBox) {
  46874. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  46875. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  46876. }
  46877. this.afterUpdateParticles(start, end, update);
  46878. return this;
  46879. };
  46880. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  46881. this._halfroll = this._roll * 0.5;
  46882. this._halfpitch = this._pitch * 0.5;
  46883. this._halfyaw = this._yaw * 0.5;
  46884. this._sinRoll = Math.sin(this._halfroll);
  46885. this._cosRoll = Math.cos(this._halfroll);
  46886. this._sinPitch = Math.sin(this._halfpitch);
  46887. this._cosPitch = Math.cos(this._halfpitch);
  46888. this._sinYaw = Math.sin(this._halfyaw);
  46889. this._cosYaw = Math.cos(this._halfyaw);
  46890. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  46891. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  46892. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  46893. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  46894. };
  46895. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  46896. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  46897. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  46898. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  46899. this._rotMatrix.m[3] = 0;
  46900. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  46901. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  46902. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  46903. this._rotMatrix.m[7] = 0;
  46904. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  46905. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  46906. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  46907. this._rotMatrix.m[11] = 0;
  46908. this._rotMatrix.m[12] = 0;
  46909. this._rotMatrix.m[13] = 0;
  46910. this._rotMatrix.m[14] = 0;
  46911. this._rotMatrix.m[15] = 1.0;
  46912. };
  46913. /**
  46914. * Disposes the SPS.
  46915. * Returns nothing.
  46916. */
  46917. SolidParticleSystem.prototype.dispose = function () {
  46918. this.mesh.dispose();
  46919. this.vars = null;
  46920. // drop references to internal big arrays for the GC
  46921. this._positions = null;
  46922. this._indices = null;
  46923. this._normals = null;
  46924. this._uvs = null;
  46925. this._colors = null;
  46926. this._indices32 = null;
  46927. this._positions32 = null;
  46928. this._normals32 = null;
  46929. this._fixedNormal32 = null;
  46930. this._uvs32 = null;
  46931. this._colors32 = null;
  46932. this.pickedParticles = null;
  46933. };
  46934. /**
  46935. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  46936. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46937. * Returns the SPS.
  46938. */
  46939. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  46940. if (!this._isVisibilityBoxLocked) {
  46941. this.mesh.refreshBoundingInfo();
  46942. }
  46943. return this;
  46944. };
  46945. /**
  46946. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  46947. * @param size the size (float) of the visibility box
  46948. * note : this doesn't lock the SPS mesh bounding box.
  46949. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46950. */
  46951. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  46952. var vis = size / 2;
  46953. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  46954. };
  46955. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  46956. // getter and setter
  46957. get: function () {
  46958. return this._alwaysVisible;
  46959. },
  46960. /**
  46961. * Sets the SPS as always visible or not
  46962. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46963. */
  46964. set: function (val) {
  46965. this._alwaysVisible = val;
  46966. this.mesh.alwaysSelectAsActiveMesh = val;
  46967. },
  46968. enumerable: true,
  46969. configurable: true
  46970. });
  46971. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  46972. get: function () {
  46973. return this._isVisibilityBoxLocked;
  46974. },
  46975. /**
  46976. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  46977. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46978. */
  46979. set: function (val) {
  46980. this._isVisibilityBoxLocked = val;
  46981. var boundingInfo = this.mesh.getBoundingInfo();
  46982. boundingInfo.isLocked = val;
  46983. },
  46984. enumerable: true,
  46985. configurable: true
  46986. });
  46987. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  46988. // getters
  46989. get: function () {
  46990. return this._computeParticleRotation;
  46991. },
  46992. // Optimizer setters
  46993. /**
  46994. * Tells to `setParticles()` to compute the particle rotations or not.
  46995. * Default value : true. The SPS is faster when it's set to false.
  46996. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  46997. */
  46998. set: function (val) {
  46999. this._computeParticleRotation = val;
  47000. },
  47001. enumerable: true,
  47002. configurable: true
  47003. });
  47004. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  47005. get: function () {
  47006. return this._computeParticleColor;
  47007. },
  47008. /**
  47009. * Tells to `setParticles()` to compute the particle colors or not.
  47010. * Default value : true. The SPS is faster when it's set to false.
  47011. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  47012. */
  47013. set: function (val) {
  47014. this._computeParticleColor = val;
  47015. },
  47016. enumerable: true,
  47017. configurable: true
  47018. });
  47019. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  47020. get: function () {
  47021. return this._computeParticleTexture;
  47022. },
  47023. /**
  47024. * Tells to `setParticles()` to compute the particle textures or not.
  47025. * Default value : true. The SPS is faster when it's set to false.
  47026. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  47027. */
  47028. set: function (val) {
  47029. this._computeParticleTexture = val;
  47030. },
  47031. enumerable: true,
  47032. configurable: true
  47033. });
  47034. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  47035. get: function () {
  47036. return this._computeParticleVertex;
  47037. },
  47038. /**
  47039. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  47040. * Default value : false. The SPS is faster when it's set to false.
  47041. * Note : the particle custom vertex positions aren't stored values.
  47042. */
  47043. set: function (val) {
  47044. this._computeParticleVertex = val;
  47045. },
  47046. enumerable: true,
  47047. configurable: true
  47048. });
  47049. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  47050. get: function () {
  47051. return this._computeBoundingBox;
  47052. },
  47053. /**
  47054. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  47055. */
  47056. set: function (val) {
  47057. this._computeBoundingBox = val;
  47058. },
  47059. enumerable: true,
  47060. configurable: true
  47061. });
  47062. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  47063. get: function () {
  47064. return this._depthSortParticles;
  47065. },
  47066. /**
  47067. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  47068. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  47069. * Default : `true`
  47070. */
  47071. set: function (val) {
  47072. this._depthSortParticles = val;
  47073. },
  47074. enumerable: true,
  47075. configurable: true
  47076. });
  47077. // =======================================================================
  47078. // Particle behavior logic
  47079. // these following methods may be overwritten by the user to fit his needs
  47080. /**
  47081. * This function does nothing. It may be overwritten to set all the particle first values.
  47082. * The SPS doesn't call this function, you may have to call it by your own.
  47083. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  47084. */
  47085. SolidParticleSystem.prototype.initParticles = function () {
  47086. };
  47087. /**
  47088. * This function does nothing. It may be overwritten to recycle a particle.
  47089. * The SPS doesn't call this function, you may have to call it by your own.
  47090. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  47091. */
  47092. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  47093. return particle;
  47094. };
  47095. /**
  47096. * Updates a particle : this function should be overwritten by the user.
  47097. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  47098. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  47099. * ex : just set a particle position or velocity and recycle conditions
  47100. */
  47101. SolidParticleSystem.prototype.updateParticle = function (particle) {
  47102. return particle;
  47103. };
  47104. /**
  47105. * Updates a vertex of a particle : it can be overwritten by the user.
  47106. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  47107. * @param particle the current particle
  47108. * @param vertex the current index of the current particle
  47109. * @param pt the index of the current vertex in the particle shape
  47110. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  47111. * ex : just set a vertex particle position
  47112. */
  47113. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  47114. return vertex;
  47115. };
  47116. /**
  47117. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  47118. * This does nothing and may be overwritten by the user.
  47119. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  47120. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  47121. * @param update the boolean update value actually passed to setParticles()
  47122. */
  47123. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  47124. };
  47125. /**
  47126. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  47127. * This will be passed three parameters.
  47128. * This does nothing and may be overwritten by the user.
  47129. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  47130. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  47131. * @param update the boolean update value actually passed to setParticles()
  47132. */
  47133. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  47134. };
  47135. return SolidParticleSystem;
  47136. }());
  47137. BABYLON.SolidParticleSystem = SolidParticleSystem;
  47138. })(BABYLON || (BABYLON = {}));
  47139. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  47140. var BABYLON;
  47141. (function (BABYLON) {
  47142. var GroundMesh = /** @class */ (function (_super) {
  47143. __extends(GroundMesh, _super);
  47144. function GroundMesh(name, scene) {
  47145. var _this = _super.call(this, name, scene) || this;
  47146. _this.generateOctree = false;
  47147. return _this;
  47148. }
  47149. GroundMesh.prototype.getClassName = function () {
  47150. return "GroundMesh";
  47151. };
  47152. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  47153. get: function () {
  47154. return Math.min(this._subdivisionsX, this._subdivisionsY);
  47155. },
  47156. enumerable: true,
  47157. configurable: true
  47158. });
  47159. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  47160. get: function () {
  47161. return this._subdivisionsX;
  47162. },
  47163. enumerable: true,
  47164. configurable: true
  47165. });
  47166. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  47167. get: function () {
  47168. return this._subdivisionsY;
  47169. },
  47170. enumerable: true,
  47171. configurable: true
  47172. });
  47173. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  47174. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  47175. this._subdivisionsX = chunksCount;
  47176. this._subdivisionsY = chunksCount;
  47177. this.subdivide(chunksCount);
  47178. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  47179. };
  47180. /**
  47181. * Returns a height (y) value in the Worl system :
  47182. * the ground altitude at the coordinates (x, z) expressed in the World system.
  47183. * Returns the ground y position if (x, z) are outside the ground surface.
  47184. */
  47185. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  47186. var world = this.getWorldMatrix();
  47187. var invMat = BABYLON.Tmp.Matrix[5];
  47188. world.invertToRef(invMat);
  47189. var tmpVect = BABYLON.Tmp.Vector3[8];
  47190. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  47191. x = tmpVect.x;
  47192. z = tmpVect.z;
  47193. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  47194. return this.position.y;
  47195. }
  47196. if (!this._heightQuads || this._heightQuads.length == 0) {
  47197. this._initHeightQuads();
  47198. this._computeHeightQuads();
  47199. }
  47200. var facet = this._getFacetAt(x, z);
  47201. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  47202. // return y in the World system
  47203. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  47204. return tmpVect.y;
  47205. };
  47206. /**
  47207. * Returns a normalized vector (Vector3) orthogonal to the ground
  47208. * at the ground coordinates (x, z) expressed in the World system.
  47209. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  47210. */
  47211. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  47212. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  47213. this.getNormalAtCoordinatesToRef(x, z, normal);
  47214. return normal;
  47215. };
  47216. /**
  47217. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  47218. * at the ground coordinates (x, z) expressed in the World system.
  47219. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  47220. * Returns the GroundMesh.
  47221. */
  47222. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  47223. var world = this.getWorldMatrix();
  47224. var tmpMat = BABYLON.Tmp.Matrix[5];
  47225. world.invertToRef(tmpMat);
  47226. var tmpVect = BABYLON.Tmp.Vector3[8];
  47227. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  47228. x = tmpVect.x;
  47229. z = tmpVect.z;
  47230. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  47231. return this;
  47232. }
  47233. if (!this._heightQuads || this._heightQuads.length == 0) {
  47234. this._initHeightQuads();
  47235. this._computeHeightQuads();
  47236. }
  47237. var facet = this._getFacetAt(x, z);
  47238. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  47239. return this;
  47240. };
  47241. /**
  47242. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  47243. * if the ground has been updated.
  47244. * This can be used in the render loop.
  47245. * Returns the GroundMesh.
  47246. */
  47247. GroundMesh.prototype.updateCoordinateHeights = function () {
  47248. if (!this._heightQuads || this._heightQuads.length == 0) {
  47249. this._initHeightQuads();
  47250. }
  47251. this._computeHeightQuads();
  47252. return this;
  47253. };
  47254. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  47255. GroundMesh.prototype._getFacetAt = function (x, z) {
  47256. // retrieve col and row from x, z coordinates in the ground local system
  47257. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  47258. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  47259. var quad = this._heightQuads[row * this._subdivisionsX + col];
  47260. var facet;
  47261. if (z < quad.slope.x * x + quad.slope.y) {
  47262. facet = quad.facet1;
  47263. }
  47264. else {
  47265. facet = quad.facet2;
  47266. }
  47267. return facet;
  47268. };
  47269. // Creates and populates the heightMap array with "facet" elements :
  47270. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  47271. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  47272. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  47273. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  47274. // Returns the GroundMesh.
  47275. GroundMesh.prototype._initHeightQuads = function () {
  47276. var subdivisionsX = this._subdivisionsX;
  47277. var subdivisionsY = this._subdivisionsY;
  47278. this._heightQuads = new Array();
  47279. for (var row = 0; row < subdivisionsY; row++) {
  47280. for (var col = 0; col < subdivisionsX; col++) {
  47281. 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) };
  47282. this._heightQuads[row * subdivisionsX + col] = quad;
  47283. }
  47284. }
  47285. return this;
  47286. };
  47287. // Compute each quad element values and update the the heightMap array :
  47288. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  47289. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  47290. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  47291. // Returns the GroundMesh.
  47292. GroundMesh.prototype._computeHeightQuads = function () {
  47293. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47294. if (!positions) {
  47295. return this;
  47296. }
  47297. var v1 = BABYLON.Tmp.Vector3[3];
  47298. var v2 = BABYLON.Tmp.Vector3[2];
  47299. var v3 = BABYLON.Tmp.Vector3[1];
  47300. var v4 = BABYLON.Tmp.Vector3[0];
  47301. var v1v2 = BABYLON.Tmp.Vector3[4];
  47302. var v1v3 = BABYLON.Tmp.Vector3[5];
  47303. var v1v4 = BABYLON.Tmp.Vector3[6];
  47304. var norm1 = BABYLON.Tmp.Vector3[7];
  47305. var norm2 = BABYLON.Tmp.Vector3[8];
  47306. var i = 0;
  47307. var j = 0;
  47308. var k = 0;
  47309. var cd = 0; // 2D slope coefficient : z = cd * x + h
  47310. var h = 0;
  47311. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  47312. var d2 = 0;
  47313. var subdivisionsX = this._subdivisionsX;
  47314. var subdivisionsY = this._subdivisionsY;
  47315. for (var row = 0; row < subdivisionsY; row++) {
  47316. for (var col = 0; col < subdivisionsX; col++) {
  47317. i = col * 3;
  47318. j = row * (subdivisionsX + 1) * 3;
  47319. k = (row + 1) * (subdivisionsX + 1) * 3;
  47320. v1.x = positions[j + i];
  47321. v1.y = positions[j + i + 1];
  47322. v1.z = positions[j + i + 2];
  47323. v2.x = positions[j + i + 3];
  47324. v2.y = positions[j + i + 4];
  47325. v2.z = positions[j + i + 5];
  47326. v3.x = positions[k + i];
  47327. v3.y = positions[k + i + 1];
  47328. v3.z = positions[k + i + 2];
  47329. v4.x = positions[k + i + 3];
  47330. v4.y = positions[k + i + 4];
  47331. v4.z = positions[k + i + 5];
  47332. // 2D slope V1V4
  47333. cd = (v4.z - v1.z) / (v4.x - v1.x);
  47334. h = v1.z - cd * v1.x; // v1 belongs to the slope
  47335. // facet equations :
  47336. // we compute each facet normal vector
  47337. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  47338. // we compute the value d by applying the equation to v1 which belongs to the plane
  47339. // then we store the facet equation in a Vector4
  47340. v2.subtractToRef(v1, v1v2);
  47341. v3.subtractToRef(v1, v1v3);
  47342. v4.subtractToRef(v1, v1v4);
  47343. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  47344. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  47345. norm1.normalize();
  47346. norm2.normalize();
  47347. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  47348. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  47349. var quad = this._heightQuads[row * subdivisionsX + col];
  47350. quad.slope.copyFromFloats(cd, h);
  47351. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  47352. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  47353. }
  47354. }
  47355. return this;
  47356. };
  47357. GroundMesh.prototype.serialize = function (serializationObject) {
  47358. _super.prototype.serialize.call(this, serializationObject);
  47359. serializationObject.subdivisionsX = this._subdivisionsX;
  47360. serializationObject.subdivisionsY = this._subdivisionsY;
  47361. serializationObject.minX = this._minX;
  47362. serializationObject.maxX = this._maxX;
  47363. serializationObject.minZ = this._minZ;
  47364. serializationObject.maxZ = this._maxZ;
  47365. serializationObject.width = this._width;
  47366. serializationObject.height = this._height;
  47367. };
  47368. GroundMesh.Parse = function (parsedMesh, scene) {
  47369. var result = new GroundMesh(parsedMesh.name, scene);
  47370. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  47371. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  47372. result._minX = parsedMesh.minX;
  47373. result._maxX = parsedMesh.maxX;
  47374. result._minZ = parsedMesh.minZ;
  47375. result._maxZ = parsedMesh.maxZ;
  47376. result._width = parsedMesh.width;
  47377. result._height = parsedMesh.height;
  47378. return result;
  47379. };
  47380. return GroundMesh;
  47381. }(BABYLON.Mesh));
  47382. BABYLON.GroundMesh = GroundMesh;
  47383. })(BABYLON || (BABYLON = {}));
  47384. //# sourceMappingURL=babylon.groundMesh.js.map
  47385. var BABYLON;
  47386. (function (BABYLON) {
  47387. /**
  47388. * Creates an instance based on a source mesh.
  47389. */
  47390. var InstancedMesh = /** @class */ (function (_super) {
  47391. __extends(InstancedMesh, _super);
  47392. function InstancedMesh(name, source) {
  47393. var _this = _super.call(this, name, source.getScene()) || this;
  47394. source.instances.push(_this);
  47395. _this._sourceMesh = source;
  47396. _this.position.copyFrom(source.position);
  47397. _this.rotation.copyFrom(source.rotation);
  47398. _this.scaling.copyFrom(source.scaling);
  47399. if (source.rotationQuaternion) {
  47400. _this.rotationQuaternion = source.rotationQuaternion.clone();
  47401. }
  47402. _this.infiniteDistance = source.infiniteDistance;
  47403. _this.setPivotMatrix(source.getPivotMatrix());
  47404. _this.refreshBoundingInfo();
  47405. _this._syncSubMeshes();
  47406. return _this;
  47407. }
  47408. /**
  47409. * Returns the string "InstancedMesh".
  47410. */
  47411. InstancedMesh.prototype.getClassName = function () {
  47412. return "InstancedMesh";
  47413. };
  47414. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  47415. // Methods
  47416. get: function () {
  47417. return this._sourceMesh.receiveShadows;
  47418. },
  47419. enumerable: true,
  47420. configurable: true
  47421. });
  47422. Object.defineProperty(InstancedMesh.prototype, "material", {
  47423. get: function () {
  47424. return this._sourceMesh.material;
  47425. },
  47426. enumerable: true,
  47427. configurable: true
  47428. });
  47429. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  47430. get: function () {
  47431. return this._sourceMesh.visibility;
  47432. },
  47433. enumerable: true,
  47434. configurable: true
  47435. });
  47436. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  47437. get: function () {
  47438. return this._sourceMesh.skeleton;
  47439. },
  47440. enumerable: true,
  47441. configurable: true
  47442. });
  47443. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  47444. get: function () {
  47445. return this._sourceMesh.renderingGroupId;
  47446. },
  47447. enumerable: true,
  47448. configurable: true
  47449. });
  47450. /**
  47451. * Returns the total number of vertices (integer).
  47452. */
  47453. InstancedMesh.prototype.getTotalVertices = function () {
  47454. return this._sourceMesh.getTotalVertices();
  47455. };
  47456. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  47457. get: function () {
  47458. return this._sourceMesh;
  47459. },
  47460. enumerable: true,
  47461. configurable: true
  47462. });
  47463. /**
  47464. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  47465. */
  47466. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  47467. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  47468. };
  47469. /**
  47470. * Sets the vertex data of the mesh geometry for the requested `kind`.
  47471. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  47472. * The `data` are either a numeric array either a Float32Array.
  47473. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  47474. * 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).
  47475. * Note that a new underlying VertexBuffer object is created each call.
  47476. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  47477. *
  47478. * Possible `kind` values :
  47479. * - BABYLON.VertexBuffer.PositionKind
  47480. * - BABYLON.VertexBuffer.UVKind
  47481. * - BABYLON.VertexBuffer.UV2Kind
  47482. * - BABYLON.VertexBuffer.UV3Kind
  47483. * - BABYLON.VertexBuffer.UV4Kind
  47484. * - BABYLON.VertexBuffer.UV5Kind
  47485. * - BABYLON.VertexBuffer.UV6Kind
  47486. * - BABYLON.VertexBuffer.ColorKind
  47487. * - BABYLON.VertexBuffer.MatricesIndicesKind
  47488. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  47489. * - BABYLON.VertexBuffer.MatricesWeightsKind
  47490. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  47491. *
  47492. * Returns the Mesh.
  47493. */
  47494. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  47495. if (this.sourceMesh) {
  47496. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  47497. }
  47498. return this.sourceMesh;
  47499. };
  47500. /**
  47501. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  47502. * If the mesh has no geometry, it is simply returned as it is.
  47503. * The `data` are either a numeric array either a Float32Array.
  47504. * No new underlying VertexBuffer object is created.
  47505. * 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.
  47506. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  47507. *
  47508. * Possible `kind` values :
  47509. * - BABYLON.VertexBuffer.PositionKind
  47510. * - BABYLON.VertexBuffer.UVKind
  47511. * - BABYLON.VertexBuffer.UV2Kind
  47512. * - BABYLON.VertexBuffer.UV3Kind
  47513. * - BABYLON.VertexBuffer.UV4Kind
  47514. * - BABYLON.VertexBuffer.UV5Kind
  47515. * - BABYLON.VertexBuffer.UV6Kind
  47516. * - BABYLON.VertexBuffer.ColorKind
  47517. * - BABYLON.VertexBuffer.MatricesIndicesKind
  47518. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  47519. * - BABYLON.VertexBuffer.MatricesWeightsKind
  47520. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  47521. *
  47522. * Returns the Mesh.
  47523. */
  47524. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  47525. if (this.sourceMesh) {
  47526. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  47527. }
  47528. return this.sourceMesh;
  47529. };
  47530. /**
  47531. * Sets the mesh indices.
  47532. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  47533. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  47534. * This method creates a new index buffer each call.
  47535. * Returns the Mesh.
  47536. */
  47537. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  47538. if (totalVertices === void 0) { totalVertices = null; }
  47539. if (this.sourceMesh) {
  47540. this.sourceMesh.setIndices(indices, totalVertices);
  47541. }
  47542. return this.sourceMesh;
  47543. };
  47544. /**
  47545. * Boolean : True if the mesh owns the requested kind of data.
  47546. */
  47547. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  47548. return this._sourceMesh.isVerticesDataPresent(kind);
  47549. };
  47550. /**
  47551. * Returns an array of indices (IndicesArray).
  47552. */
  47553. InstancedMesh.prototype.getIndices = function () {
  47554. return this._sourceMesh.getIndices();
  47555. };
  47556. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  47557. get: function () {
  47558. return this._sourceMesh._positions;
  47559. },
  47560. enumerable: true,
  47561. configurable: true
  47562. });
  47563. /**
  47564. * Sets a new updated BoundingInfo to the mesh.
  47565. * Returns the mesh.
  47566. */
  47567. InstancedMesh.prototype.refreshBoundingInfo = function () {
  47568. var meshBB = this._sourceMesh.getBoundingInfo();
  47569. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  47570. this._updateBoundingInfo();
  47571. return this;
  47572. };
  47573. InstancedMesh.prototype._preActivate = function () {
  47574. if (this._currentLOD) {
  47575. this._currentLOD._preActivate();
  47576. }
  47577. return this;
  47578. };
  47579. InstancedMesh.prototype._activate = function (renderId) {
  47580. if (this._currentLOD) {
  47581. this._currentLOD._registerInstanceForRenderId(this, renderId);
  47582. }
  47583. return this;
  47584. };
  47585. /**
  47586. * Returns the current associated LOD AbstractMesh.
  47587. */
  47588. InstancedMesh.prototype.getLOD = function (camera) {
  47589. if (!camera) {
  47590. return this;
  47591. }
  47592. var boundingInfo = this.getBoundingInfo();
  47593. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  47594. if (this._currentLOD === this.sourceMesh) {
  47595. return this;
  47596. }
  47597. return this._currentLOD;
  47598. };
  47599. InstancedMesh.prototype._syncSubMeshes = function () {
  47600. this.releaseSubMeshes();
  47601. if (this._sourceMesh.subMeshes) {
  47602. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  47603. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  47604. }
  47605. }
  47606. return this;
  47607. };
  47608. InstancedMesh.prototype._generatePointsArray = function () {
  47609. return this._sourceMesh._generatePointsArray();
  47610. };
  47611. /**
  47612. * Creates a new InstancedMesh from the current mesh.
  47613. * - name (string) : the cloned mesh name
  47614. * - newParent (optional Node) : the optional Node to parent the clone to.
  47615. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  47616. *
  47617. * Returns the clone.
  47618. */
  47619. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  47620. var result = this._sourceMesh.createInstance(name);
  47621. // Deep copy
  47622. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  47623. // Bounding info
  47624. this.refreshBoundingInfo();
  47625. // Parent
  47626. if (newParent) {
  47627. result.parent = newParent;
  47628. }
  47629. if (!doNotCloneChildren) {
  47630. // Children
  47631. for (var index = 0; index < this.getScene().meshes.length; index++) {
  47632. var mesh = this.getScene().meshes[index];
  47633. if (mesh.parent === this) {
  47634. mesh.clone(mesh.name, result);
  47635. }
  47636. }
  47637. }
  47638. result.computeWorldMatrix(true);
  47639. return result;
  47640. };
  47641. /**
  47642. * Disposes the InstancedMesh.
  47643. * Returns nothing.
  47644. */
  47645. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  47646. // Remove from mesh
  47647. var index = this._sourceMesh.instances.indexOf(this);
  47648. this._sourceMesh.instances.splice(index, 1);
  47649. _super.prototype.dispose.call(this, doNotRecurse);
  47650. };
  47651. return InstancedMesh;
  47652. }(BABYLON.AbstractMesh));
  47653. BABYLON.InstancedMesh = InstancedMesh;
  47654. })(BABYLON || (BABYLON = {}));
  47655. //# sourceMappingURL=babylon.instancedMesh.js.map
  47656. var BABYLON;
  47657. (function (BABYLON) {
  47658. var LinesMesh = /** @class */ (function (_super) {
  47659. __extends(LinesMesh, _super);
  47660. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  47661. if (scene === void 0) { scene = null; }
  47662. if (parent === void 0) { parent = null; }
  47663. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  47664. _this.useVertexColor = useVertexColor;
  47665. _this.useVertexAlpha = useVertexAlpha;
  47666. _this.color = new BABYLON.Color3(1, 1, 1);
  47667. _this.alpha = 1;
  47668. if (source) {
  47669. _this.color = source.color.clone();
  47670. _this.alpha = source.alpha;
  47671. _this.useVertexColor = source.useVertexColor;
  47672. _this.useVertexAlpha = source.useVertexAlpha;
  47673. }
  47674. _this._intersectionThreshold = 0.1;
  47675. var defines = [];
  47676. var options = {
  47677. attributes: [BABYLON.VertexBuffer.PositionKind],
  47678. uniforms: ["world", "viewProjection"],
  47679. needAlphaBlending: true,
  47680. defines: defines
  47681. };
  47682. if (useVertexAlpha === false) {
  47683. options.needAlphaBlending = false;
  47684. }
  47685. if (!useVertexColor) {
  47686. options.uniforms.push("color");
  47687. }
  47688. else {
  47689. options.defines.push("#define VERTEXCOLOR");
  47690. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  47691. }
  47692. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  47693. return _this;
  47694. }
  47695. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  47696. /**
  47697. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  47698. * This margin is expressed in world space coordinates, so its value may vary.
  47699. * Default value is 0.1
  47700. * @returns the intersection Threshold value.
  47701. */
  47702. get: function () {
  47703. return this._intersectionThreshold;
  47704. },
  47705. /**
  47706. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  47707. * This margin is expressed in world space coordinates, so its value may vary.
  47708. * @param value the new threshold to apply
  47709. */
  47710. set: function (value) {
  47711. if (this._intersectionThreshold === value) {
  47712. return;
  47713. }
  47714. this._intersectionThreshold = value;
  47715. if (this.geometry) {
  47716. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  47717. }
  47718. },
  47719. enumerable: true,
  47720. configurable: true
  47721. });
  47722. /**
  47723. * Returns the string "LineMesh"
  47724. */
  47725. LinesMesh.prototype.getClassName = function () {
  47726. return "LinesMesh";
  47727. };
  47728. Object.defineProperty(LinesMesh.prototype, "material", {
  47729. get: function () {
  47730. return this._colorShader;
  47731. },
  47732. set: function (value) {
  47733. // Do nothing
  47734. },
  47735. enumerable: true,
  47736. configurable: true
  47737. });
  47738. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  47739. get: function () {
  47740. return false;
  47741. },
  47742. enumerable: true,
  47743. configurable: true
  47744. });
  47745. LinesMesh.prototype.createInstance = function (name) {
  47746. throw new Error("LinesMeshes do not support createInstance.");
  47747. };
  47748. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  47749. if (!this._geometry) {
  47750. return this;
  47751. }
  47752. // VBOs
  47753. this._geometry._bind(this._colorShader.getEffect());
  47754. // Color
  47755. if (!this.useVertexColor) {
  47756. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  47757. }
  47758. return this;
  47759. };
  47760. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  47761. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  47762. return this;
  47763. }
  47764. var engine = this.getScene().getEngine();
  47765. // Draw order
  47766. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  47767. return this;
  47768. };
  47769. LinesMesh.prototype.dispose = function (doNotRecurse) {
  47770. this._colorShader.dispose();
  47771. _super.prototype.dispose.call(this, doNotRecurse);
  47772. };
  47773. /**
  47774. * Returns a new LineMesh object cloned from the current one.
  47775. */
  47776. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  47777. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  47778. };
  47779. return LinesMesh;
  47780. }(BABYLON.Mesh));
  47781. BABYLON.LinesMesh = LinesMesh;
  47782. })(BABYLON || (BABYLON = {}));
  47783. //# sourceMappingURL=babylon.linesMesh.js.map
  47784. var BABYLON;
  47785. (function (BABYLON) {
  47786. var ShaderMaterial = /** @class */ (function (_super) {
  47787. __extends(ShaderMaterial, _super);
  47788. function ShaderMaterial(name, scene, shaderPath, options) {
  47789. var _this = _super.call(this, name, scene) || this;
  47790. _this._textures = {};
  47791. _this._textureArrays = {};
  47792. _this._floats = {};
  47793. _this._floatsArrays = {};
  47794. _this._colors3 = {};
  47795. _this._colors3Arrays = {};
  47796. _this._colors4 = {};
  47797. _this._vectors2 = {};
  47798. _this._vectors3 = {};
  47799. _this._vectors4 = {};
  47800. _this._matrices = {};
  47801. _this._matrices3x3 = {};
  47802. _this._matrices2x2 = {};
  47803. _this._vectors2Arrays = {};
  47804. _this._vectors3Arrays = {};
  47805. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  47806. _this._shaderPath = shaderPath;
  47807. options.needAlphaBlending = options.needAlphaBlending || false;
  47808. options.needAlphaTesting = options.needAlphaTesting || false;
  47809. options.attributes = options.attributes || ["position", "normal", "uv"];
  47810. options.uniforms = options.uniforms || ["worldViewProjection"];
  47811. options.uniformBuffers = options.uniformBuffers || [];
  47812. options.samplers = options.samplers || [];
  47813. options.defines = options.defines || [];
  47814. _this._options = options;
  47815. return _this;
  47816. }
  47817. ShaderMaterial.prototype.getClassName = function () {
  47818. return "ShaderMaterial";
  47819. };
  47820. ShaderMaterial.prototype.needAlphaBlending = function () {
  47821. return this._options.needAlphaBlending;
  47822. };
  47823. ShaderMaterial.prototype.needAlphaTesting = function () {
  47824. return this._options.needAlphaTesting;
  47825. };
  47826. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  47827. if (this._options.uniforms.indexOf(uniformName) === -1) {
  47828. this._options.uniforms.push(uniformName);
  47829. }
  47830. };
  47831. ShaderMaterial.prototype.setTexture = function (name, texture) {
  47832. if (this._options.samplers.indexOf(name) === -1) {
  47833. this._options.samplers.push(name);
  47834. }
  47835. this._textures[name] = texture;
  47836. return this;
  47837. };
  47838. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  47839. if (this._options.samplers.indexOf(name) === -1) {
  47840. this._options.samplers.push(name);
  47841. }
  47842. this._checkUniform(name);
  47843. this._textureArrays[name] = textures;
  47844. return this;
  47845. };
  47846. ShaderMaterial.prototype.setFloat = function (name, value) {
  47847. this._checkUniform(name);
  47848. this._floats[name] = value;
  47849. return this;
  47850. };
  47851. ShaderMaterial.prototype.setFloats = function (name, value) {
  47852. this._checkUniform(name);
  47853. this._floatsArrays[name] = value;
  47854. return this;
  47855. };
  47856. ShaderMaterial.prototype.setColor3 = function (name, value) {
  47857. this._checkUniform(name);
  47858. this._colors3[name] = value;
  47859. return this;
  47860. };
  47861. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  47862. this._checkUniform(name);
  47863. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  47864. color.toArray(arr, arr.length);
  47865. return arr;
  47866. }, []);
  47867. return this;
  47868. };
  47869. ShaderMaterial.prototype.setColor4 = function (name, value) {
  47870. this._checkUniform(name);
  47871. this._colors4[name] = value;
  47872. return this;
  47873. };
  47874. ShaderMaterial.prototype.setVector2 = function (name, value) {
  47875. this._checkUniform(name);
  47876. this._vectors2[name] = value;
  47877. return this;
  47878. };
  47879. ShaderMaterial.prototype.setVector3 = function (name, value) {
  47880. this._checkUniform(name);
  47881. this._vectors3[name] = value;
  47882. return this;
  47883. };
  47884. ShaderMaterial.prototype.setVector4 = function (name, value) {
  47885. this._checkUniform(name);
  47886. this._vectors4[name] = value;
  47887. return this;
  47888. };
  47889. ShaderMaterial.prototype.setMatrix = function (name, value) {
  47890. this._checkUniform(name);
  47891. this._matrices[name] = value;
  47892. return this;
  47893. };
  47894. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  47895. this._checkUniform(name);
  47896. this._matrices3x3[name] = value;
  47897. return this;
  47898. };
  47899. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  47900. this._checkUniform(name);
  47901. this._matrices2x2[name] = value;
  47902. return this;
  47903. };
  47904. ShaderMaterial.prototype.setArray2 = function (name, value) {
  47905. this._checkUniform(name);
  47906. this._vectors2Arrays[name] = value;
  47907. return this;
  47908. };
  47909. ShaderMaterial.prototype.setArray3 = function (name, value) {
  47910. this._checkUniform(name);
  47911. this._vectors3Arrays[name] = value;
  47912. return this;
  47913. };
  47914. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  47915. if (!mesh) {
  47916. return true;
  47917. }
  47918. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  47919. return false;
  47920. }
  47921. return false;
  47922. };
  47923. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  47924. var scene = this.getScene();
  47925. var engine = scene.getEngine();
  47926. if (!this.checkReadyOnEveryCall) {
  47927. if (this._renderId === scene.getRenderId()) {
  47928. if (this._checkCache(scene, mesh, useInstances)) {
  47929. return true;
  47930. }
  47931. }
  47932. }
  47933. // Instances
  47934. var defines = [];
  47935. var attribs = [];
  47936. var fallbacks = new BABYLON.EffectFallbacks();
  47937. if (useInstances) {
  47938. defines.push("#define INSTANCES");
  47939. }
  47940. for (var index = 0; index < this._options.defines.length; index++) {
  47941. defines.push(this._options.defines[index]);
  47942. }
  47943. for (var index = 0; index < this._options.attributes.length; index++) {
  47944. attribs.push(this._options.attributes[index]);
  47945. }
  47946. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  47947. attribs.push(BABYLON.VertexBuffer.ColorKind);
  47948. defines.push("#define VERTEXCOLOR");
  47949. }
  47950. // Bones
  47951. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  47952. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47953. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47954. if (mesh.numBoneInfluencers > 4) {
  47955. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  47956. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  47957. }
  47958. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47959. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47960. fallbacks.addCPUSkinningFallback(0, mesh);
  47961. if (this._options.uniforms.indexOf("mBones") === -1) {
  47962. this._options.uniforms.push("mBones");
  47963. }
  47964. }
  47965. else {
  47966. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47967. }
  47968. // Textures
  47969. for (var name in this._textures) {
  47970. if (!this._textures[name].isReady()) {
  47971. return false;
  47972. }
  47973. }
  47974. // Alpha test
  47975. if (engine.getAlphaTesting()) {
  47976. defines.push("#define ALPHATEST");
  47977. }
  47978. var previousEffect = this._effect;
  47979. var join = defines.join("\n");
  47980. this._effect = engine.createEffect(this._shaderPath, {
  47981. attributes: attribs,
  47982. uniformsNames: this._options.uniforms,
  47983. uniformBuffersNames: this._options.uniformBuffers,
  47984. samplers: this._options.samplers,
  47985. defines: join,
  47986. fallbacks: fallbacks,
  47987. onCompiled: this.onCompiled,
  47988. onError: this.onError
  47989. }, engine);
  47990. if (!this._effect.isReady()) {
  47991. return false;
  47992. }
  47993. if (previousEffect !== this._effect) {
  47994. scene.resetCachedMaterial();
  47995. }
  47996. this._renderId = scene.getRenderId();
  47997. return true;
  47998. };
  47999. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  48000. var scene = this.getScene();
  48001. if (!this._effect) {
  48002. return;
  48003. }
  48004. if (this._options.uniforms.indexOf("world") !== -1) {
  48005. this._effect.setMatrix("world", world);
  48006. }
  48007. if (this._options.uniforms.indexOf("worldView") !== -1) {
  48008. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  48009. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  48010. }
  48011. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  48012. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  48013. }
  48014. };
  48015. ShaderMaterial.prototype.bind = function (world, mesh) {
  48016. // Std values
  48017. this.bindOnlyWorldMatrix(world);
  48018. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  48019. if (this._options.uniforms.indexOf("view") !== -1) {
  48020. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  48021. }
  48022. if (this._options.uniforms.indexOf("projection") !== -1) {
  48023. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  48024. }
  48025. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  48026. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  48027. }
  48028. // Bones
  48029. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  48030. var name;
  48031. // Texture
  48032. for (name in this._textures) {
  48033. this._effect.setTexture(name, this._textures[name]);
  48034. }
  48035. // Texture arrays
  48036. for (name in this._textureArrays) {
  48037. this._effect.setTextureArray(name, this._textureArrays[name]);
  48038. }
  48039. // Float
  48040. for (name in this._floats) {
  48041. this._effect.setFloat(name, this._floats[name]);
  48042. }
  48043. // Float s
  48044. for (name in this._floatsArrays) {
  48045. this._effect.setArray(name, this._floatsArrays[name]);
  48046. }
  48047. // Color3
  48048. for (name in this._colors3) {
  48049. this._effect.setColor3(name, this._colors3[name]);
  48050. }
  48051. for (name in this._colors3Arrays) {
  48052. this._effect.setArray3(name, this._colors3Arrays[name]);
  48053. }
  48054. // Color4
  48055. for (name in this._colors4) {
  48056. var color = this._colors4[name];
  48057. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  48058. }
  48059. // Vector2
  48060. for (name in this._vectors2) {
  48061. this._effect.setVector2(name, this._vectors2[name]);
  48062. }
  48063. // Vector3
  48064. for (name in this._vectors3) {
  48065. this._effect.setVector3(name, this._vectors3[name]);
  48066. }
  48067. // Vector4
  48068. for (name in this._vectors4) {
  48069. this._effect.setVector4(name, this._vectors4[name]);
  48070. }
  48071. // Matrix
  48072. for (name in this._matrices) {
  48073. this._effect.setMatrix(name, this._matrices[name]);
  48074. }
  48075. // Matrix 3x3
  48076. for (name in this._matrices3x3) {
  48077. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  48078. }
  48079. // Matrix 2x2
  48080. for (name in this._matrices2x2) {
  48081. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  48082. }
  48083. // Vector2Array
  48084. for (name in this._vectors2Arrays) {
  48085. this._effect.setArray2(name, this._vectors2Arrays[name]);
  48086. }
  48087. // Vector3Array
  48088. for (name in this._vectors3Arrays) {
  48089. this._effect.setArray3(name, this._vectors3Arrays[name]);
  48090. }
  48091. }
  48092. this._afterBind(mesh);
  48093. };
  48094. ShaderMaterial.prototype.getActiveTextures = function () {
  48095. var activeTextures = _super.prototype.getActiveTextures.call(this);
  48096. for (var name in this._textures) {
  48097. activeTextures.push(this._textures[name]);
  48098. }
  48099. for (var name in this._textureArrays) {
  48100. var array = this._textureArrays[name];
  48101. for (var index = 0; index < array.length; index++) {
  48102. activeTextures.push(array[index]);
  48103. }
  48104. }
  48105. return activeTextures;
  48106. };
  48107. ShaderMaterial.prototype.hasTexture = function (texture) {
  48108. if (_super.prototype.hasTexture.call(this, texture)) {
  48109. return true;
  48110. }
  48111. for (var name in this._textures) {
  48112. if (this._textures[name] === texture) {
  48113. return true;
  48114. }
  48115. }
  48116. for (var name in this._textureArrays) {
  48117. var array = this._textureArrays[name];
  48118. for (var index = 0; index < array.length; index++) {
  48119. if (array[index] === texture) {
  48120. return true;
  48121. }
  48122. }
  48123. }
  48124. return false;
  48125. };
  48126. ShaderMaterial.prototype.clone = function (name) {
  48127. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  48128. return newShaderMaterial;
  48129. };
  48130. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  48131. if (forceDisposeTextures) {
  48132. var name;
  48133. for (name in this._textures) {
  48134. this._textures[name].dispose();
  48135. }
  48136. for (name in this._textureArrays) {
  48137. var array = this._textureArrays[name];
  48138. for (var index = 0; index < array.length; index++) {
  48139. array[index].dispose();
  48140. }
  48141. }
  48142. }
  48143. this._textures = {};
  48144. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  48145. };
  48146. ShaderMaterial.prototype.serialize = function () {
  48147. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  48148. serializationObject.customType = "BABYLON.ShaderMaterial";
  48149. serializationObject.options = this._options;
  48150. serializationObject.shaderPath = this._shaderPath;
  48151. var name;
  48152. // Texture
  48153. serializationObject.textures = {};
  48154. for (name in this._textures) {
  48155. serializationObject.textures[name] = this._textures[name].serialize();
  48156. }
  48157. // Texture arrays
  48158. serializationObject.textureArrays = {};
  48159. for (name in this._textureArrays) {
  48160. serializationObject.textureArrays[name] = [];
  48161. var array = this._textureArrays[name];
  48162. for (var index = 0; index < array.length; index++) {
  48163. serializationObject.textureArrays[name].push(array[index].serialize());
  48164. }
  48165. }
  48166. // Float
  48167. serializationObject.floats = {};
  48168. for (name in this._floats) {
  48169. serializationObject.floats[name] = this._floats[name];
  48170. }
  48171. // Float s
  48172. serializationObject.FloatArrays = {};
  48173. for (name in this._floatsArrays) {
  48174. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  48175. }
  48176. // Color3
  48177. serializationObject.colors3 = {};
  48178. for (name in this._colors3) {
  48179. serializationObject.colors3[name] = this._colors3[name].asArray();
  48180. }
  48181. // Color3 array
  48182. serializationObject.colors3Arrays = {};
  48183. for (name in this._colors3Arrays) {
  48184. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  48185. }
  48186. // Color4
  48187. serializationObject.colors4 = {};
  48188. for (name in this._colors4) {
  48189. serializationObject.colors4[name] = this._colors4[name].asArray();
  48190. }
  48191. // Vector2
  48192. serializationObject.vectors2 = {};
  48193. for (name in this._vectors2) {
  48194. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  48195. }
  48196. // Vector3
  48197. serializationObject.vectors3 = {};
  48198. for (name in this._vectors3) {
  48199. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  48200. }
  48201. // Vector4
  48202. serializationObject.vectors4 = {};
  48203. for (name in this._vectors4) {
  48204. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  48205. }
  48206. // Matrix
  48207. serializationObject.matrices = {};
  48208. for (name in this._matrices) {
  48209. serializationObject.matrices[name] = this._matrices[name].asArray();
  48210. }
  48211. // Matrix 3x3
  48212. serializationObject.matrices3x3 = {};
  48213. for (name in this._matrices3x3) {
  48214. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  48215. }
  48216. // Matrix 2x2
  48217. serializationObject.matrices2x2 = {};
  48218. for (name in this._matrices2x2) {
  48219. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  48220. }
  48221. // Vector2Array
  48222. serializationObject.vectors2Arrays = {};
  48223. for (name in this._vectors2Arrays) {
  48224. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  48225. }
  48226. // Vector3Array
  48227. serializationObject.vectors3Arrays = {};
  48228. for (name in this._vectors3Arrays) {
  48229. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  48230. }
  48231. return serializationObject;
  48232. };
  48233. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  48234. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  48235. var name;
  48236. // Texture
  48237. for (name in source.textures) {
  48238. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  48239. }
  48240. // Texture arrays
  48241. for (name in source.textureArrays) {
  48242. var array = source.textureArrays[name];
  48243. var textureArray = new Array();
  48244. for (var index = 0; index < array.length; index++) {
  48245. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  48246. }
  48247. material.setTextureArray(name, textureArray);
  48248. }
  48249. // Float
  48250. for (name in source.floats) {
  48251. material.setFloat(name, source.floats[name]);
  48252. }
  48253. // Float s
  48254. for (name in source.floatsArrays) {
  48255. material.setFloats(name, source.floatsArrays[name]);
  48256. }
  48257. // Color3
  48258. for (name in source.colors3) {
  48259. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  48260. }
  48261. // Color3 arrays
  48262. for (name in source.colors3Arrays) {
  48263. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  48264. if (i % 3 === 0) {
  48265. arr.push([num]);
  48266. }
  48267. else {
  48268. arr[arr.length - 1].push(num);
  48269. }
  48270. return arr;
  48271. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  48272. material.setColor3Array(name, colors);
  48273. }
  48274. // Color4
  48275. for (name in source.colors4) {
  48276. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  48277. }
  48278. // Vector2
  48279. for (name in source.vectors2) {
  48280. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  48281. }
  48282. // Vector3
  48283. for (name in source.vectors3) {
  48284. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  48285. }
  48286. // Vector4
  48287. for (name in source.vectors4) {
  48288. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  48289. }
  48290. // Matrix
  48291. for (name in source.matrices) {
  48292. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  48293. }
  48294. // Matrix 3x3
  48295. for (name in source.matrices3x3) {
  48296. material.setMatrix3x3(name, source.matrices3x3[name]);
  48297. }
  48298. // Matrix 2x2
  48299. for (name in source.matrices2x2) {
  48300. material.setMatrix2x2(name, source.matrices2x2[name]);
  48301. }
  48302. // Vector2Array
  48303. for (name in source.vectors2Arrays) {
  48304. material.setArray2(name, source.vectors2Arrays[name]);
  48305. }
  48306. // Vector3Array
  48307. for (name in source.vectors3Arrays) {
  48308. material.setArray3(name, source.vectors3Arrays[name]);
  48309. }
  48310. return material;
  48311. };
  48312. return ShaderMaterial;
  48313. }(BABYLON.Material));
  48314. BABYLON.ShaderMaterial = ShaderMaterial;
  48315. })(BABYLON || (BABYLON = {}));
  48316. //# sourceMappingURL=babylon.shaderMaterial.js.map
  48317. var BABYLON;
  48318. (function (BABYLON) {
  48319. var MeshBuilder = /** @class */ (function () {
  48320. function MeshBuilder() {
  48321. }
  48322. MeshBuilder.updateSideOrientation = function (orientation) {
  48323. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  48324. return BABYLON.Mesh.DOUBLESIDE;
  48325. }
  48326. if (orientation === undefined || orientation === null) {
  48327. return BABYLON.Mesh.FRONTSIDE;
  48328. }
  48329. return orientation;
  48330. };
  48331. /**
  48332. * Creates a box mesh.
  48333. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  48334. * The parameter `size` sets the size (float) of each box side (default 1).
  48335. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  48336. * 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).
  48337. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  48338. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48339. * 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).
  48340. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48341. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48342. */
  48343. MeshBuilder.CreateBox = function (name, options, scene) {
  48344. if (scene === void 0) { scene = null; }
  48345. var box = new BABYLON.Mesh(name, scene);
  48346. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48347. box._originalBuilderSideOrientation = options.sideOrientation;
  48348. var vertexData = BABYLON.VertexData.CreateBox(options);
  48349. vertexData.applyToMesh(box, options.updatable);
  48350. return box;
  48351. };
  48352. /**
  48353. * Creates a sphere mesh.
  48354. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  48355. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  48356. * 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`).
  48357. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  48358. * 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
  48359. * 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).
  48360. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48361. * 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).
  48362. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48363. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48364. */
  48365. MeshBuilder.CreateSphere = function (name, options, scene) {
  48366. var sphere = new BABYLON.Mesh(name, scene);
  48367. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48368. sphere._originalBuilderSideOrientation = options.sideOrientation;
  48369. var vertexData = BABYLON.VertexData.CreateSphere(options);
  48370. vertexData.applyToMesh(sphere, options.updatable);
  48371. return sphere;
  48372. };
  48373. /**
  48374. * Creates a plane polygonal mesh. By default, this is a disc.
  48375. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  48376. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  48377. * 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.
  48378. * 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
  48379. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48380. * 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).
  48381. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48382. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48383. */
  48384. MeshBuilder.CreateDisc = function (name, options, scene) {
  48385. if (scene === void 0) { scene = null; }
  48386. var disc = new BABYLON.Mesh(name, scene);
  48387. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48388. disc._originalBuilderSideOrientation = options.sideOrientation;
  48389. var vertexData = BABYLON.VertexData.CreateDisc(options);
  48390. vertexData.applyToMesh(disc, options.updatable);
  48391. return disc;
  48392. };
  48393. /**
  48394. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  48395. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  48396. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  48397. * 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`).
  48398. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  48399. * 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.
  48400. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48401. * 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).
  48402. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48403. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48404. */
  48405. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  48406. var sphere = new BABYLON.Mesh(name, scene);
  48407. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48408. sphere._originalBuilderSideOrientation = options.sideOrientation;
  48409. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  48410. vertexData.applyToMesh(sphere, options.updatable);
  48411. return sphere;
  48412. };
  48413. ;
  48414. /**
  48415. * Creates a ribbon mesh.
  48416. * 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.
  48417. *
  48418. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  48419. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  48420. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  48421. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  48422. * 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.
  48423. * 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.
  48424. * 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
  48425. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48426. * 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).
  48427. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48428. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48429. * 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.
  48430. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  48431. * 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
  48432. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  48433. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  48434. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48435. */
  48436. MeshBuilder.CreateRibbon = function (name, options, scene) {
  48437. if (scene === void 0) { scene = null; }
  48438. var pathArray = options.pathArray;
  48439. var closeArray = options.closeArray;
  48440. var closePath = options.closePath;
  48441. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48442. var instance = options.instance;
  48443. var updatable = options.updatable;
  48444. if (instance) {
  48445. // positionFunction : ribbon case
  48446. // only pathArray and sideOrientation parameters are taken into account for positions update
  48447. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  48448. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  48449. var positionFunction = function (positions) {
  48450. var minlg = pathArray[0].length;
  48451. var i = 0;
  48452. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  48453. for (var si = 1; si <= ns; si++) {
  48454. for (var p = 0; p < pathArray.length; p++) {
  48455. var path = pathArray[p];
  48456. var l = path.length;
  48457. minlg = (minlg < l) ? minlg : l;
  48458. var j = 0;
  48459. while (j < minlg) {
  48460. positions[i] = path[j].x;
  48461. positions[i + 1] = path[j].y;
  48462. positions[i + 2] = path[j].z;
  48463. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  48464. BABYLON.Tmp.Vector3[0].x = path[j].x;
  48465. }
  48466. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  48467. BABYLON.Tmp.Vector3[1].x = path[j].x;
  48468. }
  48469. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  48470. BABYLON.Tmp.Vector3[0].y = path[j].y;
  48471. }
  48472. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  48473. BABYLON.Tmp.Vector3[1].y = path[j].y;
  48474. }
  48475. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  48476. BABYLON.Tmp.Vector3[0].z = path[j].z;
  48477. }
  48478. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  48479. BABYLON.Tmp.Vector3[1].z = path[j].z;
  48480. }
  48481. j++;
  48482. i += 3;
  48483. }
  48484. if (instance._closePath) {
  48485. positions[i] = path[0].x;
  48486. positions[i + 1] = path[0].y;
  48487. positions[i + 2] = path[0].z;
  48488. i += 3;
  48489. }
  48490. }
  48491. }
  48492. };
  48493. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48494. positionFunction(positions);
  48495. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  48496. instance._boundingInfo.update(instance._worldMatrix);
  48497. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  48498. if (options.colors) {
  48499. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  48500. for (var c = 0; c < options.colors.length; c++) {
  48501. colors[c * 4] = options.colors[c].r;
  48502. colors[c * 4 + 1] = options.colors[c].g;
  48503. colors[c * 4 + 2] = options.colors[c].b;
  48504. colors[c * 4 + 3] = options.colors[c].a;
  48505. }
  48506. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  48507. }
  48508. if (options.uvs) {
  48509. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48510. for (var i = 0; i < options.uvs.length; i++) {
  48511. uvs[i * 2] = options.uvs[i].x;
  48512. uvs[i * 2 + 1] = options.uvs[i].y;
  48513. }
  48514. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  48515. }
  48516. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  48517. var indices = instance.getIndices();
  48518. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48519. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  48520. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  48521. if (instance._closePath) {
  48522. var indexFirst = 0;
  48523. var indexLast = 0;
  48524. for (var p = 0; p < pathArray.length; p++) {
  48525. indexFirst = instance._idx[p] * 3;
  48526. if (p + 1 < pathArray.length) {
  48527. indexLast = (instance._idx[p + 1] - 1) * 3;
  48528. }
  48529. else {
  48530. indexLast = normals.length - 3;
  48531. }
  48532. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  48533. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  48534. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  48535. normals[indexLast] = normals[indexFirst];
  48536. normals[indexLast + 1] = normals[indexFirst + 1];
  48537. normals[indexLast + 2] = normals[indexFirst + 2];
  48538. }
  48539. }
  48540. if (!(instance.areNormalsFrozen)) {
  48541. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  48542. }
  48543. }
  48544. return instance;
  48545. }
  48546. else {
  48547. var ribbon = new BABYLON.Mesh(name, scene);
  48548. ribbon._originalBuilderSideOrientation = sideOrientation;
  48549. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  48550. if (closePath) {
  48551. ribbon._idx = vertexData._idx;
  48552. }
  48553. ribbon._closePath = closePath;
  48554. ribbon._closeArray = closeArray;
  48555. vertexData.applyToMesh(ribbon, updatable);
  48556. return ribbon;
  48557. }
  48558. };
  48559. /**
  48560. * Creates a cylinder or a cone mesh.
  48561. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  48562. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  48563. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  48564. * 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.
  48565. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  48566. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  48567. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  48568. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  48569. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  48570. * 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).
  48571. * 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
  48572. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  48573. * 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
  48574. * 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.
  48575. * If `enclose` is false, a ring surface is one element.
  48576. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  48577. * 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
  48578. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48579. * 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).
  48580. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48581. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48582. */
  48583. MeshBuilder.CreateCylinder = function (name, options, scene) {
  48584. var cylinder = new BABYLON.Mesh(name, scene);
  48585. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48586. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  48587. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  48588. vertexData.applyToMesh(cylinder, options.updatable);
  48589. return cylinder;
  48590. };
  48591. /**
  48592. * Creates a torus mesh.
  48593. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  48594. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  48595. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  48596. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  48597. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48598. * 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).
  48599. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48600. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48601. */
  48602. MeshBuilder.CreateTorus = function (name, options, scene) {
  48603. var torus = new BABYLON.Mesh(name, scene);
  48604. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48605. torus._originalBuilderSideOrientation = options.sideOrientation;
  48606. var vertexData = BABYLON.VertexData.CreateTorus(options);
  48607. vertexData.applyToMesh(torus, options.updatable);
  48608. return torus;
  48609. };
  48610. /**
  48611. * Creates a torus knot mesh.
  48612. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  48613. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  48614. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  48615. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  48616. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  48617. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48618. * 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).
  48619. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48620. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48621. */
  48622. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  48623. var torusKnot = new BABYLON.Mesh(name, scene);
  48624. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48625. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  48626. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  48627. vertexData.applyToMesh(torusKnot, options.updatable);
  48628. return torusKnot;
  48629. };
  48630. /**
  48631. * Creates a line system mesh.
  48632. * A line system is a pool of many lines gathered in a single mesh.
  48633. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  48634. * 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.
  48635. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  48636. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  48637. * 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
  48638. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  48639. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  48640. * 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
  48641. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  48642. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48643. */
  48644. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  48645. var instance = options.instance;
  48646. var lines = options.lines;
  48647. var colors = options.colors;
  48648. if (instance) {
  48649. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48650. var vertexColor;
  48651. var lineColors;
  48652. if (colors) {
  48653. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  48654. }
  48655. var i = 0;
  48656. var c = 0;
  48657. for (var l = 0; l < lines.length; l++) {
  48658. var points = lines[l];
  48659. for (var p = 0; p < points.length; p++) {
  48660. positions[i] = points[p].x;
  48661. positions[i + 1] = points[p].y;
  48662. positions[i + 2] = points[p].z;
  48663. if (colors && vertexColor) {
  48664. lineColors = colors[l];
  48665. vertexColor[c] = lineColors[p].r;
  48666. vertexColor[c + 1] = lineColors[p].g;
  48667. vertexColor[c + 2] = lineColors[p].b;
  48668. vertexColor[c + 3] = lineColors[p].a;
  48669. c += 4;
  48670. }
  48671. i += 3;
  48672. }
  48673. }
  48674. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  48675. if (colors && vertexColor) {
  48676. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  48677. }
  48678. return instance;
  48679. }
  48680. // line system creation
  48681. var useVertexColor = (colors) ? true : false;
  48682. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  48683. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  48684. vertexData.applyToMesh(lineSystem, options.updatable);
  48685. return lineSystem;
  48686. };
  48687. /**
  48688. * Creates a line mesh.
  48689. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  48690. * 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.
  48691. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  48692. * The parameter `points` is an array successive Vector3.
  48693. * 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
  48694. * The optional parameter `colors` is an array of successive Color4, one per line point.
  48695. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  48696. * When updating an instance, remember that only point positions can change, not the number of points.
  48697. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48698. */
  48699. MeshBuilder.CreateLines = function (name, options, scene) {
  48700. if (scene === void 0) { scene = null; }
  48701. var colors = (options.colors) ? [options.colors] : null;
  48702. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  48703. return lines;
  48704. };
  48705. /**
  48706. * Creates a dashed line mesh.
  48707. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  48708. * 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.
  48709. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  48710. * The parameter `points` is an array successive Vector3.
  48711. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  48712. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  48713. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  48714. * 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
  48715. * When updating an instance, remember that only point positions can change, not the number of points.
  48716. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48717. */
  48718. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  48719. if (scene === void 0) { scene = null; }
  48720. var points = options.points;
  48721. var instance = options.instance;
  48722. var gapSize = options.gapSize || 1;
  48723. var dashSize = options.dashSize || 3;
  48724. if (instance) {
  48725. var positionFunction = function (positions) {
  48726. var curvect = BABYLON.Vector3.Zero();
  48727. var nbSeg = positions.length / 6;
  48728. var lg = 0;
  48729. var nb = 0;
  48730. var shft = 0;
  48731. var dashshft = 0;
  48732. var curshft = 0;
  48733. var p = 0;
  48734. var i = 0;
  48735. var j = 0;
  48736. for (i = 0; i < points.length - 1; i++) {
  48737. points[i + 1].subtractToRef(points[i], curvect);
  48738. lg += curvect.length();
  48739. }
  48740. shft = lg / nbSeg;
  48741. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  48742. for (i = 0; i < points.length - 1; i++) {
  48743. points[i + 1].subtractToRef(points[i], curvect);
  48744. nb = Math.floor(curvect.length() / shft);
  48745. curvect.normalize();
  48746. j = 0;
  48747. while (j < nb && p < positions.length) {
  48748. curshft = shft * j;
  48749. positions[p] = points[i].x + curshft * curvect.x;
  48750. positions[p + 1] = points[i].y + curshft * curvect.y;
  48751. positions[p + 2] = points[i].z + curshft * curvect.z;
  48752. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  48753. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  48754. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  48755. p += 6;
  48756. j++;
  48757. }
  48758. }
  48759. while (p < positions.length) {
  48760. positions[p] = points[i].x;
  48761. positions[p + 1] = points[i].y;
  48762. positions[p + 2] = points[i].z;
  48763. p += 3;
  48764. }
  48765. };
  48766. instance.updateMeshPositions(positionFunction, false);
  48767. return instance;
  48768. }
  48769. // dashed lines creation
  48770. var dashedLines = new BABYLON.LinesMesh(name, scene);
  48771. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  48772. vertexData.applyToMesh(dashedLines, options.updatable);
  48773. dashedLines.dashSize = dashSize;
  48774. dashedLines.gapSize = gapSize;
  48775. return dashedLines;
  48776. };
  48777. /**
  48778. * Creates an extruded shape mesh.
  48779. * 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.
  48780. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  48781. *
  48782. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  48783. * 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
  48784. * extruded along the Z axis.
  48785. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  48786. * 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.
  48787. * The parameter `scale` (float, default 1) is the value to scale the shape.
  48788. * 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
  48789. * 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
  48790. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  48791. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48792. * 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).
  48793. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48794. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48795. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48796. */
  48797. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  48798. if (scene === void 0) { scene = null; }
  48799. var path = options.path;
  48800. var shape = options.shape;
  48801. var scale = options.scale || 1;
  48802. var rotation = options.rotation || 0;
  48803. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  48804. var updatable = options.updatable;
  48805. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48806. var instance = options.instance || null;
  48807. var invertUV = options.invertUV || false;
  48808. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable ? true : false, sideOrientation, instance, invertUV, options.frontUVs || null, options.backUVs || null);
  48809. };
  48810. /**
  48811. * Creates an custom extruded shape mesh.
  48812. * 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.
  48813. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  48814. *
  48815. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  48816. * 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
  48817. * extruded along the Z axis.
  48818. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  48819. * 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
  48820. * and the distance of this point from the begining of the path :
  48821. * ```javascript
  48822. * var rotationFunction = function(i, distance) {
  48823. * // do things
  48824. * return rotationValue; }
  48825. * ```
  48826. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  48827. * 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
  48828. * and the distance of this point from the begining of the path :
  48829. * ```javascript
  48830. * var scaleFunction = function(i, distance) {
  48831. * // do things
  48832. * return scaleValue;}
  48833. * ```
  48834. * It must returns a float value that will be the scale value applied to the shape on each path point.
  48835. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  48836. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  48837. * 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
  48838. * 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
  48839. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  48840. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48841. * 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).
  48842. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48843. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48844. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48845. */
  48846. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  48847. var path = options.path;
  48848. var shape = options.shape;
  48849. var scaleFunction = options.scaleFunction || (function () { return 1; });
  48850. var rotationFunction = options.rotationFunction || (function () { return 0; });
  48851. var ribbonCloseArray = options.ribbonCloseArray || false;
  48852. var ribbonClosePath = options.ribbonClosePath || false;
  48853. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  48854. var updatable = options.updatable;
  48855. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48856. var instance = options.instance;
  48857. var invertUV = options.invertUV || false;
  48858. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable ? true : false, sideOrientation, instance || null, invertUV, options.frontUVs || null, options.backUVs || null);
  48859. };
  48860. /**
  48861. * Creates lathe mesh.
  48862. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  48863. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  48864. *
  48865. * 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
  48866. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  48867. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  48868. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  48869. * 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.
  48870. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  48871. * 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
  48872. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48873. * 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).
  48874. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48875. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48876. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48877. */
  48878. MeshBuilder.CreateLathe = function (name, options, scene) {
  48879. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  48880. var closed = (options.closed === undefined) ? true : options.closed;
  48881. var shape = options.shape;
  48882. var radius = options.radius || 1;
  48883. var tessellation = options.tessellation || 64;
  48884. var updatable = options.updatable;
  48885. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48886. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  48887. var pi2 = Math.PI * 2;
  48888. var paths = new Array();
  48889. var invertUV = options.invertUV || false;
  48890. var i = 0;
  48891. var p = 0;
  48892. var step = pi2 / tessellation * arc;
  48893. var rotated;
  48894. var path = new Array();
  48895. ;
  48896. for (i = 0; i <= tessellation; i++) {
  48897. var path = [];
  48898. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  48899. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  48900. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  48901. }
  48902. for (p = 0; p < shape.length; p++) {
  48903. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  48904. path.push(rotated);
  48905. }
  48906. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  48907. 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));
  48908. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  48909. }
  48910. paths.push(path);
  48911. }
  48912. // lathe ribbon
  48913. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  48914. return lathe;
  48915. };
  48916. /**
  48917. * Creates a plane mesh.
  48918. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  48919. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  48920. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  48921. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  48922. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48923. * 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).
  48924. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48925. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48926. */
  48927. MeshBuilder.CreatePlane = function (name, options, scene) {
  48928. var plane = new BABYLON.Mesh(name, scene);
  48929. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48930. plane._originalBuilderSideOrientation = options.sideOrientation;
  48931. var vertexData = BABYLON.VertexData.CreatePlane(options);
  48932. vertexData.applyToMesh(plane, options.updatable);
  48933. if (options.sourcePlane) {
  48934. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  48935. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  48936. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  48937. plane.rotate(vectorProduct, product);
  48938. }
  48939. return plane;
  48940. };
  48941. /**
  48942. * Creates a ground mesh.
  48943. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  48944. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  48945. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  48946. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48947. */
  48948. MeshBuilder.CreateGround = function (name, options, scene) {
  48949. var ground = new BABYLON.GroundMesh(name, scene);
  48950. ground._setReady(false);
  48951. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  48952. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  48953. ground._width = options.width || 1;
  48954. ground._height = options.height || 1;
  48955. ground._maxX = ground._width / 2;
  48956. ground._maxZ = ground._height / 2;
  48957. ground._minX = -ground._maxX;
  48958. ground._minZ = -ground._maxZ;
  48959. var vertexData = BABYLON.VertexData.CreateGround(options);
  48960. vertexData.applyToMesh(ground, options.updatable);
  48961. ground._setReady(true);
  48962. return ground;
  48963. };
  48964. /**
  48965. * Creates a tiled ground mesh.
  48966. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  48967. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  48968. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  48969. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  48970. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  48971. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  48972. * numbers of subdivisions on the ground width and height of each tile.
  48973. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48974. */
  48975. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  48976. var tiledGround = new BABYLON.Mesh(name, scene);
  48977. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  48978. vertexData.applyToMesh(tiledGround, options.updatable);
  48979. return tiledGround;
  48980. };
  48981. /**
  48982. * Creates a ground mesh from a height map.
  48983. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  48984. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  48985. * The parameter `url` sets the URL of the height map image resource.
  48986. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  48987. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  48988. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  48989. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  48990. * 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.
  48991. * 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).
  48992. * This function is passed the newly built mesh :
  48993. * ```javascript
  48994. * function(mesh) { // do things
  48995. * return; }
  48996. * ```
  48997. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48998. */
  48999. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  49000. var width = options.width || 10.0;
  49001. var height = options.height || 10.0;
  49002. var subdivisions = options.subdivisions || 1 | 0;
  49003. var minHeight = options.minHeight || 0.0;
  49004. var maxHeight = options.maxHeight || 1.0;
  49005. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  49006. var updatable = options.updatable;
  49007. var onReady = options.onReady;
  49008. var ground = new BABYLON.GroundMesh(name, scene);
  49009. ground._subdivisionsX = subdivisions;
  49010. ground._subdivisionsY = subdivisions;
  49011. ground._width = width;
  49012. ground._height = height;
  49013. ground._maxX = ground._width / 2.0;
  49014. ground._maxZ = ground._height / 2.0;
  49015. ground._minX = -ground._maxX;
  49016. ground._minZ = -ground._maxZ;
  49017. ground._setReady(false);
  49018. var onload = function (img) {
  49019. // Getting height map data
  49020. var canvas = document.createElement("canvas");
  49021. var context = canvas.getContext("2d");
  49022. if (!context) {
  49023. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  49024. }
  49025. var bufferWidth = img.width;
  49026. var bufferHeight = img.height;
  49027. canvas.width = bufferWidth;
  49028. canvas.height = bufferHeight;
  49029. context.drawImage(img, 0, 0);
  49030. // Create VertexData from map data
  49031. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  49032. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  49033. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  49034. width: width, height: height,
  49035. subdivisions: subdivisions,
  49036. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  49037. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  49038. });
  49039. vertexData.applyToMesh(ground, updatable);
  49040. ground._setReady(true);
  49041. //execute ready callback, if set
  49042. if (onReady) {
  49043. onReady(ground);
  49044. }
  49045. };
  49046. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  49047. return ground;
  49048. };
  49049. /**
  49050. * Creates a polygon mesh.
  49051. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  49052. * 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.
  49053. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49054. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49055. * 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).
  49056. * Remember you can only change the shape positions, not their number when updating a polygon.
  49057. */
  49058. MeshBuilder.CreatePolygon = function (name, options, scene) {
  49059. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49060. var shape = options.shape;
  49061. var holes = options.holes || [];
  49062. var depth = options.depth || 0;
  49063. var contours = [];
  49064. var hole = [];
  49065. for (var i = 0; i < shape.length; i++) {
  49066. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  49067. }
  49068. var epsilon = 0.00000001;
  49069. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  49070. contours.pop();
  49071. }
  49072. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  49073. for (var hNb = 0; hNb < holes.length; hNb++) {
  49074. hole = [];
  49075. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  49076. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  49077. }
  49078. polygonTriangulation.addHole(hole);
  49079. }
  49080. var polygon = polygonTriangulation.build(options.updatable, depth);
  49081. polygon._originalBuilderSideOrientation = options.sideOrientation;
  49082. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  49083. vertexData.applyToMesh(polygon, options.updatable);
  49084. return polygon;
  49085. };
  49086. ;
  49087. /**
  49088. * Creates an extruded polygon mesh, with depth in the Y direction.
  49089. * 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).
  49090. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  49091. */
  49092. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  49093. return MeshBuilder.CreatePolygon(name, options, scene);
  49094. };
  49095. ;
  49096. /**
  49097. * Creates a tube mesh.
  49098. * 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.
  49099. *
  49100. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  49101. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  49102. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  49103. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  49104. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  49105. * 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.
  49106. * It must return a radius value (positive float) :
  49107. * ```javascript
  49108. * var radiusFunction = function(i, distance) {
  49109. * // do things
  49110. * return radius; }
  49111. * ```
  49112. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  49113. * 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
  49114. * 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
  49115. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49116. * 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).
  49117. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49118. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49119. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49120. */
  49121. MeshBuilder.CreateTube = function (name, options, scene) {
  49122. var path = options.path;
  49123. var instance = options.instance;
  49124. var radius = 1.0;
  49125. if (instance) {
  49126. radius = instance.radius;
  49127. }
  49128. if (options.radius !== undefined) {
  49129. radius = options.radius;
  49130. }
  49131. ;
  49132. var tessellation = options.tessellation || 64 | 0;
  49133. var radiusFunction = options.radiusFunction || null;
  49134. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  49135. var invertUV = options.invertUV || false;
  49136. var updatable = options.updatable;
  49137. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49138. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  49139. // tube geometry
  49140. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  49141. var tangents = path3D.getTangents();
  49142. var normals = path3D.getNormals();
  49143. var distances = path3D.getDistances();
  49144. var pi2 = Math.PI * 2;
  49145. var step = pi2 / tessellation * arc;
  49146. var returnRadius = function () { return radius; };
  49147. var radiusFunctionFinal = radiusFunction || returnRadius;
  49148. var circlePath;
  49149. var rad;
  49150. var normal;
  49151. var rotated;
  49152. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  49153. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  49154. for (var i = 0; i < path.length; i++) {
  49155. rad = radiusFunctionFinal(i, distances[i]); // current radius
  49156. circlePath = Array(); // current circle array
  49157. normal = normals[i]; // current normal
  49158. for (var t = 0; t < tessellation; t++) {
  49159. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  49160. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  49161. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  49162. rotated.scaleInPlace(rad).addInPlace(path[i]);
  49163. circlePath[t] = rotated;
  49164. }
  49165. circlePaths[index] = circlePath;
  49166. index++;
  49167. }
  49168. // cap
  49169. var capPath = function (nbPoints, pathIndex) {
  49170. var pointCap = Array();
  49171. for (var i = 0; i < nbPoints; i++) {
  49172. pointCap.push(path[pathIndex]);
  49173. }
  49174. return pointCap;
  49175. };
  49176. switch (cap) {
  49177. case BABYLON.Mesh.NO_CAP:
  49178. break;
  49179. case BABYLON.Mesh.CAP_START:
  49180. circlePaths[0] = capPath(tessellation, 0);
  49181. circlePaths[1] = circlePaths[2].slice(0);
  49182. break;
  49183. case BABYLON.Mesh.CAP_END:
  49184. circlePaths[index] = circlePaths[index - 1].slice(0);
  49185. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  49186. break;
  49187. case BABYLON.Mesh.CAP_ALL:
  49188. circlePaths[0] = capPath(tessellation, 0);
  49189. circlePaths[1] = circlePaths[2].slice(0);
  49190. circlePaths[index] = circlePaths[index - 1].slice(0);
  49191. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  49192. break;
  49193. default:
  49194. break;
  49195. }
  49196. return circlePaths;
  49197. };
  49198. var path3D;
  49199. var pathArray;
  49200. if (instance) {
  49201. var arc = options.arc || instance.arc;
  49202. path3D = (instance.path3D).update(path);
  49203. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  49204. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  49205. instance.path3D = path3D;
  49206. instance.pathArray = pathArray;
  49207. instance.arc = arc;
  49208. instance.radius = radius;
  49209. return instance;
  49210. }
  49211. // tube creation
  49212. path3D = new BABYLON.Path3D(path);
  49213. var newPathArray = new Array();
  49214. cap = (cap < 0 || cap > 3) ? 0 : cap;
  49215. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  49216. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  49217. tube.pathArray = pathArray;
  49218. tube.path3D = path3D;
  49219. tube.tessellation = tessellation;
  49220. tube.cap = cap;
  49221. tube.arc = options.arc;
  49222. tube.radius = radius;
  49223. return tube;
  49224. };
  49225. /**
  49226. * Creates a polyhedron mesh.
  49227. *
  49228. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  49229. * 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
  49230. * to choose the wanted type.
  49231. * The parameter `size` (positive float, default 1) sets the polygon size.
  49232. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  49233. * 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`.
  49234. * 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
  49235. * 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)`).
  49236. * 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
  49237. * 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.
  49238. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49239. * 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).
  49240. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49241. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49242. */
  49243. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  49244. var polyhedron = new BABYLON.Mesh(name, scene);
  49245. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49246. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  49247. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  49248. vertexData.applyToMesh(polyhedron, options.updatable);
  49249. return polyhedron;
  49250. };
  49251. /**
  49252. * Creates a decal mesh.
  49253. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  49254. * 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.
  49255. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  49256. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  49257. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  49258. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  49259. */
  49260. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  49261. var indices = sourceMesh.getIndices();
  49262. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49263. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49264. var position = options.position || BABYLON.Vector3.Zero();
  49265. var normal = options.normal || BABYLON.Vector3.Up();
  49266. var size = options.size || BABYLON.Vector3.One();
  49267. var angle = options.angle || 0;
  49268. // Getting correct rotation
  49269. if (!normal) {
  49270. var target = new BABYLON.Vector3(0, 0, 1);
  49271. var camera = sourceMesh.getScene().activeCamera;
  49272. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  49273. normal = camera.globalPosition.subtract(cameraWorldTarget);
  49274. }
  49275. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  49276. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  49277. var pitch = Math.atan2(normal.y, len);
  49278. // Matrix
  49279. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  49280. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  49281. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  49282. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  49283. var vertexData = new BABYLON.VertexData();
  49284. vertexData.indices = [];
  49285. vertexData.positions = [];
  49286. vertexData.normals = [];
  49287. vertexData.uvs = [];
  49288. var currentVertexDataIndex = 0;
  49289. var extractDecalVector3 = function (indexId) {
  49290. var result = new BABYLON.PositionNormalVertex();
  49291. if (!indices || !positions || !normals) {
  49292. return result;
  49293. }
  49294. var vertexId = indices[indexId];
  49295. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  49296. // Send vector to decal local world
  49297. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  49298. // Get normal
  49299. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  49300. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  49301. return result;
  49302. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  49303. var clip = function (vertices, axis) {
  49304. if (vertices.length === 0) {
  49305. return vertices;
  49306. }
  49307. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  49308. var clipVertices = function (v0, v1) {
  49309. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  49310. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  49311. };
  49312. var result = new Array();
  49313. for (var index = 0; index < vertices.length; index += 3) {
  49314. var v1Out;
  49315. var v2Out;
  49316. var v3Out;
  49317. var total = 0;
  49318. var nV1 = null;
  49319. var nV2 = null;
  49320. var nV3 = null;
  49321. var nV4 = null;
  49322. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  49323. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  49324. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  49325. v1Out = d1 > 0;
  49326. v2Out = d2 > 0;
  49327. v3Out = d3 > 0;
  49328. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  49329. switch (total) {
  49330. case 0:
  49331. result.push(vertices[index]);
  49332. result.push(vertices[index + 1]);
  49333. result.push(vertices[index + 2]);
  49334. break;
  49335. case 1:
  49336. if (v1Out) {
  49337. nV1 = vertices[index + 1];
  49338. nV2 = vertices[index + 2];
  49339. nV3 = clipVertices(vertices[index], nV1);
  49340. nV4 = clipVertices(vertices[index], nV2);
  49341. }
  49342. if (v2Out) {
  49343. nV1 = vertices[index];
  49344. nV2 = vertices[index + 2];
  49345. nV3 = clipVertices(vertices[index + 1], nV1);
  49346. nV4 = clipVertices(vertices[index + 1], nV2);
  49347. result.push(nV3);
  49348. result.push(nV2.clone());
  49349. result.push(nV1.clone());
  49350. result.push(nV2.clone());
  49351. result.push(nV3.clone());
  49352. result.push(nV4);
  49353. break;
  49354. }
  49355. if (v3Out) {
  49356. nV1 = vertices[index];
  49357. nV2 = vertices[index + 1];
  49358. nV3 = clipVertices(vertices[index + 2], nV1);
  49359. nV4 = clipVertices(vertices[index + 2], nV2);
  49360. }
  49361. if (nV1 && nV2 && nV3 && nV4) {
  49362. result.push(nV1.clone());
  49363. result.push(nV2.clone());
  49364. result.push(nV3);
  49365. result.push(nV4);
  49366. result.push(nV3.clone());
  49367. result.push(nV2.clone());
  49368. }
  49369. break;
  49370. case 2:
  49371. if (!v1Out) {
  49372. nV1 = vertices[index].clone();
  49373. nV2 = clipVertices(nV1, vertices[index + 1]);
  49374. nV3 = clipVertices(nV1, vertices[index + 2]);
  49375. result.push(nV1);
  49376. result.push(nV2);
  49377. result.push(nV3);
  49378. }
  49379. if (!v2Out) {
  49380. nV1 = vertices[index + 1].clone();
  49381. nV2 = clipVertices(nV1, vertices[index + 2]);
  49382. nV3 = clipVertices(nV1, vertices[index]);
  49383. result.push(nV1);
  49384. result.push(nV2);
  49385. result.push(nV3);
  49386. }
  49387. if (!v3Out) {
  49388. nV1 = vertices[index + 2].clone();
  49389. nV2 = clipVertices(nV1, vertices[index]);
  49390. nV3 = clipVertices(nV1, vertices[index + 1]);
  49391. result.push(nV1);
  49392. result.push(nV2);
  49393. result.push(nV3);
  49394. }
  49395. break;
  49396. case 3:
  49397. break;
  49398. }
  49399. }
  49400. return result;
  49401. };
  49402. for (var index = 0; index < indices.length; index += 3) {
  49403. var faceVertices = new Array();
  49404. faceVertices.push(extractDecalVector3(index));
  49405. faceVertices.push(extractDecalVector3(index + 1));
  49406. faceVertices.push(extractDecalVector3(index + 2));
  49407. // Clip
  49408. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  49409. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  49410. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  49411. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  49412. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  49413. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  49414. if (faceVertices.length === 0) {
  49415. continue;
  49416. }
  49417. // Add UVs and get back to world
  49418. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  49419. var vertex = faceVertices[vIndex];
  49420. //TODO check for Int32Array | Uint32Array | Uint16Array
  49421. vertexData.indices.push(currentVertexDataIndex);
  49422. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  49423. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  49424. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  49425. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  49426. currentVertexDataIndex++;
  49427. }
  49428. }
  49429. // Return mesh
  49430. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  49431. vertexData.applyToMesh(decal);
  49432. decal.position = position.clone();
  49433. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  49434. return decal;
  49435. };
  49436. // Privates
  49437. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  49438. // extrusion geometry
  49439. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  49440. var tangents = path3D.getTangents();
  49441. var normals = path3D.getNormals();
  49442. var binormals = path3D.getBinormals();
  49443. var distances = path3D.getDistances();
  49444. var angle = 0;
  49445. var returnScale = function () { return scale !== null ? scale : 1; };
  49446. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  49447. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  49448. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  49449. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  49450. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  49451. for (var i = 0; i < curve.length; i++) {
  49452. var shapePath = new Array();
  49453. var angleStep = rotate(i, distances[i]);
  49454. var scaleRatio = scl(i, distances[i]);
  49455. for (var p = 0; p < shape.length; p++) {
  49456. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  49457. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  49458. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  49459. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  49460. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  49461. shapePath[p] = rotated;
  49462. }
  49463. shapePaths[index] = shapePath;
  49464. angle += angleStep;
  49465. index++;
  49466. }
  49467. // cap
  49468. var capPath = function (shapePath) {
  49469. var pointCap = Array();
  49470. var barycenter = BABYLON.Vector3.Zero();
  49471. var i;
  49472. for (i = 0; i < shapePath.length; i++) {
  49473. barycenter.addInPlace(shapePath[i]);
  49474. }
  49475. barycenter.scaleInPlace(1.0 / shapePath.length);
  49476. for (i = 0; i < shapePath.length; i++) {
  49477. pointCap.push(barycenter);
  49478. }
  49479. return pointCap;
  49480. };
  49481. switch (cap) {
  49482. case BABYLON.Mesh.NO_CAP:
  49483. break;
  49484. case BABYLON.Mesh.CAP_START:
  49485. shapePaths[0] = capPath(shapePaths[2]);
  49486. shapePaths[1] = shapePaths[2];
  49487. break;
  49488. case BABYLON.Mesh.CAP_END:
  49489. shapePaths[index] = shapePaths[index - 1];
  49490. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  49491. break;
  49492. case BABYLON.Mesh.CAP_ALL:
  49493. shapePaths[0] = capPath(shapePaths[2]);
  49494. shapePaths[1] = shapePaths[2];
  49495. shapePaths[index] = shapePaths[index - 1];
  49496. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  49497. break;
  49498. default:
  49499. break;
  49500. }
  49501. return shapePaths;
  49502. };
  49503. var path3D;
  49504. var pathArray;
  49505. if (instance) {
  49506. path3D = (instance.path3D).update(curve);
  49507. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  49508. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  49509. return instance;
  49510. }
  49511. // extruded shape creation
  49512. path3D = new BABYLON.Path3D(curve);
  49513. var newShapePaths = new Array();
  49514. cap = (cap < 0 || cap > 3) ? 0 : cap;
  49515. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  49516. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  49517. extrudedGeneric.pathArray = pathArray;
  49518. extrudedGeneric.path3D = path3D;
  49519. extrudedGeneric.cap = cap;
  49520. return extrudedGeneric;
  49521. };
  49522. return MeshBuilder;
  49523. }());
  49524. BABYLON.MeshBuilder = MeshBuilder;
  49525. })(BABYLON || (BABYLON = {}));
  49526. //# sourceMappingURL=babylon.meshBuilder.js.map
  49527. var BABYLON;
  49528. (function (BABYLON) {
  49529. var AudioEngine = /** @class */ (function () {
  49530. function AudioEngine() {
  49531. this._audioContext = null;
  49532. this._audioContextInitialized = false;
  49533. this.canUseWebAudio = false;
  49534. this.WarnedWebAudioUnsupported = false;
  49535. this.unlocked = false;
  49536. this.isMP3supported = false;
  49537. this.isOGGsupported = false;
  49538. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  49539. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  49540. this.canUseWebAudio = true;
  49541. }
  49542. var audioElem = document.createElement('audio');
  49543. try {
  49544. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  49545. this.isMP3supported = true;
  49546. }
  49547. }
  49548. catch (e) {
  49549. // protect error during capability check.
  49550. }
  49551. try {
  49552. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  49553. this.isOGGsupported = true;
  49554. }
  49555. }
  49556. catch (e) {
  49557. // protect error during capability check.
  49558. }
  49559. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  49560. this._unlockiOSaudio();
  49561. }
  49562. else {
  49563. this.unlocked = true;
  49564. }
  49565. }
  49566. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  49567. get: function () {
  49568. if (!this._audioContextInitialized) {
  49569. this._initializeAudioContext();
  49570. }
  49571. return this._audioContext;
  49572. },
  49573. enumerable: true,
  49574. configurable: true
  49575. });
  49576. AudioEngine.prototype._unlockiOSaudio = function () {
  49577. var _this = this;
  49578. var unlockaudio = function () {
  49579. if (!_this.audioContext) {
  49580. return;
  49581. }
  49582. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  49583. var source = _this.audioContext.createBufferSource();
  49584. source.buffer = buffer;
  49585. source.connect(_this.audioContext.destination);
  49586. source.start(0);
  49587. setTimeout(function () {
  49588. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  49589. _this.unlocked = true;
  49590. window.removeEventListener('touchend', unlockaudio, false);
  49591. if (_this.onAudioUnlocked) {
  49592. _this.onAudioUnlocked();
  49593. }
  49594. }
  49595. }, 0);
  49596. };
  49597. window.addEventListener('touchend', unlockaudio, false);
  49598. };
  49599. AudioEngine.prototype._initializeAudioContext = function () {
  49600. try {
  49601. if (this.canUseWebAudio) {
  49602. this._audioContext = new AudioContext();
  49603. // create a global volume gain node
  49604. this.masterGain = this._audioContext.createGain();
  49605. this.masterGain.gain.value = 1;
  49606. this.masterGain.connect(this._audioContext.destination);
  49607. this._audioContextInitialized = true;
  49608. }
  49609. }
  49610. catch (e) {
  49611. this.canUseWebAudio = false;
  49612. BABYLON.Tools.Error("Web Audio: " + e.message);
  49613. }
  49614. };
  49615. AudioEngine.prototype.dispose = function () {
  49616. if (this.canUseWebAudio && this._audioContextInitialized) {
  49617. if (this._connectedAnalyser && this._audioContext) {
  49618. this._connectedAnalyser.stopDebugCanvas();
  49619. this._connectedAnalyser.dispose();
  49620. this.masterGain.disconnect();
  49621. this.masterGain.connect(this._audioContext.destination);
  49622. this._connectedAnalyser = null;
  49623. }
  49624. this.masterGain.gain.value = 1;
  49625. }
  49626. this.WarnedWebAudioUnsupported = false;
  49627. };
  49628. AudioEngine.prototype.getGlobalVolume = function () {
  49629. if (this.canUseWebAudio && this._audioContextInitialized) {
  49630. return this.masterGain.gain.value;
  49631. }
  49632. else {
  49633. return -1;
  49634. }
  49635. };
  49636. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  49637. if (this.canUseWebAudio && this._audioContextInitialized) {
  49638. this.masterGain.gain.value = newVolume;
  49639. }
  49640. };
  49641. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  49642. if (this._connectedAnalyser) {
  49643. this._connectedAnalyser.stopDebugCanvas();
  49644. }
  49645. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  49646. this._connectedAnalyser = analyser;
  49647. this.masterGain.disconnect();
  49648. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  49649. }
  49650. };
  49651. return AudioEngine;
  49652. }());
  49653. BABYLON.AudioEngine = AudioEngine;
  49654. })(BABYLON || (BABYLON = {}));
  49655. //# sourceMappingURL=babylon.audioEngine.js.map
  49656. var BABYLON;
  49657. (function (BABYLON) {
  49658. var Sound = /** @class */ (function () {
  49659. /**
  49660. * Create a sound and attach it to a scene
  49661. * @param name Name of your sound
  49662. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  49663. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  49664. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  49665. */
  49666. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  49667. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  49668. var _this = this;
  49669. this.autoplay = false;
  49670. this.loop = false;
  49671. this.useCustomAttenuation = false;
  49672. this.spatialSound = false;
  49673. this.refDistance = 1;
  49674. this.rolloffFactor = 1;
  49675. this.maxDistance = 100;
  49676. this.distanceModel = "linear";
  49677. this._panningModel = "equalpower";
  49678. this._playbackRate = 1;
  49679. this._streaming = false;
  49680. this._startTime = 0;
  49681. this._startOffset = 0;
  49682. this._position = BABYLON.Vector3.Zero();
  49683. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  49684. this._volume = 1;
  49685. this._isReadyToPlay = false;
  49686. this.isPlaying = false;
  49687. this.isPaused = false;
  49688. this._isDirectional = false;
  49689. // Used if you'd like to create a directional sound.
  49690. // If not set, the sound will be omnidirectional
  49691. this._coneInnerAngle = 360;
  49692. this._coneOuterAngle = 360;
  49693. this._coneOuterGain = 0;
  49694. this._isOutputConnected = false;
  49695. this._urlType = "Unknown";
  49696. this.name = name;
  49697. this._scene = scene;
  49698. this._readyToPlayCallback = readyToPlayCallback;
  49699. // Default custom attenuation function is a linear attenuation
  49700. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  49701. if (currentDistance < maxDistance) {
  49702. return currentVolume * (1 - currentDistance / maxDistance);
  49703. }
  49704. else {
  49705. return 0;
  49706. }
  49707. };
  49708. if (options) {
  49709. this.autoplay = options.autoplay || false;
  49710. this.loop = options.loop || false;
  49711. // if volume === 0, we need another way to check this option
  49712. if (options.volume !== undefined) {
  49713. this._volume = options.volume;
  49714. }
  49715. this.spatialSound = options.spatialSound || false;
  49716. this.maxDistance = options.maxDistance || 100;
  49717. this.useCustomAttenuation = options.useCustomAttenuation || false;
  49718. this.rolloffFactor = options.rolloffFactor || 1;
  49719. this.refDistance = options.refDistance || 1;
  49720. this.distanceModel = options.distanceModel || "linear";
  49721. this._playbackRate = options.playbackRate || 1;
  49722. this._streaming = options.streaming || false;
  49723. }
  49724. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  49725. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  49726. this._soundGain.gain.value = this._volume;
  49727. this._inputAudioNode = this._soundGain;
  49728. this._ouputAudioNode = this._soundGain;
  49729. if (this.spatialSound) {
  49730. this._createSpatialParameters();
  49731. }
  49732. this._scene.mainSoundTrack.AddSound(this);
  49733. var validParameter = true;
  49734. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  49735. if (urlOrArrayBuffer) {
  49736. if (typeof (urlOrArrayBuffer) === "string")
  49737. this._urlType = "String";
  49738. if (Array.isArray(urlOrArrayBuffer))
  49739. this._urlType = "Array";
  49740. if (urlOrArrayBuffer instanceof ArrayBuffer)
  49741. this._urlType = "ArrayBuffer";
  49742. var urls = [];
  49743. var codecSupportedFound = false;
  49744. switch (this._urlType) {
  49745. case "ArrayBuffer":
  49746. if (urlOrArrayBuffer.byteLength > 0) {
  49747. codecSupportedFound = true;
  49748. this._soundLoaded(urlOrArrayBuffer);
  49749. }
  49750. break;
  49751. case "String":
  49752. urls.push(urlOrArrayBuffer);
  49753. case "Array":
  49754. if (urls.length === 0)
  49755. urls = urlOrArrayBuffer;
  49756. // If we found a supported format, we load it immediately and stop the loop
  49757. for (var i = 0; i < urls.length; i++) {
  49758. var url = urls[i];
  49759. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  49760. codecSupportedFound = true;
  49761. }
  49762. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  49763. codecSupportedFound = true;
  49764. }
  49765. if (url.indexOf(".wav", url.length - 4) !== -1) {
  49766. codecSupportedFound = true;
  49767. }
  49768. if (url.indexOf("blob:") !== -1) {
  49769. codecSupportedFound = true;
  49770. }
  49771. if (codecSupportedFound) {
  49772. // Loading sound using XHR2
  49773. if (!this._streaming) {
  49774. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, undefined, this._scene.database, true);
  49775. }
  49776. else {
  49777. this._htmlAudioElement = new Audio(url);
  49778. this._htmlAudioElement.controls = false;
  49779. this._htmlAudioElement.loop = this.loop;
  49780. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  49781. this._htmlAudioElement.preload = "auto";
  49782. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  49783. _this._isReadyToPlay = true;
  49784. if (_this.autoplay) {
  49785. _this.play();
  49786. }
  49787. if (_this._readyToPlayCallback) {
  49788. _this._readyToPlayCallback();
  49789. }
  49790. });
  49791. document.body.appendChild(this._htmlAudioElement);
  49792. }
  49793. break;
  49794. }
  49795. }
  49796. break;
  49797. default:
  49798. validParameter = false;
  49799. break;
  49800. }
  49801. if (!validParameter) {
  49802. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  49803. }
  49804. else {
  49805. if (!codecSupportedFound) {
  49806. this._isReadyToPlay = true;
  49807. // Simulating a ready to play event to avoid breaking code path
  49808. if (this._readyToPlayCallback) {
  49809. window.setTimeout(function () {
  49810. if (_this._readyToPlayCallback) {
  49811. _this._readyToPlayCallback();
  49812. }
  49813. }, 1000);
  49814. }
  49815. }
  49816. }
  49817. }
  49818. }
  49819. else {
  49820. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  49821. this._scene.mainSoundTrack.AddSound(this);
  49822. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  49823. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  49824. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  49825. }
  49826. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  49827. if (this._readyToPlayCallback) {
  49828. window.setTimeout(function () {
  49829. if (_this._readyToPlayCallback) {
  49830. _this._readyToPlayCallback();
  49831. }
  49832. }, 1000);
  49833. }
  49834. }
  49835. }
  49836. Sound.prototype.dispose = function () {
  49837. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  49838. if (this.isPlaying) {
  49839. this.stop();
  49840. }
  49841. this._isReadyToPlay = false;
  49842. if (this.soundTrackId === -1) {
  49843. this._scene.mainSoundTrack.RemoveSound(this);
  49844. }
  49845. else {
  49846. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  49847. }
  49848. if (this._soundGain) {
  49849. this._soundGain.disconnect();
  49850. this._soundGain = null;
  49851. }
  49852. if (this._soundPanner) {
  49853. this._soundPanner.disconnect();
  49854. this._soundPanner = null;
  49855. }
  49856. if (this._soundSource) {
  49857. this._soundSource.disconnect();
  49858. this._soundSource = null;
  49859. }
  49860. this._audioBuffer = null;
  49861. if (this._htmlAudioElement) {
  49862. this._htmlAudioElement.pause();
  49863. this._htmlAudioElement.src = "";
  49864. document.body.removeChild(this._htmlAudioElement);
  49865. }
  49866. if (this._connectedMesh && this._registerFunc) {
  49867. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  49868. this._connectedMesh = null;
  49869. }
  49870. }
  49871. };
  49872. Sound.prototype.isReady = function () {
  49873. return this._isReadyToPlay;
  49874. };
  49875. Sound.prototype._soundLoaded = function (audioData) {
  49876. var _this = this;
  49877. if (!BABYLON.Engine.audioEngine.audioContext) {
  49878. return;
  49879. }
  49880. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  49881. _this._audioBuffer = buffer;
  49882. _this._isReadyToPlay = true;
  49883. if (_this.autoplay) {
  49884. _this.play();
  49885. }
  49886. if (_this._readyToPlayCallback) {
  49887. _this._readyToPlayCallback();
  49888. }
  49889. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  49890. };
  49891. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  49892. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49893. this._audioBuffer = audioBuffer;
  49894. this._isReadyToPlay = true;
  49895. }
  49896. };
  49897. Sound.prototype.updateOptions = function (options) {
  49898. if (options) {
  49899. this.loop = options.loop || this.loop;
  49900. this.maxDistance = options.maxDistance || this.maxDistance;
  49901. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  49902. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  49903. this.refDistance = options.refDistance || this.refDistance;
  49904. this.distanceModel = options.distanceModel || this.distanceModel;
  49905. this._playbackRate = options.playbackRate || this._playbackRate;
  49906. this._updateSpatialParameters();
  49907. if (this.isPlaying) {
  49908. if (this._streaming) {
  49909. this._htmlAudioElement.playbackRate = this._playbackRate;
  49910. }
  49911. else {
  49912. if (this._soundSource) {
  49913. this._soundSource.playbackRate.value = this._playbackRate;
  49914. }
  49915. }
  49916. }
  49917. }
  49918. };
  49919. Sound.prototype._createSpatialParameters = function () {
  49920. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  49921. if (this._scene.headphone) {
  49922. this._panningModel = "HRTF";
  49923. }
  49924. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  49925. this._updateSpatialParameters();
  49926. this._soundPanner.connect(this._ouputAudioNode);
  49927. this._inputAudioNode = this._soundPanner;
  49928. }
  49929. };
  49930. Sound.prototype._updateSpatialParameters = function () {
  49931. if (this.spatialSound && this._soundPanner) {
  49932. if (this.useCustomAttenuation) {
  49933. // Tricks to disable in a way embedded Web Audio attenuation
  49934. this._soundPanner.distanceModel = "linear";
  49935. this._soundPanner.maxDistance = Number.MAX_VALUE;
  49936. this._soundPanner.refDistance = 1;
  49937. this._soundPanner.rolloffFactor = 1;
  49938. this._soundPanner.panningModel = this._panningModel;
  49939. }
  49940. else {
  49941. this._soundPanner.distanceModel = this.distanceModel;
  49942. this._soundPanner.maxDistance = this.maxDistance;
  49943. this._soundPanner.refDistance = this.refDistance;
  49944. this._soundPanner.rolloffFactor = this.rolloffFactor;
  49945. this._soundPanner.panningModel = this._panningModel;
  49946. }
  49947. }
  49948. };
  49949. Sound.prototype.switchPanningModelToHRTF = function () {
  49950. this._panningModel = "HRTF";
  49951. this._switchPanningModel();
  49952. };
  49953. Sound.prototype.switchPanningModelToEqualPower = function () {
  49954. this._panningModel = "equalpower";
  49955. this._switchPanningModel();
  49956. };
  49957. Sound.prototype._switchPanningModel = function () {
  49958. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  49959. this._soundPanner.panningModel = this._panningModel;
  49960. }
  49961. };
  49962. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  49963. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49964. if (this._isOutputConnected) {
  49965. this._ouputAudioNode.disconnect();
  49966. }
  49967. this._ouputAudioNode.connect(soundTrackAudioNode);
  49968. this._isOutputConnected = true;
  49969. }
  49970. };
  49971. /**
  49972. * Transform this sound into a directional source
  49973. * @param coneInnerAngle Size of the inner cone in degree
  49974. * @param coneOuterAngle Size of the outer cone in degree
  49975. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  49976. */
  49977. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  49978. if (coneOuterAngle < coneInnerAngle) {
  49979. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  49980. return;
  49981. }
  49982. this._coneInnerAngle = coneInnerAngle;
  49983. this._coneOuterAngle = coneOuterAngle;
  49984. this._coneOuterGain = coneOuterGain;
  49985. this._isDirectional = true;
  49986. if (this.isPlaying && this.loop) {
  49987. this.stop();
  49988. this.play();
  49989. }
  49990. };
  49991. Sound.prototype.setPosition = function (newPosition) {
  49992. this._position = newPosition;
  49993. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  49994. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  49995. }
  49996. };
  49997. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  49998. this._localDirection = newLocalDirection;
  49999. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  50000. this._updateDirection();
  50001. }
  50002. };
  50003. Sound.prototype._updateDirection = function () {
  50004. if (!this._connectedMesh || !this._soundPanner) {
  50005. return;
  50006. }
  50007. var mat = this._connectedMesh.getWorldMatrix();
  50008. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  50009. direction.normalize();
  50010. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  50011. };
  50012. Sound.prototype.updateDistanceFromListener = function () {
  50013. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  50014. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  50015. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  50016. }
  50017. };
  50018. Sound.prototype.setAttenuationFunction = function (callback) {
  50019. this._customAttenuationFunction = callback;
  50020. };
  50021. /**
  50022. * Play the sound
  50023. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  50024. * @param offset (optional) Start the sound setting it at a specific time
  50025. */
  50026. Sound.prototype.play = function (time, offset) {
  50027. var _this = this;
  50028. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  50029. try {
  50030. if (this._startOffset < 0) {
  50031. time = -this._startOffset;
  50032. this._startOffset = 0;
  50033. }
  50034. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  50035. if (!this._soundSource || !this._streamingSource) {
  50036. if (this.spatialSound && this._soundPanner) {
  50037. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  50038. if (this._isDirectional) {
  50039. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  50040. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  50041. this._soundPanner.coneOuterGain = this._coneOuterGain;
  50042. if (this._connectedMesh) {
  50043. this._updateDirection();
  50044. }
  50045. else {
  50046. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  50047. }
  50048. }
  50049. }
  50050. }
  50051. if (this._streaming) {
  50052. if (!this._streamingSource) {
  50053. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  50054. this._htmlAudioElement.onended = function () { _this._onended(); };
  50055. this._htmlAudioElement.playbackRate = this._playbackRate;
  50056. }
  50057. this._streamingSource.disconnect();
  50058. this._streamingSource.connect(this._inputAudioNode);
  50059. this._htmlAudioElement.play();
  50060. }
  50061. else {
  50062. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  50063. this._soundSource.buffer = this._audioBuffer;
  50064. this._soundSource.connect(this._inputAudioNode);
  50065. this._soundSource.loop = this.loop;
  50066. this._soundSource.playbackRate.value = this._playbackRate;
  50067. this._soundSource.onended = function () { _this._onended(); };
  50068. if (this._soundSource.buffer) {
  50069. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  50070. }
  50071. }
  50072. this._startTime = startTime;
  50073. this.isPlaying = true;
  50074. this.isPaused = false;
  50075. }
  50076. catch (ex) {
  50077. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  50078. }
  50079. }
  50080. };
  50081. Sound.prototype._onended = function () {
  50082. this.isPlaying = false;
  50083. if (this.onended) {
  50084. this.onended();
  50085. }
  50086. };
  50087. /**
  50088. * Stop the sound
  50089. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  50090. */
  50091. Sound.prototype.stop = function (time) {
  50092. if (this.isPlaying) {
  50093. if (this._streaming) {
  50094. this._htmlAudioElement.pause();
  50095. // Test needed for Firefox or it will generate an Invalid State Error
  50096. if (this._htmlAudioElement.currentTime > 0) {
  50097. this._htmlAudioElement.currentTime = 0;
  50098. }
  50099. }
  50100. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  50101. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  50102. this._soundSource.stop(stopTime);
  50103. this._soundSource.onended = function () { };
  50104. if (!this.isPaused) {
  50105. this._startOffset = 0;
  50106. }
  50107. }
  50108. this.isPlaying = false;
  50109. }
  50110. };
  50111. Sound.prototype.pause = function () {
  50112. if (this.isPlaying) {
  50113. this.isPaused = true;
  50114. if (this._streaming) {
  50115. this._htmlAudioElement.pause();
  50116. }
  50117. else if (BABYLON.Engine.audioEngine.audioContext) {
  50118. this.stop(0);
  50119. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  50120. }
  50121. }
  50122. };
  50123. Sound.prototype.setVolume = function (newVolume, time) {
  50124. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  50125. if (time && BABYLON.Engine.audioEngine.audioContext) {
  50126. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  50127. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  50128. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  50129. }
  50130. else {
  50131. this._soundGain.gain.value = newVolume;
  50132. }
  50133. }
  50134. this._volume = newVolume;
  50135. };
  50136. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  50137. this._playbackRate = newPlaybackRate;
  50138. if (this.isPlaying) {
  50139. if (this._streaming) {
  50140. this._htmlAudioElement.playbackRate = this._playbackRate;
  50141. }
  50142. else if (this._soundSource) {
  50143. this._soundSource.playbackRate.value = this._playbackRate;
  50144. }
  50145. }
  50146. };
  50147. Sound.prototype.getVolume = function () {
  50148. return this._volume;
  50149. };
  50150. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  50151. var _this = this;
  50152. if (this._connectedMesh && this._registerFunc) {
  50153. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  50154. this._registerFunc = null;
  50155. }
  50156. this._connectedMesh = meshToConnectTo;
  50157. if (!this.spatialSound) {
  50158. this.spatialSound = true;
  50159. this._createSpatialParameters();
  50160. if (this.isPlaying && this.loop) {
  50161. this.stop();
  50162. this.play();
  50163. }
  50164. }
  50165. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  50166. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  50167. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  50168. };
  50169. Sound.prototype.detachFromMesh = function () {
  50170. if (this._connectedMesh && this._registerFunc) {
  50171. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  50172. this._registerFunc = null;
  50173. this._connectedMesh = null;
  50174. }
  50175. };
  50176. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  50177. if (!node.getBoundingInfo) {
  50178. return;
  50179. }
  50180. var mesh = node;
  50181. var boundingInfo = mesh.getBoundingInfo();
  50182. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  50183. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  50184. this._updateDirection();
  50185. }
  50186. };
  50187. Sound.prototype.clone = function () {
  50188. var _this = this;
  50189. if (!this._streaming) {
  50190. var setBufferAndRun = function () {
  50191. if (_this._isReadyToPlay) {
  50192. clonedSound._audioBuffer = _this.getAudioBuffer();
  50193. clonedSound._isReadyToPlay = true;
  50194. if (clonedSound.autoplay) {
  50195. clonedSound.play();
  50196. }
  50197. }
  50198. else {
  50199. window.setTimeout(setBufferAndRun, 300);
  50200. }
  50201. };
  50202. var currentOptions = {
  50203. autoplay: this.autoplay, loop: this.loop,
  50204. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  50205. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  50206. refDistance: this.refDistance, distanceModel: this.distanceModel
  50207. };
  50208. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  50209. if (this.useCustomAttenuation) {
  50210. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  50211. }
  50212. clonedSound.setPosition(this._position);
  50213. clonedSound.setPlaybackRate(this._playbackRate);
  50214. setBufferAndRun();
  50215. return clonedSound;
  50216. }
  50217. else {
  50218. return null;
  50219. }
  50220. };
  50221. Sound.prototype.getAudioBuffer = function () {
  50222. return this._audioBuffer;
  50223. };
  50224. Sound.prototype.serialize = function () {
  50225. var serializationObject = {
  50226. name: this.name,
  50227. url: this.name,
  50228. autoplay: this.autoplay,
  50229. loop: this.loop,
  50230. volume: this._volume,
  50231. spatialSound: this.spatialSound,
  50232. maxDistance: this.maxDistance,
  50233. rolloffFactor: this.rolloffFactor,
  50234. refDistance: this.refDistance,
  50235. distanceModel: this.distanceModel,
  50236. playbackRate: this._playbackRate,
  50237. panningModel: this._panningModel,
  50238. soundTrackId: this.soundTrackId
  50239. };
  50240. if (this.spatialSound) {
  50241. if (this._connectedMesh)
  50242. serializationObject.connectedMeshId = this._connectedMesh.id;
  50243. serializationObject.position = this._position.asArray();
  50244. serializationObject.refDistance = this.refDistance;
  50245. serializationObject.distanceModel = this.distanceModel;
  50246. serializationObject.isDirectional = this._isDirectional;
  50247. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  50248. serializationObject.coneInnerAngle = this._coneInnerAngle;
  50249. serializationObject.coneOuterAngle = this._coneOuterAngle;
  50250. serializationObject.coneOuterGain = this._coneOuterGain;
  50251. }
  50252. return serializationObject;
  50253. };
  50254. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  50255. var soundName = parsedSound.name;
  50256. var soundUrl;
  50257. if (parsedSound.url) {
  50258. soundUrl = rootUrl + parsedSound.url;
  50259. }
  50260. else {
  50261. soundUrl = rootUrl + soundName;
  50262. }
  50263. var options = {
  50264. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  50265. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  50266. rolloffFactor: parsedSound.rolloffFactor,
  50267. refDistance: parsedSound.refDistance,
  50268. distanceModel: parsedSound.distanceModel,
  50269. playbackRate: parsedSound.playbackRate
  50270. };
  50271. var newSound;
  50272. if (!sourceSound) {
  50273. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  50274. scene._addPendingData(newSound);
  50275. }
  50276. else {
  50277. var setBufferAndRun = function () {
  50278. if (sourceSound._isReadyToPlay) {
  50279. newSound._audioBuffer = sourceSound.getAudioBuffer();
  50280. newSound._isReadyToPlay = true;
  50281. if (newSound.autoplay) {
  50282. newSound.play();
  50283. }
  50284. }
  50285. else {
  50286. window.setTimeout(setBufferAndRun, 300);
  50287. }
  50288. };
  50289. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  50290. setBufferAndRun();
  50291. }
  50292. if (parsedSound.position) {
  50293. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  50294. newSound.setPosition(soundPosition);
  50295. }
  50296. if (parsedSound.isDirectional) {
  50297. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  50298. if (parsedSound.localDirectionToMesh) {
  50299. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  50300. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  50301. }
  50302. }
  50303. if (parsedSound.connectedMeshId) {
  50304. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  50305. if (connectedMesh) {
  50306. newSound.attachToMesh(connectedMesh);
  50307. }
  50308. }
  50309. return newSound;
  50310. };
  50311. return Sound;
  50312. }());
  50313. BABYLON.Sound = Sound;
  50314. })(BABYLON || (BABYLON = {}));
  50315. //# sourceMappingURL=babylon.sound.js.map
  50316. var BABYLON;
  50317. (function (BABYLON) {
  50318. var SoundTrack = /** @class */ (function () {
  50319. function SoundTrack(scene, options) {
  50320. this.id = -1;
  50321. this._isMainTrack = false;
  50322. this._isInitialized = false;
  50323. this._scene = scene;
  50324. this.soundCollection = new Array();
  50325. this._options = options;
  50326. if (!this._isMainTrack) {
  50327. this._scene.soundTracks.push(this);
  50328. this.id = this._scene.soundTracks.length - 1;
  50329. }
  50330. }
  50331. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  50332. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  50333. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  50334. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  50335. if (this._options) {
  50336. if (this._options.volume) {
  50337. this._outputAudioNode.gain.value = this._options.volume;
  50338. }
  50339. if (this._options.mainTrack) {
  50340. this._isMainTrack = this._options.mainTrack;
  50341. }
  50342. }
  50343. this._isInitialized = true;
  50344. }
  50345. };
  50346. SoundTrack.prototype.dispose = function () {
  50347. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  50348. if (this._connectedAnalyser) {
  50349. this._connectedAnalyser.stopDebugCanvas();
  50350. }
  50351. while (this.soundCollection.length) {
  50352. this.soundCollection[0].dispose();
  50353. }
  50354. if (this._outputAudioNode) {
  50355. this._outputAudioNode.disconnect();
  50356. }
  50357. this._outputAudioNode = null;
  50358. }
  50359. };
  50360. SoundTrack.prototype.AddSound = function (sound) {
  50361. if (!this._isInitialized) {
  50362. this._initializeSoundTrackAudioGraph();
  50363. }
  50364. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  50365. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  50366. }
  50367. if (sound.soundTrackId) {
  50368. if (sound.soundTrackId === -1) {
  50369. this._scene.mainSoundTrack.RemoveSound(sound);
  50370. }
  50371. else {
  50372. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  50373. }
  50374. }
  50375. this.soundCollection.push(sound);
  50376. sound.soundTrackId = this.id;
  50377. };
  50378. SoundTrack.prototype.RemoveSound = function (sound) {
  50379. var index = this.soundCollection.indexOf(sound);
  50380. if (index !== -1) {
  50381. this.soundCollection.splice(index, 1);
  50382. }
  50383. };
  50384. SoundTrack.prototype.setVolume = function (newVolume) {
  50385. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  50386. this._outputAudioNode.gain.value = newVolume;
  50387. }
  50388. };
  50389. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  50390. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  50391. for (var i = 0; i < this.soundCollection.length; i++) {
  50392. this.soundCollection[i].switchPanningModelToHRTF();
  50393. }
  50394. }
  50395. };
  50396. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  50397. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  50398. for (var i = 0; i < this.soundCollection.length; i++) {
  50399. this.soundCollection[i].switchPanningModelToEqualPower();
  50400. }
  50401. }
  50402. };
  50403. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  50404. if (this._connectedAnalyser) {
  50405. this._connectedAnalyser.stopDebugCanvas();
  50406. }
  50407. this._connectedAnalyser = analyser;
  50408. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  50409. this._outputAudioNode.disconnect();
  50410. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  50411. }
  50412. };
  50413. return SoundTrack;
  50414. }());
  50415. BABYLON.SoundTrack = SoundTrack;
  50416. })(BABYLON || (BABYLON = {}));
  50417. //# sourceMappingURL=babylon.soundtrack.js.map
  50418. var BABYLON;
  50419. (function (BABYLON) {
  50420. var Analyser = /** @class */ (function () {
  50421. function Analyser(scene) {
  50422. this.SMOOTHING = 0.75;
  50423. this.FFT_SIZE = 512;
  50424. this.BARGRAPHAMPLITUDE = 256;
  50425. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  50426. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  50427. this._scene = scene;
  50428. this._audioEngine = BABYLON.Engine.audioEngine;
  50429. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  50430. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  50431. this._webAudioAnalyser.minDecibels = -140;
  50432. this._webAudioAnalyser.maxDecibels = 0;
  50433. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  50434. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  50435. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  50436. }
  50437. }
  50438. Analyser.prototype.getFrequencyBinCount = function () {
  50439. if (this._audioEngine.canUseWebAudio) {
  50440. return this._webAudioAnalyser.frequencyBinCount;
  50441. }
  50442. else {
  50443. return 0;
  50444. }
  50445. };
  50446. Analyser.prototype.getByteFrequencyData = function () {
  50447. if (this._audioEngine.canUseWebAudio) {
  50448. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  50449. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  50450. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  50451. }
  50452. return this._byteFreqs;
  50453. };
  50454. Analyser.prototype.getByteTimeDomainData = function () {
  50455. if (this._audioEngine.canUseWebAudio) {
  50456. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  50457. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  50458. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  50459. }
  50460. return this._byteTime;
  50461. };
  50462. Analyser.prototype.getFloatFrequencyData = function () {
  50463. if (this._audioEngine.canUseWebAudio) {
  50464. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  50465. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  50466. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  50467. }
  50468. return this._floatFreqs;
  50469. };
  50470. Analyser.prototype.drawDebugCanvas = function () {
  50471. var _this = this;
  50472. if (this._audioEngine.canUseWebAudio) {
  50473. if (!this._debugCanvas) {
  50474. this._debugCanvas = document.createElement("canvas");
  50475. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  50476. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  50477. this._debugCanvas.style.position = "absolute";
  50478. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  50479. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  50480. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  50481. document.body.appendChild(this._debugCanvas);
  50482. this._registerFunc = function () {
  50483. _this.drawDebugCanvas();
  50484. };
  50485. this._scene.registerBeforeRender(this._registerFunc);
  50486. }
  50487. if (this._registerFunc && this._debugCanvasContext) {
  50488. var workingArray = this.getByteFrequencyData();
  50489. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  50490. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  50491. // Draw the frequency domain chart.
  50492. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  50493. var value = workingArray[i];
  50494. var percent = value / this.BARGRAPHAMPLITUDE;
  50495. var height = this.DEBUGCANVASSIZE.height * percent;
  50496. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  50497. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  50498. var hue = i / this.getFrequencyBinCount() * 360;
  50499. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  50500. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  50501. }
  50502. }
  50503. }
  50504. };
  50505. Analyser.prototype.stopDebugCanvas = function () {
  50506. if (this._debugCanvas) {
  50507. if (this._registerFunc) {
  50508. this._scene.unregisterBeforeRender(this._registerFunc);
  50509. this._registerFunc = null;
  50510. }
  50511. document.body.removeChild(this._debugCanvas);
  50512. this._debugCanvas = null;
  50513. this._debugCanvasContext = null;
  50514. }
  50515. };
  50516. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  50517. if (this._audioEngine.canUseWebAudio) {
  50518. inputAudioNode.connect(this._webAudioAnalyser);
  50519. this._webAudioAnalyser.connect(outputAudioNode);
  50520. }
  50521. };
  50522. Analyser.prototype.dispose = function () {
  50523. if (this._audioEngine.canUseWebAudio) {
  50524. this._webAudioAnalyser.disconnect();
  50525. }
  50526. };
  50527. return Analyser;
  50528. }());
  50529. BABYLON.Analyser = Analyser;
  50530. })(BABYLON || (BABYLON = {}));
  50531. //# sourceMappingURL=babylon.analyser.js.map
  50532. var BABYLON;
  50533. (function (BABYLON) {
  50534. var CubeTexture = /** @class */ (function (_super) {
  50535. __extends(CubeTexture, _super);
  50536. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  50537. if (extensions === void 0) { extensions = null; }
  50538. if (noMipmap === void 0) { noMipmap = false; }
  50539. if (files === void 0) { files = null; }
  50540. if (onLoad === void 0) { onLoad = null; }
  50541. if (onError === void 0) { onError = null; }
  50542. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  50543. if (prefiltered === void 0) { prefiltered = false; }
  50544. if (forcedExtension === void 0) { forcedExtension = null; }
  50545. var _this = _super.call(this, scene) || this;
  50546. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  50547. _this.name = rootUrl;
  50548. _this.url = rootUrl;
  50549. _this._noMipmap = noMipmap;
  50550. _this.hasAlpha = false;
  50551. _this._format = format;
  50552. _this._prefiltered = prefiltered;
  50553. _this.isCube = true;
  50554. _this._textureMatrix = BABYLON.Matrix.Identity();
  50555. if (prefiltered) {
  50556. _this.gammaSpace = false;
  50557. }
  50558. if (!rootUrl && !files) {
  50559. return _this;
  50560. }
  50561. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  50562. var lastDot = rootUrl.lastIndexOf(".");
  50563. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  50564. var isDDS = (extension === ".dds");
  50565. if (!files) {
  50566. if (!isDDS && !extensions) {
  50567. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  50568. }
  50569. files = [];
  50570. if (extensions) {
  50571. for (var index = 0; index < extensions.length; index++) {
  50572. files.push(rootUrl + extensions[index]);
  50573. }
  50574. }
  50575. }
  50576. _this._files = files;
  50577. if (!_this._texture) {
  50578. if (!scene.useDelayedTextureLoading) {
  50579. if (prefiltered) {
  50580. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  50581. }
  50582. else {
  50583. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  50584. }
  50585. }
  50586. else {
  50587. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  50588. }
  50589. }
  50590. else if (onLoad) {
  50591. if (_this._texture.isReady) {
  50592. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  50593. }
  50594. else {
  50595. _this._texture.onLoadedObservable.add(onLoad);
  50596. }
  50597. }
  50598. return _this;
  50599. }
  50600. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  50601. return new CubeTexture("", scene, null, noMipmap, files);
  50602. };
  50603. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  50604. if (forcedExtension === void 0) { forcedExtension = null; }
  50605. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  50606. };
  50607. // Methods
  50608. CubeTexture.prototype.delayLoad = function () {
  50609. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  50610. return;
  50611. }
  50612. var scene = this.getScene();
  50613. if (!scene) {
  50614. return;
  50615. }
  50616. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  50617. this._texture = this._getFromCache(this.url, this._noMipmap);
  50618. if (!this._texture) {
  50619. if (this._prefiltered) {
  50620. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  50621. }
  50622. else {
  50623. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  50624. }
  50625. }
  50626. };
  50627. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  50628. return this._textureMatrix;
  50629. };
  50630. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  50631. this._textureMatrix = value;
  50632. };
  50633. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  50634. var texture = BABYLON.SerializationHelper.Parse(function () {
  50635. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  50636. }, parsedTexture, scene);
  50637. // Animations
  50638. if (parsedTexture.animations) {
  50639. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  50640. var parsedAnimation = parsedTexture.animations[animationIndex];
  50641. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  50642. }
  50643. }
  50644. return texture;
  50645. };
  50646. CubeTexture.prototype.clone = function () {
  50647. var _this = this;
  50648. return BABYLON.SerializationHelper.Clone(function () {
  50649. var scene = _this.getScene();
  50650. if (!scene) {
  50651. return _this;
  50652. }
  50653. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  50654. }, this);
  50655. };
  50656. return CubeTexture;
  50657. }(BABYLON.BaseTexture));
  50658. BABYLON.CubeTexture = CubeTexture;
  50659. })(BABYLON || (BABYLON = {}));
  50660. //# sourceMappingURL=babylon.cubeTexture.js.map
  50661. var BABYLON;
  50662. (function (BABYLON) {
  50663. var RenderTargetTexture = /** @class */ (function (_super) {
  50664. __extends(RenderTargetTexture, _super);
  50665. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  50666. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  50667. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50668. if (isCube === void 0) { isCube = false; }
  50669. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50670. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  50671. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  50672. if (isMulti === void 0) { isMulti = false; }
  50673. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  50674. _this.isCube = isCube;
  50675. /**
  50676. * Use this list to define the list of mesh you want to render.
  50677. */
  50678. _this.renderList = new Array();
  50679. _this.renderParticles = true;
  50680. _this.renderSprites = false;
  50681. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  50682. _this.ignoreCameraViewport = false;
  50683. // Events
  50684. /**
  50685. * An event triggered when the texture is unbind.
  50686. * @type {BABYLON.Observable}
  50687. */
  50688. _this.onBeforeBindObservable = new BABYLON.Observable();
  50689. /**
  50690. * An event triggered when the texture is unbind.
  50691. * @type {BABYLON.Observable}
  50692. */
  50693. _this.onAfterUnbindObservable = new BABYLON.Observable();
  50694. /**
  50695. * An event triggered before rendering the texture
  50696. * @type {BABYLON.Observable}
  50697. */
  50698. _this.onBeforeRenderObservable = new BABYLON.Observable();
  50699. /**
  50700. * An event triggered after rendering the texture
  50701. * @type {BABYLON.Observable}
  50702. */
  50703. _this.onAfterRenderObservable = new BABYLON.Observable();
  50704. /**
  50705. * An event triggered after the texture clear
  50706. * @type {BABYLON.Observable}
  50707. */
  50708. _this.onClearObservable = new BABYLON.Observable();
  50709. _this._currentRefreshId = -1;
  50710. _this._refreshRate = 1;
  50711. _this._samples = 1;
  50712. scene = _this.getScene();
  50713. if (!scene) {
  50714. return _this;
  50715. }
  50716. _this._engine = scene.getEngine();
  50717. _this.name = name;
  50718. _this.isRenderTarget = true;
  50719. _this._initialSizeParameter = size;
  50720. _this._processSizeParameter(size);
  50721. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  50722. });
  50723. _this._generateMipMaps = generateMipMaps ? true : false;
  50724. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  50725. // Rendering groups
  50726. _this._renderingManager = new BABYLON.RenderingManager(scene);
  50727. if (isMulti) {
  50728. return _this;
  50729. }
  50730. _this._renderTargetOptions = {
  50731. generateMipMaps: generateMipMaps,
  50732. type: type,
  50733. samplingMode: samplingMode,
  50734. generateDepthBuffer: generateDepthBuffer,
  50735. generateStencilBuffer: generateStencilBuffer
  50736. };
  50737. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  50738. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50739. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50740. }
  50741. if (isCube) {
  50742. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  50743. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  50744. _this._textureMatrix = BABYLON.Matrix.Identity();
  50745. }
  50746. else {
  50747. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  50748. }
  50749. return _this;
  50750. }
  50751. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  50752. get: function () {
  50753. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  50754. },
  50755. enumerable: true,
  50756. configurable: true
  50757. });
  50758. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  50759. get: function () {
  50760. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  50761. },
  50762. enumerable: true,
  50763. configurable: true
  50764. });
  50765. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  50766. get: function () {
  50767. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  50768. },
  50769. enumerable: true,
  50770. configurable: true
  50771. });
  50772. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  50773. set: function (callback) {
  50774. if (this._onAfterUnbindObserver) {
  50775. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  50776. }
  50777. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  50778. },
  50779. enumerable: true,
  50780. configurable: true
  50781. });
  50782. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  50783. set: function (callback) {
  50784. if (this._onBeforeRenderObserver) {
  50785. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  50786. }
  50787. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  50788. },
  50789. enumerable: true,
  50790. configurable: true
  50791. });
  50792. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  50793. set: function (callback) {
  50794. if (this._onAfterRenderObserver) {
  50795. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  50796. }
  50797. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  50798. },
  50799. enumerable: true,
  50800. configurable: true
  50801. });
  50802. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  50803. set: function (callback) {
  50804. if (this._onClearObserver) {
  50805. this.onClearObservable.remove(this._onClearObserver);
  50806. }
  50807. this._onClearObserver = this.onClearObservable.add(callback);
  50808. },
  50809. enumerable: true,
  50810. configurable: true
  50811. });
  50812. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  50813. get: function () {
  50814. return this._renderTargetOptions;
  50815. },
  50816. enumerable: true,
  50817. configurable: true
  50818. });
  50819. RenderTargetTexture.prototype._onRatioRescale = function () {
  50820. if (this._sizeRatio) {
  50821. this.resize(this._initialSizeParameter);
  50822. }
  50823. };
  50824. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  50825. if (size.ratio) {
  50826. this._sizeRatio = size.ratio;
  50827. this._size = {
  50828. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  50829. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  50830. };
  50831. }
  50832. else {
  50833. this._size = size;
  50834. }
  50835. };
  50836. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  50837. get: function () {
  50838. return this._samples;
  50839. },
  50840. set: function (value) {
  50841. if (this._samples === value) {
  50842. return;
  50843. }
  50844. var scene = this.getScene();
  50845. if (!scene) {
  50846. return;
  50847. }
  50848. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  50849. },
  50850. enumerable: true,
  50851. configurable: true
  50852. });
  50853. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  50854. this._currentRefreshId = -1;
  50855. };
  50856. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  50857. get: function () {
  50858. return this._refreshRate;
  50859. },
  50860. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  50861. set: function (value) {
  50862. this._refreshRate = value;
  50863. this.resetRefreshCounter();
  50864. },
  50865. enumerable: true,
  50866. configurable: true
  50867. });
  50868. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  50869. if (!this._postProcessManager) {
  50870. var scene = this.getScene();
  50871. if (!scene) {
  50872. return;
  50873. }
  50874. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  50875. this._postProcesses = new Array();
  50876. }
  50877. this._postProcesses.push(postProcess);
  50878. this._postProcesses[0].autoClear = false;
  50879. };
  50880. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  50881. if (!this._postProcesses) {
  50882. return;
  50883. }
  50884. if (dispose) {
  50885. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  50886. var postProcess = _a[_i];
  50887. postProcess.dispose();
  50888. }
  50889. }
  50890. this._postProcesses = [];
  50891. };
  50892. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  50893. if (!this._postProcesses) {
  50894. return;
  50895. }
  50896. var index = this._postProcesses.indexOf(postProcess);
  50897. if (index === -1) {
  50898. return;
  50899. }
  50900. this._postProcesses.splice(index, 1);
  50901. if (this._postProcesses.length > 0) {
  50902. this._postProcesses[0].autoClear = false;
  50903. }
  50904. };
  50905. RenderTargetTexture.prototype._shouldRender = function () {
  50906. if (this._currentRefreshId === -1) {
  50907. this._currentRefreshId = 1;
  50908. return true;
  50909. }
  50910. if (this.refreshRate === this._currentRefreshId) {
  50911. this._currentRefreshId = 1;
  50912. return true;
  50913. }
  50914. this._currentRefreshId++;
  50915. return false;
  50916. };
  50917. RenderTargetTexture.prototype.getRenderSize = function () {
  50918. if (this._size.width) {
  50919. return this._size.width;
  50920. }
  50921. return this._size;
  50922. };
  50923. RenderTargetTexture.prototype.getRenderWidth = function () {
  50924. if (this._size.width) {
  50925. return this._size.width;
  50926. }
  50927. return this._size;
  50928. };
  50929. RenderTargetTexture.prototype.getRenderHeight = function () {
  50930. if (this._size.width) {
  50931. return this._size.height;
  50932. }
  50933. return this._size;
  50934. };
  50935. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  50936. get: function () {
  50937. return true;
  50938. },
  50939. enumerable: true,
  50940. configurable: true
  50941. });
  50942. RenderTargetTexture.prototype.scale = function (ratio) {
  50943. var newSize = this.getRenderSize() * ratio;
  50944. this.resize(newSize);
  50945. };
  50946. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  50947. if (this.isCube) {
  50948. return this._textureMatrix;
  50949. }
  50950. return _super.prototype.getReflectionTextureMatrix.call(this);
  50951. };
  50952. RenderTargetTexture.prototype.resize = function (size) {
  50953. this.releaseInternalTexture();
  50954. var scene = this.getScene();
  50955. if (!scene) {
  50956. return;
  50957. }
  50958. this._processSizeParameter(size);
  50959. if (this.isCube) {
  50960. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  50961. }
  50962. else {
  50963. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  50964. }
  50965. };
  50966. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  50967. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  50968. if (dumpForDebug === void 0) { dumpForDebug = false; }
  50969. var scene = this.getScene();
  50970. if (!scene) {
  50971. return;
  50972. }
  50973. var engine = scene.getEngine();
  50974. if (this.useCameraPostProcesses !== undefined) {
  50975. useCameraPostProcess = this.useCameraPostProcesses;
  50976. }
  50977. if (this._waitingRenderList) {
  50978. this.renderList = [];
  50979. for (var index = 0; index < this._waitingRenderList.length; index++) {
  50980. var id = this._waitingRenderList[index];
  50981. var mesh_1 = scene.getMeshByID(id);
  50982. if (mesh_1) {
  50983. this.renderList.push(mesh_1);
  50984. }
  50985. }
  50986. delete this._waitingRenderList;
  50987. }
  50988. // Is predicate defined?
  50989. if (this.renderListPredicate) {
  50990. if (this.renderList) {
  50991. this.renderList.splice(0); // Clear previous renderList
  50992. }
  50993. else {
  50994. this.renderList = [];
  50995. }
  50996. var scene = this.getScene();
  50997. if (!scene) {
  50998. return;
  50999. }
  51000. var sceneMeshes = scene.meshes;
  51001. for (var index = 0; index < sceneMeshes.length; index++) {
  51002. var mesh = sceneMeshes[index];
  51003. if (this.renderListPredicate(mesh)) {
  51004. this.renderList.push(mesh);
  51005. }
  51006. }
  51007. }
  51008. this.onBeforeBindObservable.notifyObservers(this);
  51009. // Set custom projection.
  51010. // Needs to be before binding to prevent changing the aspect ratio.
  51011. var camera;
  51012. if (this.activeCamera) {
  51013. camera = this.activeCamera;
  51014. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  51015. if (this.activeCamera !== scene.activeCamera) {
  51016. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  51017. }
  51018. }
  51019. else {
  51020. camera = scene.activeCamera;
  51021. if (camera) {
  51022. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  51023. }
  51024. }
  51025. // Prepare renderingManager
  51026. this._renderingManager.reset();
  51027. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  51028. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  51029. var sceneRenderId = scene.getRenderId();
  51030. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  51031. var mesh = currentRenderList[meshIndex];
  51032. if (mesh) {
  51033. if (!mesh.isReady()) {
  51034. // Reset _currentRefreshId
  51035. this.resetRefreshCounter();
  51036. continue;
  51037. }
  51038. mesh._preActivateForIntermediateRendering(sceneRenderId);
  51039. var isMasked = void 0;
  51040. if (!this.renderList && camera) {
  51041. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  51042. }
  51043. else {
  51044. isMasked = false;
  51045. }
  51046. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  51047. mesh._activate(sceneRenderId);
  51048. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  51049. var subMesh = mesh.subMeshes[subIndex];
  51050. scene._activeIndices.addCount(subMesh.indexCount, false);
  51051. this._renderingManager.dispatch(subMesh);
  51052. }
  51053. }
  51054. }
  51055. }
  51056. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  51057. var particleSystem = scene.particleSystems[particleIndex];
  51058. var emitter = particleSystem.emitter;
  51059. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  51060. continue;
  51061. }
  51062. if (currentRenderList.indexOf(emitter) >= 0) {
  51063. this._renderingManager.dispatchParticles(particleSystem);
  51064. }
  51065. }
  51066. if (this.isCube) {
  51067. for (var face = 0; face < 6; face++) {
  51068. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  51069. scene.incrementRenderId();
  51070. scene.resetCachedMaterial();
  51071. }
  51072. }
  51073. else {
  51074. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  51075. }
  51076. this.onAfterUnbindObservable.notifyObservers(this);
  51077. if (scene.activeCamera) {
  51078. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  51079. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  51080. }
  51081. engine.setViewport(scene.activeCamera.viewport);
  51082. }
  51083. scene.resetCachedMaterial();
  51084. };
  51085. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  51086. var minimum = 128;
  51087. var x = renderDimension * scale;
  51088. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  51089. // Ensure we don't exceed the render dimension (while staying POT)
  51090. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  51091. };
  51092. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  51093. var _this = this;
  51094. var scene = this.getScene();
  51095. if (!scene) {
  51096. return;
  51097. }
  51098. var engine = scene.getEngine();
  51099. if (!this._texture) {
  51100. return;
  51101. }
  51102. // Bind
  51103. if (this._postProcessManager) {
  51104. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  51105. }
  51106. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  51107. if (this._texture) {
  51108. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  51109. }
  51110. }
  51111. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  51112. // Clear
  51113. if (this.onClearObservable.hasObservers()) {
  51114. this.onClearObservable.notifyObservers(engine);
  51115. }
  51116. else {
  51117. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  51118. }
  51119. if (!this._doNotChangeAspectRatio) {
  51120. scene.updateTransformMatrix(true);
  51121. }
  51122. // Render
  51123. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  51124. if (this._postProcessManager) {
  51125. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  51126. }
  51127. else if (useCameraPostProcess) {
  51128. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  51129. }
  51130. if (!this._doNotChangeAspectRatio) {
  51131. scene.updateTransformMatrix(true);
  51132. }
  51133. // Dump ?
  51134. if (dumpForDebug) {
  51135. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  51136. }
  51137. // Unbind
  51138. if (!this.isCube || faceIndex === 5) {
  51139. if (this.isCube) {
  51140. if (faceIndex === 5) {
  51141. engine.generateMipMapsForCubemap(this._texture);
  51142. }
  51143. }
  51144. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  51145. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  51146. });
  51147. }
  51148. else {
  51149. this.onAfterRenderObservable.notifyObservers(faceIndex);
  51150. }
  51151. };
  51152. /**
  51153. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  51154. * This allowed control for front to back rendering or reversly depending of the special needs.
  51155. *
  51156. * @param renderingGroupId The rendering group id corresponding to its index
  51157. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  51158. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  51159. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  51160. */
  51161. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  51162. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  51163. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  51164. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  51165. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  51166. };
  51167. /**
  51168. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  51169. *
  51170. * @param renderingGroupId The rendering group id corresponding to its index
  51171. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  51172. */
  51173. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  51174. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  51175. };
  51176. RenderTargetTexture.prototype.clone = function () {
  51177. var textureSize = this.getSize();
  51178. 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);
  51179. // Base texture
  51180. newTexture.hasAlpha = this.hasAlpha;
  51181. newTexture.level = this.level;
  51182. // RenderTarget Texture
  51183. newTexture.coordinatesMode = this.coordinatesMode;
  51184. if (this.renderList) {
  51185. newTexture.renderList = this.renderList.slice(0);
  51186. }
  51187. return newTexture;
  51188. };
  51189. RenderTargetTexture.prototype.serialize = function () {
  51190. if (!this.name) {
  51191. return null;
  51192. }
  51193. var serializationObject = _super.prototype.serialize.call(this);
  51194. serializationObject.renderTargetSize = this.getRenderSize();
  51195. serializationObject.renderList = [];
  51196. if (this.renderList) {
  51197. for (var index = 0; index < this.renderList.length; index++) {
  51198. serializationObject.renderList.push(this.renderList[index].id);
  51199. }
  51200. }
  51201. return serializationObject;
  51202. };
  51203. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  51204. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  51205. var objBuffer = this.getInternalTexture();
  51206. var scene = this.getScene();
  51207. if (objBuffer && scene) {
  51208. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  51209. }
  51210. };
  51211. RenderTargetTexture.prototype.dispose = function () {
  51212. if (this._postProcessManager) {
  51213. this._postProcessManager.dispose();
  51214. this._postProcessManager = null;
  51215. }
  51216. this.clearPostProcesses(true);
  51217. if (this._resizeObserver) {
  51218. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  51219. this._resizeObserver = null;
  51220. }
  51221. this.renderList = null;
  51222. // Remove from custom render targets
  51223. var scene = this.getScene();
  51224. if (!scene) {
  51225. return;
  51226. }
  51227. var index = scene.customRenderTargets.indexOf(this);
  51228. if (index >= 0) {
  51229. scene.customRenderTargets.splice(index, 1);
  51230. }
  51231. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  51232. var camera = _a[_i];
  51233. index = camera.customRenderTargets.indexOf(this);
  51234. if (index >= 0) {
  51235. camera.customRenderTargets.splice(index, 1);
  51236. }
  51237. }
  51238. _super.prototype.dispose.call(this);
  51239. };
  51240. RenderTargetTexture.prototype._rebuild = function () {
  51241. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  51242. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  51243. }
  51244. if (this._postProcessManager) {
  51245. this._postProcessManager._rebuild();
  51246. }
  51247. };
  51248. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  51249. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  51250. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  51251. return RenderTargetTexture;
  51252. }(BABYLON.Texture));
  51253. BABYLON.RenderTargetTexture = RenderTargetTexture;
  51254. })(BABYLON || (BABYLON = {}));
  51255. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  51256. var BABYLON;
  51257. (function (BABYLON) {
  51258. ;
  51259. var MultiRenderTarget = /** @class */ (function (_super) {
  51260. __extends(MultiRenderTarget, _super);
  51261. function MultiRenderTarget(name, size, count, scene, options) {
  51262. var _this = this;
  51263. options = options || {};
  51264. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  51265. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  51266. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  51267. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  51268. _this._engine = scene.getEngine();
  51269. if (!_this.isSupported) {
  51270. _this.dispose();
  51271. return;
  51272. }
  51273. var types = [];
  51274. var samplingModes = [];
  51275. for (var i = 0; i < count; i++) {
  51276. if (options.types && options.types[i]) {
  51277. types.push(options.types[i]);
  51278. }
  51279. else {
  51280. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  51281. }
  51282. if (options.samplingModes && options.samplingModes[i]) {
  51283. samplingModes.push(options.samplingModes[i]);
  51284. }
  51285. else {
  51286. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51287. }
  51288. }
  51289. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  51290. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  51291. _this._size = size;
  51292. _this._multiRenderTargetOptions = {
  51293. samplingModes: samplingModes,
  51294. generateMipMaps: generateMipMaps,
  51295. generateDepthBuffer: generateDepthBuffer,
  51296. generateStencilBuffer: generateStencilBuffer,
  51297. generateDepthTexture: generateDepthTexture,
  51298. types: types,
  51299. textureCount: count
  51300. };
  51301. _this._createInternalTextures();
  51302. _this._createTextures();
  51303. return _this;
  51304. }
  51305. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  51306. get: function () {
  51307. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  51308. },
  51309. enumerable: true,
  51310. configurable: true
  51311. });
  51312. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  51313. get: function () {
  51314. return this._textures;
  51315. },
  51316. enumerable: true,
  51317. configurable: true
  51318. });
  51319. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  51320. get: function () {
  51321. return this._textures[this._textures.length - 1];
  51322. },
  51323. enumerable: true,
  51324. configurable: true
  51325. });
  51326. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  51327. set: function (wrap) {
  51328. if (this._textures) {
  51329. for (var i = 0; i < this._textures.length; i++) {
  51330. this._textures[i].wrapU = wrap;
  51331. }
  51332. }
  51333. },
  51334. enumerable: true,
  51335. configurable: true
  51336. });
  51337. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  51338. set: function (wrap) {
  51339. if (this._textures) {
  51340. for (var i = 0; i < this._textures.length; i++) {
  51341. this._textures[i].wrapV = wrap;
  51342. }
  51343. }
  51344. },
  51345. enumerable: true,
  51346. configurable: true
  51347. });
  51348. MultiRenderTarget.prototype._rebuild = function () {
  51349. this.releaseInternalTextures();
  51350. this._createInternalTextures();
  51351. for (var i = 0; i < this._internalTextures.length; i++) {
  51352. var texture = this._textures[i];
  51353. texture._texture = this._internalTextures[i];
  51354. }
  51355. // Keeps references to frame buffer and stencil/depth buffer
  51356. this._texture = this._internalTextures[0];
  51357. };
  51358. MultiRenderTarget.prototype._createInternalTextures = function () {
  51359. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  51360. };
  51361. MultiRenderTarget.prototype._createTextures = function () {
  51362. this._textures = [];
  51363. for (var i = 0; i < this._internalTextures.length; i++) {
  51364. var texture = new BABYLON.Texture(null, this.getScene());
  51365. texture._texture = this._internalTextures[i];
  51366. this._textures.push(texture);
  51367. }
  51368. // Keeps references to frame buffer and stencil/depth buffer
  51369. this._texture = this._internalTextures[0];
  51370. };
  51371. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  51372. get: function () {
  51373. return this._samples;
  51374. },
  51375. set: function (value) {
  51376. if (this._samples === value) {
  51377. return;
  51378. }
  51379. for (var i = 0; i < this._internalTextures.length; i++) {
  51380. this._samples = this._engine.updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  51381. }
  51382. },
  51383. enumerable: true,
  51384. configurable: true
  51385. });
  51386. MultiRenderTarget.prototype.resize = function (size) {
  51387. this.releaseInternalTextures();
  51388. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  51389. this._createInternalTextures();
  51390. };
  51391. MultiRenderTarget.prototype.dispose = function () {
  51392. this.releaseInternalTextures();
  51393. _super.prototype.dispose.call(this);
  51394. };
  51395. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  51396. if (!this._internalTextures) {
  51397. return;
  51398. }
  51399. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  51400. if (this._internalTextures[i] !== undefined) {
  51401. this._internalTextures[i].dispose();
  51402. this._internalTextures.splice(i, 1);
  51403. }
  51404. }
  51405. };
  51406. return MultiRenderTarget;
  51407. }(BABYLON.RenderTargetTexture));
  51408. BABYLON.MultiRenderTarget = MultiRenderTarget;
  51409. })(BABYLON || (BABYLON = {}));
  51410. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  51411. var BABYLON;
  51412. (function (BABYLON) {
  51413. var MirrorTexture = /** @class */ (function (_super) {
  51414. __extends(MirrorTexture, _super);
  51415. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  51416. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51417. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  51418. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  51419. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  51420. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  51421. _this._transformMatrix = BABYLON.Matrix.Zero();
  51422. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  51423. _this._adaptiveBlurKernel = 0;
  51424. _this._blurKernelX = 0;
  51425. _this._blurKernelY = 0;
  51426. _this._blurRatio = 1.0;
  51427. _this.ignoreCameraViewport = true;
  51428. _this.onBeforeRenderObservable.add(function () {
  51429. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  51430. _this._savedViewMatrix = scene.getViewMatrix();
  51431. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  51432. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  51433. scene.clipPlane = _this.mirrorPlane;
  51434. scene.getEngine().cullBackFaces = false;
  51435. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  51436. });
  51437. _this.onAfterRenderObservable.add(function () {
  51438. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  51439. scene.getEngine().cullBackFaces = true;
  51440. scene._mirroredCameraPosition = null;
  51441. delete scene.clipPlane;
  51442. });
  51443. return _this;
  51444. }
  51445. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  51446. get: function () {
  51447. return this._blurRatio;
  51448. },
  51449. set: function (value) {
  51450. if (this._blurRatio === value) {
  51451. return;
  51452. }
  51453. this._blurRatio = value;
  51454. this._preparePostProcesses();
  51455. },
  51456. enumerable: true,
  51457. configurable: true
  51458. });
  51459. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  51460. set: function (value) {
  51461. this._adaptiveBlurKernel = value;
  51462. this._autoComputeBlurKernel();
  51463. },
  51464. enumerable: true,
  51465. configurable: true
  51466. });
  51467. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  51468. set: function (value) {
  51469. this.blurKernelX = value;
  51470. this.blurKernelY = value;
  51471. },
  51472. enumerable: true,
  51473. configurable: true
  51474. });
  51475. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  51476. get: function () {
  51477. return this._blurKernelX;
  51478. },
  51479. set: function (value) {
  51480. if (this._blurKernelX === value) {
  51481. return;
  51482. }
  51483. this._blurKernelX = value;
  51484. this._preparePostProcesses();
  51485. },
  51486. enumerable: true,
  51487. configurable: true
  51488. });
  51489. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  51490. get: function () {
  51491. return this._blurKernelY;
  51492. },
  51493. set: function (value) {
  51494. if (this._blurKernelY === value) {
  51495. return;
  51496. }
  51497. this._blurKernelY = value;
  51498. this._preparePostProcesses();
  51499. },
  51500. enumerable: true,
  51501. configurable: true
  51502. });
  51503. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  51504. var engine = this.getScene().getEngine();
  51505. var dw = this.getRenderWidth() / engine.getRenderWidth();
  51506. var dh = this.getRenderHeight() / engine.getRenderHeight();
  51507. this.blurKernelX = this._adaptiveBlurKernel * dw;
  51508. this.blurKernelY = this._adaptiveBlurKernel * dh;
  51509. };
  51510. MirrorTexture.prototype._onRatioRescale = function () {
  51511. if (this._sizeRatio) {
  51512. this.resize(this._initialSizeParameter);
  51513. if (!this._adaptiveBlurKernel) {
  51514. this._preparePostProcesses();
  51515. }
  51516. }
  51517. if (this._adaptiveBlurKernel) {
  51518. this._autoComputeBlurKernel();
  51519. }
  51520. };
  51521. MirrorTexture.prototype._preparePostProcesses = function () {
  51522. this.clearPostProcesses(true);
  51523. if (this._blurKernelX && this._blurKernelY) {
  51524. var engine = this.getScene().getEngine();
  51525. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  51526. 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);
  51527. this._blurX.autoClear = false;
  51528. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  51529. this._blurX.outputTexture = this._texture;
  51530. }
  51531. else {
  51532. this._blurX.alwaysForcePOT = true;
  51533. }
  51534. 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);
  51535. this._blurY.autoClear = false;
  51536. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  51537. this.addPostProcess(this._blurX);
  51538. this.addPostProcess(this._blurY);
  51539. }
  51540. else {
  51541. if (this._blurY) {
  51542. this.removePostProcess(this._blurY);
  51543. this._blurY.dispose();
  51544. this._blurY = null;
  51545. }
  51546. if (this._blurX) {
  51547. this.removePostProcess(this._blurX);
  51548. this._blurX.dispose();
  51549. this._blurX = null;
  51550. }
  51551. }
  51552. };
  51553. MirrorTexture.prototype.clone = function () {
  51554. var scene = this.getScene();
  51555. if (!scene) {
  51556. return this;
  51557. }
  51558. var textureSize = this.getSize();
  51559. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  51560. // Base texture
  51561. newTexture.hasAlpha = this.hasAlpha;
  51562. newTexture.level = this.level;
  51563. // Mirror Texture
  51564. newTexture.mirrorPlane = this.mirrorPlane.clone();
  51565. if (this.renderList) {
  51566. newTexture.renderList = this.renderList.slice(0);
  51567. }
  51568. return newTexture;
  51569. };
  51570. MirrorTexture.prototype.serialize = function () {
  51571. if (!this.name) {
  51572. return null;
  51573. }
  51574. var serializationObject = _super.prototype.serialize.call(this);
  51575. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  51576. return serializationObject;
  51577. };
  51578. return MirrorTexture;
  51579. }(BABYLON.RenderTargetTexture));
  51580. BABYLON.MirrorTexture = MirrorTexture;
  51581. })(BABYLON || (BABYLON = {}));
  51582. //# sourceMappingURL=babylon.mirrorTexture.js.map
  51583. var BABYLON;
  51584. (function (BABYLON) {
  51585. /**
  51586. * Creates a refraction texture used by refraction channel of the standard material.
  51587. * @param name the texture name
  51588. * @param size size of the underlying texture
  51589. * @param scene root scene
  51590. */
  51591. var RefractionTexture = /** @class */ (function (_super) {
  51592. __extends(RefractionTexture, _super);
  51593. function RefractionTexture(name, size, scene, generateMipMaps) {
  51594. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  51595. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  51596. _this.depth = 2.0;
  51597. _this.onBeforeRenderObservable.add(function () {
  51598. scene.clipPlane = _this.refractionPlane;
  51599. });
  51600. _this.onAfterRenderObservable.add(function () {
  51601. delete scene.clipPlane;
  51602. });
  51603. return _this;
  51604. }
  51605. RefractionTexture.prototype.clone = function () {
  51606. var scene = this.getScene();
  51607. if (!scene) {
  51608. return this;
  51609. }
  51610. var textureSize = this.getSize();
  51611. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  51612. // Base texture
  51613. newTexture.hasAlpha = this.hasAlpha;
  51614. newTexture.level = this.level;
  51615. // Refraction Texture
  51616. newTexture.refractionPlane = this.refractionPlane.clone();
  51617. if (this.renderList) {
  51618. newTexture.renderList = this.renderList.slice(0);
  51619. }
  51620. newTexture.depth = this.depth;
  51621. return newTexture;
  51622. };
  51623. RefractionTexture.prototype.serialize = function () {
  51624. if (!this.name) {
  51625. return null;
  51626. }
  51627. var serializationObject = _super.prototype.serialize.call(this);
  51628. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  51629. serializationObject.depth = this.depth;
  51630. return serializationObject;
  51631. };
  51632. return RefractionTexture;
  51633. }(BABYLON.RenderTargetTexture));
  51634. BABYLON.RefractionTexture = RefractionTexture;
  51635. })(BABYLON || (BABYLON = {}));
  51636. //# sourceMappingURL=babylon.refractionTexture.js.map
  51637. var BABYLON;
  51638. (function (BABYLON) {
  51639. var DynamicTexture = /** @class */ (function (_super) {
  51640. __extends(DynamicTexture, _super);
  51641. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  51642. if (scene === void 0) { scene = null; }
  51643. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51644. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  51645. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  51646. _this.name = name;
  51647. _this._engine = _this.getScene().getEngine();
  51648. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51649. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51650. _this._generateMipMaps = generateMipMaps;
  51651. if (options.getContext) {
  51652. _this._canvas = options;
  51653. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  51654. }
  51655. else {
  51656. _this._canvas = document.createElement("canvas");
  51657. if (options.width) {
  51658. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  51659. }
  51660. else {
  51661. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  51662. }
  51663. }
  51664. var textureSize = _this.getSize();
  51665. _this._canvas.width = textureSize.width;
  51666. _this._canvas.height = textureSize.height;
  51667. _this._context = _this._canvas.getContext("2d");
  51668. return _this;
  51669. }
  51670. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  51671. get: function () {
  51672. return true;
  51673. },
  51674. enumerable: true,
  51675. configurable: true
  51676. });
  51677. DynamicTexture.prototype._recreate = function (textureSize) {
  51678. this._canvas.width = textureSize.width;
  51679. this._canvas.height = textureSize.height;
  51680. this.releaseInternalTexture();
  51681. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  51682. };
  51683. DynamicTexture.prototype.scale = function (ratio) {
  51684. var textureSize = this.getSize();
  51685. textureSize.width *= ratio;
  51686. textureSize.height *= ratio;
  51687. this._recreate(textureSize);
  51688. };
  51689. DynamicTexture.prototype.scaleTo = function (width, height) {
  51690. var textureSize = this.getSize();
  51691. textureSize.width = width;
  51692. textureSize.height = height;
  51693. this._recreate(textureSize);
  51694. };
  51695. DynamicTexture.prototype.getContext = function () {
  51696. return this._context;
  51697. };
  51698. DynamicTexture.prototype.clear = function () {
  51699. var size = this.getSize();
  51700. this._context.fillRect(0, 0, size.width, size.height);
  51701. };
  51702. DynamicTexture.prototype.update = function (invertY) {
  51703. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  51704. };
  51705. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  51706. if (update === void 0) { update = true; }
  51707. var size = this.getSize();
  51708. if (clearColor) {
  51709. this._context.fillStyle = clearColor;
  51710. this._context.fillRect(0, 0, size.width, size.height);
  51711. }
  51712. this._context.font = font;
  51713. if (x === null || x === undefined) {
  51714. var textSize = this._context.measureText(text);
  51715. x = (size.width - textSize.width) / 2;
  51716. }
  51717. if (y === null || y === undefined) {
  51718. var fontSize = parseInt((font.replace(/\D/g, '')));
  51719. ;
  51720. y = (size.height / 2) + (fontSize / 3.65);
  51721. }
  51722. this._context.fillStyle = color;
  51723. this._context.fillText(text, x, y);
  51724. if (update) {
  51725. this.update(invertY);
  51726. }
  51727. };
  51728. DynamicTexture.prototype.clone = function () {
  51729. var scene = this.getScene();
  51730. if (!scene) {
  51731. return this;
  51732. }
  51733. var textureSize = this.getSize();
  51734. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  51735. // Base texture
  51736. newTexture.hasAlpha = this.hasAlpha;
  51737. newTexture.level = this.level;
  51738. // Dynamic Texture
  51739. newTexture.wrapU = this.wrapU;
  51740. newTexture.wrapV = this.wrapV;
  51741. return newTexture;
  51742. };
  51743. DynamicTexture.prototype._rebuild = function () {
  51744. this.update();
  51745. };
  51746. return DynamicTexture;
  51747. }(BABYLON.Texture));
  51748. BABYLON.DynamicTexture = DynamicTexture;
  51749. })(BABYLON || (BABYLON = {}));
  51750. //# sourceMappingURL=babylon.dynamicTexture.js.map
  51751. var BABYLON;
  51752. (function (BABYLON) {
  51753. var VideoTexture = /** @class */ (function (_super) {
  51754. __extends(VideoTexture, _super);
  51755. /**
  51756. * Creates a video texture.
  51757. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  51758. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  51759. * @param {BABYLON.Scene} scene is obviously the current scene.
  51760. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  51761. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  51762. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  51763. */
  51764. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  51765. if (generateMipMaps === void 0) { generateMipMaps = false; }
  51766. if (invertY === void 0) { invertY = false; }
  51767. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51768. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  51769. _this._autoLaunch = true;
  51770. var urls = null;
  51771. _this.name = name;
  51772. if (urlsOrVideo instanceof HTMLVideoElement) {
  51773. _this.video = urlsOrVideo;
  51774. }
  51775. else {
  51776. urls = urlsOrVideo;
  51777. _this.video = document.createElement("video");
  51778. _this.video.autoplay = false;
  51779. _this.video.loop = true;
  51780. BABYLON.Tools.SetCorsBehavior(urls, _this.video);
  51781. }
  51782. _this._engine = _this.getScene().getEngine();
  51783. _this._generateMipMaps = generateMipMaps;
  51784. _this._samplingMode = samplingMode;
  51785. if (!_this._engine.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  51786. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  51787. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  51788. }
  51789. else {
  51790. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51791. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51792. _this._generateMipMaps = false;
  51793. }
  51794. if (urls) {
  51795. _this.video.addEventListener("canplay", function () {
  51796. if (_this._texture === undefined) {
  51797. _this._createTexture();
  51798. }
  51799. });
  51800. urls.forEach(function (url) {
  51801. var source = document.createElement("source");
  51802. source.src = url;
  51803. _this.video.appendChild(source);
  51804. });
  51805. }
  51806. else {
  51807. _this._createTexture();
  51808. }
  51809. _this._lastUpdate = BABYLON.Tools.Now;
  51810. return _this;
  51811. }
  51812. VideoTexture.prototype.__setTextureReady = function () {
  51813. if (this._texture) {
  51814. this._texture.isReady = true;
  51815. }
  51816. };
  51817. VideoTexture.prototype._createTexture = function () {
  51818. this._texture = this._engine.createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  51819. if (this._autoLaunch) {
  51820. this._autoLaunch = false;
  51821. this.video.play();
  51822. }
  51823. this._setTextureReady = this.__setTextureReady.bind(this);
  51824. this.video.addEventListener("playing", this._setTextureReady);
  51825. };
  51826. VideoTexture.prototype._rebuild = function () {
  51827. this.update();
  51828. };
  51829. VideoTexture.prototype.update = function () {
  51830. var now = BABYLON.Tools.Now;
  51831. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  51832. return false;
  51833. }
  51834. this._lastUpdate = now;
  51835. this._engine.updateVideoTexture(this._texture, this.video, this._invertY);
  51836. return true;
  51837. };
  51838. VideoTexture.prototype.dispose = function () {
  51839. _super.prototype.dispose.call(this);
  51840. this.video.removeEventListener("playing", this._setTextureReady);
  51841. };
  51842. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  51843. var video = document.createElement("video");
  51844. var constraintsDeviceId;
  51845. if (constraints && constraints.deviceId) {
  51846. constraintsDeviceId = {
  51847. exact: constraints.deviceId
  51848. };
  51849. }
  51850. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  51851. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  51852. if (navigator.getUserMedia) {
  51853. navigator.getUserMedia({
  51854. video: {
  51855. deviceId: constraintsDeviceId,
  51856. width: {
  51857. min: (constraints && constraints.minWidth) || 256,
  51858. max: (constraints && constraints.maxWidth) || 640
  51859. },
  51860. height: {
  51861. min: (constraints && constraints.minHeight) || 256,
  51862. max: (constraints && constraints.maxHeight) || 480
  51863. }
  51864. }
  51865. }, function (stream) {
  51866. if (video.mozSrcObject !== undefined) {
  51867. video.mozSrcObject = stream;
  51868. }
  51869. else {
  51870. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  51871. }
  51872. video.play();
  51873. if (onReady) {
  51874. onReady(new VideoTexture("video", video, scene, true, true));
  51875. }
  51876. }, function (e) {
  51877. BABYLON.Tools.Error(e.name);
  51878. });
  51879. }
  51880. };
  51881. return VideoTexture;
  51882. }(BABYLON.Texture));
  51883. BABYLON.VideoTexture = VideoTexture;
  51884. })(BABYLON || (BABYLON = {}));
  51885. //# sourceMappingURL=babylon.videoTexture.js.map
  51886. var BABYLON;
  51887. (function (BABYLON) {
  51888. var RawTexture = /** @class */ (function (_super) {
  51889. __extends(RawTexture, _super);
  51890. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  51891. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51892. if (invertY === void 0) { invertY = false; }
  51893. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51894. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51895. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  51896. _this.format = format;
  51897. _this._engine = scene.getEngine();
  51898. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  51899. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51900. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51901. return _this;
  51902. }
  51903. RawTexture.prototype.update = function (data) {
  51904. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  51905. };
  51906. // Statics
  51907. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51908. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51909. if (invertY === void 0) { invertY = false; }
  51910. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51911. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  51912. };
  51913. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51914. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51915. if (invertY === void 0) { invertY = false; }
  51916. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51917. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  51918. };
  51919. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51920. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51921. if (invertY === void 0) { invertY = false; }
  51922. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51923. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  51924. };
  51925. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  51926. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51927. if (invertY === void 0) { invertY = false; }
  51928. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51929. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51930. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  51931. };
  51932. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  51933. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51934. if (invertY === void 0) { invertY = false; }
  51935. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51936. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51937. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  51938. };
  51939. return RawTexture;
  51940. }(BABYLON.Texture));
  51941. BABYLON.RawTexture = RawTexture;
  51942. })(BABYLON || (BABYLON = {}));
  51943. //# sourceMappingURL=babylon.rawTexture.js.map
  51944. var BABYLON;
  51945. (function (BABYLON) {
  51946. var PostProcess = /** @class */ (function () {
  51947. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  51948. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  51949. if (defines === void 0) { defines = null; }
  51950. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51951. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  51952. if (blockCompilation === void 0) { blockCompilation = false; }
  51953. this.name = name;
  51954. this.width = -1;
  51955. this.height = -1;
  51956. this.autoClear = true;
  51957. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  51958. this.animations = new Array();
  51959. /*
  51960. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  51961. Can only be used on a single postprocess or on the last one of a chain.
  51962. */
  51963. this.enablePixelPerfectMode = false;
  51964. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  51965. this.alwaysForcePOT = false;
  51966. this.samples = 1;
  51967. this.adaptScaleToCurrentViewport = false;
  51968. this._reusable = false;
  51969. this._textures = new BABYLON.SmartArray(2);
  51970. this._currentRenderTextureInd = 0;
  51971. this._scaleRatio = new BABYLON.Vector2(1, 1);
  51972. this._texelSize = BABYLON.Vector2.Zero();
  51973. // Events
  51974. /**
  51975. * An event triggered when the postprocess is activated.
  51976. * @type {BABYLON.Observable}
  51977. */
  51978. this.onActivateObservable = new BABYLON.Observable();
  51979. /**
  51980. * An event triggered when the postprocess changes its size.
  51981. * @type {BABYLON.Observable}
  51982. */
  51983. this.onSizeChangedObservable = new BABYLON.Observable();
  51984. /**
  51985. * An event triggered when the postprocess applies its effect.
  51986. * @type {BABYLON.Observable}
  51987. */
  51988. this.onApplyObservable = new BABYLON.Observable();
  51989. /**
  51990. * An event triggered before rendering the postprocess
  51991. * @type {BABYLON.Observable}
  51992. */
  51993. this.onBeforeRenderObservable = new BABYLON.Observable();
  51994. /**
  51995. * An event triggered after rendering the postprocess
  51996. * @type {BABYLON.Observable}
  51997. */
  51998. this.onAfterRenderObservable = new BABYLON.Observable();
  51999. if (camera != null) {
  52000. this._camera = camera;
  52001. this._scene = camera.getScene();
  52002. camera.attachPostProcess(this);
  52003. this._engine = this._scene.getEngine();
  52004. this._scene.postProcesses.push(this);
  52005. }
  52006. else if (engine) {
  52007. this._engine = engine;
  52008. this._engine.postProcesses.push(this);
  52009. }
  52010. this._options = options;
  52011. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  52012. this._reusable = reusable || false;
  52013. this._textureType = textureType;
  52014. this._samplers = samplers || [];
  52015. this._samplers.push("textureSampler");
  52016. this._fragmentUrl = fragmentUrl;
  52017. this._vertexUrl = vertexUrl;
  52018. this._parameters = parameters || [];
  52019. this._parameters.push("scale");
  52020. this._indexParameters = indexParameters;
  52021. if (!blockCompilation) {
  52022. this.updateEffect(defines);
  52023. }
  52024. }
  52025. Object.defineProperty(PostProcess.prototype, "onActivate", {
  52026. set: function (callback) {
  52027. if (this._onActivateObserver) {
  52028. this.onActivateObservable.remove(this._onActivateObserver);
  52029. }
  52030. if (callback) {
  52031. this._onActivateObserver = this.onActivateObservable.add(callback);
  52032. }
  52033. },
  52034. enumerable: true,
  52035. configurable: true
  52036. });
  52037. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  52038. set: function (callback) {
  52039. if (this._onSizeChangedObserver) {
  52040. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  52041. }
  52042. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  52043. },
  52044. enumerable: true,
  52045. configurable: true
  52046. });
  52047. Object.defineProperty(PostProcess.prototype, "onApply", {
  52048. set: function (callback) {
  52049. if (this._onApplyObserver) {
  52050. this.onApplyObservable.remove(this._onApplyObserver);
  52051. }
  52052. this._onApplyObserver = this.onApplyObservable.add(callback);
  52053. },
  52054. enumerable: true,
  52055. configurable: true
  52056. });
  52057. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  52058. set: function (callback) {
  52059. if (this._onBeforeRenderObserver) {
  52060. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  52061. }
  52062. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  52063. },
  52064. enumerable: true,
  52065. configurable: true
  52066. });
  52067. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  52068. set: function (callback) {
  52069. if (this._onAfterRenderObserver) {
  52070. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  52071. }
  52072. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  52073. },
  52074. enumerable: true,
  52075. configurable: true
  52076. });
  52077. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  52078. get: function () {
  52079. return this._textures.data[this._currentRenderTextureInd];
  52080. },
  52081. set: function (value) {
  52082. this._forcedOutputTexture = value;
  52083. },
  52084. enumerable: true,
  52085. configurable: true
  52086. });
  52087. PostProcess.prototype.getCamera = function () {
  52088. return this._camera;
  52089. };
  52090. Object.defineProperty(PostProcess.prototype, "texelSize", {
  52091. get: function () {
  52092. if (this._shareOutputWithPostProcess) {
  52093. return this._shareOutputWithPostProcess.texelSize;
  52094. }
  52095. if (this._forcedOutputTexture) {
  52096. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  52097. }
  52098. return this._texelSize;
  52099. },
  52100. enumerable: true,
  52101. configurable: true
  52102. });
  52103. PostProcess.prototype.getEngine = function () {
  52104. return this._engine;
  52105. };
  52106. PostProcess.prototype.getEffect = function () {
  52107. return this._effect;
  52108. };
  52109. PostProcess.prototype.shareOutputWith = function (postProcess) {
  52110. this._disposeTextures();
  52111. this._shareOutputWithPostProcess = postProcess;
  52112. return this;
  52113. };
  52114. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  52115. if (defines === void 0) { defines = null; }
  52116. if (uniforms === void 0) { uniforms = null; }
  52117. if (samplers === void 0) { samplers = null; }
  52118. 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);
  52119. };
  52120. PostProcess.prototype.isReusable = function () {
  52121. return this._reusable;
  52122. };
  52123. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  52124. PostProcess.prototype.markTextureDirty = function () {
  52125. this.width = -1;
  52126. };
  52127. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  52128. var _this = this;
  52129. if (sourceTexture === void 0) { sourceTexture = null; }
  52130. camera = camera || this._camera;
  52131. var scene = camera.getScene();
  52132. var engine = scene.getEngine();
  52133. var maxSize = engine.getCaps().maxTextureSize;
  52134. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  52135. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  52136. var desiredWidth = (this._options.width || requiredWidth);
  52137. var desiredHeight = this._options.height || requiredHeight;
  52138. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  52139. if (this.adaptScaleToCurrentViewport) {
  52140. var currentViewport = engine.currentViewport;
  52141. if (currentViewport) {
  52142. desiredWidth *= currentViewport.width;
  52143. desiredHeight *= currentViewport.height;
  52144. }
  52145. }
  52146. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  52147. if (!this._options.width) {
  52148. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  52149. }
  52150. if (!this._options.height) {
  52151. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  52152. }
  52153. }
  52154. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  52155. if (this._textures.length > 0) {
  52156. for (var i = 0; i < this._textures.length; i++) {
  52157. this._engine._releaseTexture(this._textures.data[i]);
  52158. }
  52159. this._textures.reset();
  52160. }
  52161. this.width = desiredWidth;
  52162. this.height = desiredHeight;
  52163. var textureSize = { width: this.width, height: this.height };
  52164. var textureOptions = {
  52165. generateMipMaps: false,
  52166. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  52167. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  52168. samplingMode: this.renderTargetSamplingMode,
  52169. type: this._textureType
  52170. };
  52171. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  52172. if (this._reusable) {
  52173. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  52174. }
  52175. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  52176. this.onSizeChangedObservable.notifyObservers(this);
  52177. }
  52178. this._textures.forEach(function (texture) {
  52179. if (texture.samples !== _this.samples) {
  52180. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  52181. }
  52182. });
  52183. }
  52184. var target;
  52185. if (this._shareOutputWithPostProcess) {
  52186. target = this._shareOutputWithPostProcess.outputTexture;
  52187. }
  52188. else if (this._forcedOutputTexture) {
  52189. target = this._forcedOutputTexture;
  52190. this.width = this._forcedOutputTexture.width;
  52191. this.height = this._forcedOutputTexture.height;
  52192. }
  52193. else {
  52194. target = this.outputTexture;
  52195. }
  52196. if (this.enablePixelPerfectMode) {
  52197. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  52198. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  52199. }
  52200. else {
  52201. this._scaleRatio.copyFromFloats(1, 1);
  52202. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  52203. }
  52204. this.onActivateObservable.notifyObservers(camera);
  52205. // Clear
  52206. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  52207. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  52208. }
  52209. if (this._reusable) {
  52210. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  52211. }
  52212. };
  52213. Object.defineProperty(PostProcess.prototype, "isSupported", {
  52214. get: function () {
  52215. return this._effect.isSupported;
  52216. },
  52217. enumerable: true,
  52218. configurable: true
  52219. });
  52220. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  52221. get: function () {
  52222. if (this._shareOutputWithPostProcess) {
  52223. return this._shareOutputWithPostProcess.aspectRatio;
  52224. }
  52225. if (this._forcedOutputTexture) {
  52226. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  52227. }
  52228. return this.width / this.height;
  52229. },
  52230. enumerable: true,
  52231. configurable: true
  52232. });
  52233. PostProcess.prototype.apply = function () {
  52234. // Check
  52235. if (!this._effect || !this._effect.isReady())
  52236. return null;
  52237. // States
  52238. this._engine.enableEffect(this._effect);
  52239. this._engine.setState(false);
  52240. this._engine.setDepthBuffer(false);
  52241. this._engine.setDepthWrite(false);
  52242. // Alpha
  52243. this._engine.setAlphaMode(this.alphaMode);
  52244. if (this.alphaConstants) {
  52245. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  52246. }
  52247. // Texture
  52248. var source;
  52249. if (this._shareOutputWithPostProcess) {
  52250. source = this._shareOutputWithPostProcess.outputTexture;
  52251. }
  52252. else if (this._forcedOutputTexture) {
  52253. source = this._forcedOutputTexture;
  52254. }
  52255. else {
  52256. source = this.outputTexture;
  52257. }
  52258. this._effect._bindTexture("textureSampler", source);
  52259. // Parameters
  52260. this._effect.setVector2("scale", this._scaleRatio);
  52261. this.onApplyObservable.notifyObservers(this._effect);
  52262. return this._effect;
  52263. };
  52264. PostProcess.prototype._disposeTextures = function () {
  52265. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  52266. return;
  52267. }
  52268. if (this._textures.length > 0) {
  52269. for (var i = 0; i < this._textures.length; i++) {
  52270. this._engine._releaseTexture(this._textures.data[i]);
  52271. }
  52272. }
  52273. this._textures.dispose();
  52274. };
  52275. PostProcess.prototype.dispose = function (camera) {
  52276. camera = camera || this._camera;
  52277. this._disposeTextures();
  52278. if (this._scene) {
  52279. var index_1 = this._scene.postProcesses.indexOf(this);
  52280. if (index_1 !== -1) {
  52281. this._scene.postProcesses.splice(index_1, 1);
  52282. }
  52283. }
  52284. else {
  52285. var index_2 = this._engine.postProcesses.indexOf(this);
  52286. if (index_2 !== -1) {
  52287. this._engine.postProcesses.splice(index_2, 1);
  52288. }
  52289. }
  52290. if (!camera) {
  52291. return;
  52292. }
  52293. camera.detachPostProcess(this);
  52294. var index = camera._postProcesses.indexOf(this);
  52295. if (index === 0 && camera._postProcesses.length > 0) {
  52296. this._camera._postProcesses[0].markTextureDirty();
  52297. }
  52298. this.onActivateObservable.clear();
  52299. this.onAfterRenderObservable.clear();
  52300. this.onApplyObservable.clear();
  52301. this.onBeforeRenderObservable.clear();
  52302. this.onSizeChangedObservable.clear();
  52303. };
  52304. return PostProcess;
  52305. }());
  52306. BABYLON.PostProcess = PostProcess;
  52307. })(BABYLON || (BABYLON = {}));
  52308. //# sourceMappingURL=babylon.postProcess.js.map
  52309. var BABYLON;
  52310. (function (BABYLON) {
  52311. var PassPostProcess = /** @class */ (function (_super) {
  52312. __extends(PassPostProcess, _super);
  52313. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  52314. if (camera === void 0) { camera = null; }
  52315. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52316. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  52317. }
  52318. return PassPostProcess;
  52319. }(BABYLON.PostProcess));
  52320. BABYLON.PassPostProcess = PassPostProcess;
  52321. })(BABYLON || (BABYLON = {}));
  52322. //# sourceMappingURL=babylon.passPostProcess.js.map
  52323. var __assign = (this && this.__assign) || Object.assign || function(t) {
  52324. for (var s, i = 1, n = arguments.length; i < n; i++) {
  52325. s = arguments[i];
  52326. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  52327. t[p] = s[p];
  52328. }
  52329. return t;
  52330. };
  52331. var BABYLON;
  52332. (function (BABYLON) {
  52333. var ShadowGenerator = /** @class */ (function () {
  52334. /**
  52335. * Creates a ShadowGenerator object.
  52336. * A ShadowGenerator is the required tool to use the shadows.
  52337. * Each light casting shadows needs to use its own ShadowGenerator.
  52338. * Required parameters :
  52339. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  52340. * - `light`: the light object generating the shadows.
  52341. * - `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.
  52342. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  52343. */
  52344. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  52345. // Members
  52346. this._bias = 0.00005;
  52347. this._blurBoxOffset = 1;
  52348. this._blurScale = 2;
  52349. this._blurKernel = 1;
  52350. this._useKernelBlur = false;
  52351. this._filter = ShadowGenerator.FILTER_NONE;
  52352. this._darkness = 0;
  52353. this._transparencyShadow = false;
  52354. /**
  52355. * Controls the extent to which the shadows fade out at the edge of the frustum
  52356. * Used only by directionals and spots
  52357. */
  52358. this.frustumEdgeFalloff = 0;
  52359. this.forceBackFacesOnly = false;
  52360. this._lightDirection = BABYLON.Vector3.Zero();
  52361. this._viewMatrix = BABYLON.Matrix.Zero();
  52362. this._projectionMatrix = BABYLON.Matrix.Zero();
  52363. this._transformMatrix = BABYLON.Matrix.Zero();
  52364. this._currentFaceIndex = 0;
  52365. this._currentFaceIndexCache = 0;
  52366. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  52367. this._mapSize = mapSize;
  52368. this._light = light;
  52369. this._scene = light.getScene();
  52370. light._shadowGenerator = this;
  52371. // Texture type fallback from float to int if not supported.
  52372. var caps = this._scene.getEngine().getCaps();
  52373. if (!useFullFloatFirst) {
  52374. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  52375. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  52376. }
  52377. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  52378. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  52379. }
  52380. else {
  52381. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  52382. }
  52383. }
  52384. else {
  52385. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  52386. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  52387. }
  52388. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  52389. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  52390. }
  52391. else {
  52392. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  52393. }
  52394. }
  52395. this._initializeGenerator();
  52396. }
  52397. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  52398. // Static
  52399. get: function () {
  52400. return ShadowGenerator._FILTER_NONE;
  52401. },
  52402. enumerable: true,
  52403. configurable: true
  52404. });
  52405. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  52406. get: function () {
  52407. return ShadowGenerator._FILTER_POISSONSAMPLING;
  52408. },
  52409. enumerable: true,
  52410. configurable: true
  52411. });
  52412. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  52413. get: function () {
  52414. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  52415. },
  52416. enumerable: true,
  52417. configurable: true
  52418. });
  52419. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  52420. get: function () {
  52421. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  52422. },
  52423. enumerable: true,
  52424. configurable: true
  52425. });
  52426. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  52427. get: function () {
  52428. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  52429. },
  52430. enumerable: true,
  52431. configurable: true
  52432. });
  52433. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  52434. get: function () {
  52435. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  52436. },
  52437. enumerable: true,
  52438. configurable: true
  52439. });
  52440. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  52441. get: function () {
  52442. return this._bias;
  52443. },
  52444. set: function (bias) {
  52445. this._bias = bias;
  52446. },
  52447. enumerable: true,
  52448. configurable: true
  52449. });
  52450. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  52451. get: function () {
  52452. return this._blurBoxOffset;
  52453. },
  52454. set: function (value) {
  52455. if (this._blurBoxOffset === value) {
  52456. return;
  52457. }
  52458. this._blurBoxOffset = value;
  52459. this._disposeBlurPostProcesses();
  52460. },
  52461. enumerable: true,
  52462. configurable: true
  52463. });
  52464. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  52465. get: function () {
  52466. return this._blurScale;
  52467. },
  52468. set: function (value) {
  52469. if (this._blurScale === value) {
  52470. return;
  52471. }
  52472. this._blurScale = value;
  52473. this._disposeBlurPostProcesses();
  52474. },
  52475. enumerable: true,
  52476. configurable: true
  52477. });
  52478. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  52479. get: function () {
  52480. return this._blurKernel;
  52481. },
  52482. set: function (value) {
  52483. if (this._blurKernel === value) {
  52484. return;
  52485. }
  52486. this._blurKernel = value;
  52487. this._disposeBlurPostProcesses();
  52488. },
  52489. enumerable: true,
  52490. configurable: true
  52491. });
  52492. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  52493. get: function () {
  52494. return this._useKernelBlur;
  52495. },
  52496. set: function (value) {
  52497. if (this._useKernelBlur === value) {
  52498. return;
  52499. }
  52500. this._useKernelBlur = value;
  52501. this._disposeBlurPostProcesses();
  52502. },
  52503. enumerable: true,
  52504. configurable: true
  52505. });
  52506. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  52507. get: function () {
  52508. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  52509. },
  52510. set: function (value) {
  52511. this._depthScale = value;
  52512. },
  52513. enumerable: true,
  52514. configurable: true
  52515. });
  52516. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  52517. get: function () {
  52518. return this._filter;
  52519. },
  52520. set: function (value) {
  52521. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  52522. if (this._light.needCube()) {
  52523. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  52524. this.useExponentialShadowMap = true;
  52525. return;
  52526. }
  52527. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  52528. this.useCloseExponentialShadowMap = true;
  52529. return;
  52530. }
  52531. }
  52532. if (this._filter === value) {
  52533. return;
  52534. }
  52535. this._filter = value;
  52536. this._disposeBlurPostProcesses();
  52537. this._applyFilterValues();
  52538. this._light._markMeshesAsLightDirty();
  52539. },
  52540. enumerable: true,
  52541. configurable: true
  52542. });
  52543. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  52544. get: function () {
  52545. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  52546. },
  52547. set: function (value) {
  52548. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  52549. return;
  52550. }
  52551. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  52552. },
  52553. enumerable: true,
  52554. configurable: true
  52555. });
  52556. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  52557. get: function () {
  52558. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  52559. return this.useExponentialShadowMap;
  52560. },
  52561. set: function (value) {
  52562. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  52563. this.useExponentialShadowMap = value;
  52564. },
  52565. enumerable: true,
  52566. configurable: true
  52567. });
  52568. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  52569. get: function () {
  52570. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  52571. return this.useBlurExponentialShadowMap;
  52572. },
  52573. set: function (value) {
  52574. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  52575. this.useBlurExponentialShadowMap = value;
  52576. },
  52577. enumerable: true,
  52578. configurable: true
  52579. });
  52580. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  52581. get: function () {
  52582. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  52583. },
  52584. set: function (value) {
  52585. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  52586. return;
  52587. }
  52588. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  52589. },
  52590. enumerable: true,
  52591. configurable: true
  52592. });
  52593. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  52594. get: function () {
  52595. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  52596. },
  52597. set: function (value) {
  52598. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  52599. return;
  52600. }
  52601. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  52602. },
  52603. enumerable: true,
  52604. configurable: true
  52605. });
  52606. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  52607. get: function () {
  52608. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  52609. },
  52610. set: function (value) {
  52611. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  52612. return;
  52613. }
  52614. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  52615. },
  52616. enumerable: true,
  52617. configurable: true
  52618. });
  52619. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  52620. get: function () {
  52621. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  52622. },
  52623. set: function (value) {
  52624. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  52625. return;
  52626. }
  52627. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  52628. },
  52629. enumerable: true,
  52630. configurable: true
  52631. });
  52632. /**
  52633. * Returns the darkness value (float).
  52634. */
  52635. ShadowGenerator.prototype.getDarkness = function () {
  52636. return this._darkness;
  52637. };
  52638. /**
  52639. * Sets the ShadowGenerator darkness value (float <= 1.0).
  52640. * Returns the ShadowGenerator.
  52641. */
  52642. ShadowGenerator.prototype.setDarkness = function (darkness) {
  52643. if (darkness >= 1.0)
  52644. this._darkness = 1.0;
  52645. else if (darkness <= 0.0)
  52646. this._darkness = 0.0;
  52647. else
  52648. this._darkness = darkness;
  52649. return this;
  52650. };
  52651. /**
  52652. * Sets the ability to have transparent shadow (boolean).
  52653. * Returns the ShadowGenerator.
  52654. */
  52655. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  52656. this._transparencyShadow = hasShadow;
  52657. return this;
  52658. };
  52659. /**
  52660. * Returns a RenderTargetTexture object : the shadow map texture.
  52661. */
  52662. ShadowGenerator.prototype.getShadowMap = function () {
  52663. return this._shadowMap;
  52664. };
  52665. /**
  52666. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  52667. */
  52668. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  52669. if (this._shadowMap2) {
  52670. return this._shadowMap2;
  52671. }
  52672. return this._shadowMap;
  52673. };
  52674. /**
  52675. * Helper function to add a mesh and its descendants to the list of shadow casters
  52676. * @param mesh Mesh to add
  52677. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  52678. */
  52679. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  52680. if (includeDescendants === void 0) { includeDescendants = true; }
  52681. if (!this._shadowMap) {
  52682. return this;
  52683. }
  52684. if (!this._shadowMap.renderList) {
  52685. this._shadowMap.renderList = [];
  52686. }
  52687. this._shadowMap.renderList.push(mesh);
  52688. if (includeDescendants) {
  52689. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  52690. }
  52691. return this;
  52692. var _a;
  52693. };
  52694. /**
  52695. * Helper function to remove a mesh and its descendants from the list of shadow casters
  52696. * @param mesh Mesh to remove
  52697. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  52698. */
  52699. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  52700. if (includeDescendants === void 0) { includeDescendants = true; }
  52701. if (!this._shadowMap || !this._shadowMap.renderList) {
  52702. return this;
  52703. }
  52704. var index = this._shadowMap.renderList.indexOf(mesh);
  52705. if (index !== -1) {
  52706. this._shadowMap.renderList.splice(index, 1);
  52707. }
  52708. if (includeDescendants) {
  52709. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  52710. var child = _a[_i];
  52711. this.removeShadowCaster(child);
  52712. }
  52713. }
  52714. return this;
  52715. };
  52716. /**
  52717. * Returns the associated light object.
  52718. */
  52719. ShadowGenerator.prototype.getLight = function () {
  52720. return this._light;
  52721. };
  52722. ShadowGenerator.prototype._initializeGenerator = function () {
  52723. this._light._markMeshesAsLightDirty();
  52724. this._initializeShadowMap();
  52725. };
  52726. ShadowGenerator.prototype._initializeShadowMap = function () {
  52727. var _this = this;
  52728. // Render target
  52729. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  52730. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52731. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52732. this._shadowMap.anisotropicFilteringLevel = 1;
  52733. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52734. this._shadowMap.renderParticles = false;
  52735. this._shadowMap.ignoreCameraViewport = true;
  52736. // Record Face Index before render.
  52737. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  52738. _this._currentFaceIndex = faceIndex;
  52739. });
  52740. // Custom render function.
  52741. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  52742. // Blur if required afer render.
  52743. this._shadowMap.onAfterUnbindObservable.add(function () {
  52744. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  52745. return;
  52746. }
  52747. if (!_this._blurPostProcesses || !_this._blurPostProcesses.length) {
  52748. _this._initializeBlurRTTAndPostProcesses();
  52749. }
  52750. var shadowMap = _this.getShadowMapForRendering();
  52751. if (shadowMap) {
  52752. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  52753. }
  52754. });
  52755. // Clear according to the chosen filter.
  52756. this._shadowMap.onClearObservable.add(function (engine) {
  52757. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  52758. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  52759. }
  52760. else {
  52761. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  52762. }
  52763. });
  52764. };
  52765. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  52766. var _this = this;
  52767. var engine = this._scene.getEngine();
  52768. var targetSize = this._mapSize / this.blurScale;
  52769. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  52770. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  52771. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52772. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52773. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52774. }
  52775. if (this.useKernelBlur) {
  52776. 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);
  52777. this._kernelBlurXPostprocess.width = targetSize;
  52778. this._kernelBlurXPostprocess.height = targetSize;
  52779. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  52780. effect.setTexture("textureSampler", _this._shadowMap);
  52781. });
  52782. 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);
  52783. this._kernelBlurXPostprocess.autoClear = false;
  52784. this._kernelBlurYPostprocess.autoClear = false;
  52785. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  52786. this._kernelBlurXPostprocess.packedFloat = true;
  52787. this._kernelBlurYPostprocess.packedFloat = true;
  52788. }
  52789. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  52790. }
  52791. else {
  52792. 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);
  52793. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  52794. effect.setFloat2("screenSize", targetSize, targetSize);
  52795. effect.setTexture("textureSampler", _this._shadowMap);
  52796. });
  52797. this._boxBlurPostprocess.autoClear = false;
  52798. this._blurPostProcesses = [this._boxBlurPostprocess];
  52799. }
  52800. };
  52801. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  52802. var index;
  52803. var engine = this._scene.getEngine();
  52804. if (depthOnlySubMeshes.length) {
  52805. engine.setColorWrite(false);
  52806. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  52807. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  52808. }
  52809. engine.setColorWrite(true);
  52810. }
  52811. for (index = 0; index < opaqueSubMeshes.length; index++) {
  52812. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  52813. }
  52814. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  52815. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  52816. }
  52817. if (this._transparencyShadow) {
  52818. for (index = 0; index < transparentSubMeshes.length; index++) {
  52819. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  52820. }
  52821. }
  52822. };
  52823. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  52824. var _this = this;
  52825. var mesh = subMesh.getRenderingMesh();
  52826. var scene = this._scene;
  52827. var engine = scene.getEngine();
  52828. var material = subMesh.getMaterial();
  52829. if (!material) {
  52830. return;
  52831. }
  52832. // Culling
  52833. engine.setState(material.backFaceCulling);
  52834. // Managing instances
  52835. var batch = mesh._getInstancesRenderList(subMesh._id);
  52836. if (batch.mustReturn) {
  52837. return;
  52838. }
  52839. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  52840. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  52841. engine.enableEffect(this._effect);
  52842. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  52843. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  52844. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  52845. this._effect.setVector3("lightPosition", this.getLight().position);
  52846. if (scene.activeCamera) {
  52847. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  52848. }
  52849. // Alpha test
  52850. if (material && material.needAlphaTesting()) {
  52851. var alphaTexture = material.getAlphaTestTexture();
  52852. if (alphaTexture) {
  52853. this._effect.setTexture("diffuseSampler", alphaTexture);
  52854. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  52855. }
  52856. }
  52857. // Bones
  52858. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52859. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  52860. }
  52861. if (this.forceBackFacesOnly) {
  52862. engine.setState(true, 0, false, true);
  52863. }
  52864. // Draw
  52865. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  52866. if (this.forceBackFacesOnly) {
  52867. engine.setState(true, 0, false, false);
  52868. }
  52869. }
  52870. else {
  52871. // Need to reset refresh rate of the shadowMap
  52872. if (this._shadowMap) {
  52873. this._shadowMap.resetRefreshCounter();
  52874. }
  52875. }
  52876. };
  52877. ShadowGenerator.prototype._applyFilterValues = function () {
  52878. if (!this._shadowMap) {
  52879. return;
  52880. }
  52881. if (this.filter === ShadowGenerator.FILTER_NONE) {
  52882. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  52883. }
  52884. else {
  52885. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52886. }
  52887. };
  52888. /**
  52889. * Force shader compilation including textures ready check
  52890. */
  52891. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  52892. var _this = this;
  52893. var localOptions = __assign({ useInstances: false }, options);
  52894. var shadowMap = this.getShadowMap();
  52895. if (!shadowMap) {
  52896. if (onCompiled) {
  52897. onCompiled(this);
  52898. }
  52899. return;
  52900. }
  52901. var renderList = shadowMap.renderList;
  52902. if (!renderList) {
  52903. if (onCompiled) {
  52904. onCompiled(this);
  52905. }
  52906. return;
  52907. }
  52908. var subMeshes = new Array();
  52909. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  52910. var mesh = renderList_1[_i];
  52911. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  52912. }
  52913. if (subMeshes.length === 0) {
  52914. if (onCompiled) {
  52915. onCompiled(this);
  52916. }
  52917. return;
  52918. }
  52919. var currentIndex = 0;
  52920. var checkReady = function () {
  52921. if (!_this._scene || !_this._scene.getEngine()) {
  52922. return;
  52923. }
  52924. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  52925. currentIndex++;
  52926. if (currentIndex >= subMeshes.length) {
  52927. if (onCompiled) {
  52928. onCompiled(_this);
  52929. }
  52930. return;
  52931. }
  52932. }
  52933. setTimeout(checkReady, 16);
  52934. };
  52935. checkReady();
  52936. };
  52937. /**
  52938. * Boolean : true when the ShadowGenerator is finally computed.
  52939. */
  52940. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  52941. var defines = [];
  52942. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  52943. defines.push("#define FLOAT");
  52944. }
  52945. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  52946. defines.push("#define ESM");
  52947. }
  52948. var attribs = [BABYLON.VertexBuffer.PositionKind];
  52949. var mesh = subMesh.getMesh();
  52950. var material = subMesh.getMaterial();
  52951. // Alpha test
  52952. if (material && material.needAlphaTesting()) {
  52953. var alphaTexture = material.getAlphaTestTexture();
  52954. if (alphaTexture) {
  52955. defines.push("#define ALPHATEST");
  52956. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52957. attribs.push(BABYLON.VertexBuffer.UVKind);
  52958. defines.push("#define UV1");
  52959. }
  52960. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  52961. if (alphaTexture.coordinatesIndex === 1) {
  52962. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52963. defines.push("#define UV2");
  52964. }
  52965. }
  52966. }
  52967. }
  52968. // Bones
  52969. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52970. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52971. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52972. if (mesh.numBoneInfluencers > 4) {
  52973. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52974. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52975. }
  52976. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52977. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52978. }
  52979. else {
  52980. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52981. }
  52982. // Instances
  52983. if (useInstances) {
  52984. defines.push("#define INSTANCES");
  52985. attribs.push("world0");
  52986. attribs.push("world1");
  52987. attribs.push("world2");
  52988. attribs.push("world3");
  52989. }
  52990. // Get correct effect
  52991. var join = defines.join("\n");
  52992. if (this._cachedDefines !== join) {
  52993. this._cachedDefines = join;
  52994. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  52995. }
  52996. return this._effect.isReady();
  52997. };
  52998. /**
  52999. * This creates the defines related to the standard BJS materials.
  53000. */
  53001. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  53002. var scene = this._scene;
  53003. var light = this._light;
  53004. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  53005. return;
  53006. }
  53007. defines["SHADOW" + lightIndex] = true;
  53008. if (this.usePoissonSampling) {
  53009. defines["SHADOWPCF" + lightIndex] = true;
  53010. }
  53011. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  53012. defines["SHADOWESM" + lightIndex] = true;
  53013. }
  53014. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  53015. defines["SHADOWCLOSEESM" + lightIndex] = true;
  53016. }
  53017. if (light.needCube()) {
  53018. defines["SHADOWCUBE" + lightIndex] = true;
  53019. }
  53020. };
  53021. /**
  53022. * This binds shadow lights related to the standard BJS materials.
  53023. * It implies the unifroms available on the materials are the standard BJS ones.
  53024. */
  53025. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  53026. var light = this._light;
  53027. var scene = this._scene;
  53028. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  53029. return;
  53030. }
  53031. var camera = scene.activeCamera;
  53032. if (!camera) {
  53033. return;
  53034. }
  53035. var shadowMap = this.getShadowMap();
  53036. if (!shadowMap) {
  53037. return;
  53038. }
  53039. if (!light.needCube()) {
  53040. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  53041. }
  53042. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  53043. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  53044. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  53045. };
  53046. // Methods
  53047. /**
  53048. * Returns a Matrix object : the updated transformation matrix.
  53049. */
  53050. ShadowGenerator.prototype.getTransformMatrix = function () {
  53051. var scene = this._scene;
  53052. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  53053. return this._transformMatrix;
  53054. }
  53055. this._currentRenderID = scene.getRenderId();
  53056. this._currentFaceIndexCache = this._currentFaceIndex;
  53057. var lightPosition = this._light.position;
  53058. if (this._light.computeTransformedInformation()) {
  53059. lightPosition = this._light.transformedPosition;
  53060. }
  53061. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  53062. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  53063. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  53064. }
  53065. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  53066. this._cachedPosition = lightPosition.clone();
  53067. this._cachedDirection = this._lightDirection.clone();
  53068. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  53069. var shadowMap = this.getShadowMap();
  53070. if (shadowMap) {
  53071. var renderList = shadowMap.renderList;
  53072. if (renderList) {
  53073. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  53074. }
  53075. }
  53076. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  53077. }
  53078. return this._transformMatrix;
  53079. };
  53080. ShadowGenerator.prototype.recreateShadowMap = function () {
  53081. var shadowMap = this._shadowMap;
  53082. if (!shadowMap) {
  53083. return;
  53084. }
  53085. // Track render list.
  53086. var renderList = shadowMap.renderList;
  53087. // Clean up existing data.
  53088. this._disposeRTTandPostProcesses();
  53089. // Reinitializes.
  53090. this._initializeGenerator();
  53091. // Reaffect the filter to ensure a correct fallback if necessary.
  53092. this.filter = this.filter;
  53093. // Reaffect the filter.
  53094. this._applyFilterValues();
  53095. // Reaffect Render List.
  53096. this._shadowMap.renderList = renderList;
  53097. };
  53098. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  53099. if (this._shadowMap2) {
  53100. this._shadowMap2.dispose();
  53101. this._shadowMap2 = null;
  53102. }
  53103. if (this._downSamplePostprocess) {
  53104. this._downSamplePostprocess.dispose();
  53105. this._downSamplePostprocess = null;
  53106. }
  53107. if (this._boxBlurPostprocess) {
  53108. this._boxBlurPostprocess.dispose();
  53109. this._boxBlurPostprocess = null;
  53110. }
  53111. if (this._kernelBlurXPostprocess) {
  53112. this._kernelBlurXPostprocess.dispose();
  53113. this._kernelBlurXPostprocess = null;
  53114. }
  53115. if (this._kernelBlurYPostprocess) {
  53116. this._kernelBlurYPostprocess.dispose();
  53117. this._kernelBlurYPostprocess = null;
  53118. }
  53119. this._blurPostProcesses = [];
  53120. };
  53121. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  53122. if (this._shadowMap) {
  53123. this._shadowMap.dispose();
  53124. this._shadowMap = null;
  53125. }
  53126. this._disposeBlurPostProcesses();
  53127. };
  53128. /**
  53129. * Disposes the ShadowGenerator.
  53130. * Returns nothing.
  53131. */
  53132. ShadowGenerator.prototype.dispose = function () {
  53133. this._disposeRTTandPostProcesses();
  53134. if (this._light) {
  53135. this._light._shadowGenerator = null;
  53136. this._light._markMeshesAsLightDirty();
  53137. }
  53138. };
  53139. /**
  53140. * Serializes the ShadowGenerator and returns a serializationObject.
  53141. */
  53142. ShadowGenerator.prototype.serialize = function () {
  53143. var serializationObject = {};
  53144. var shadowMap = this.getShadowMap();
  53145. if (!shadowMap) {
  53146. return serializationObject;
  53147. }
  53148. serializationObject.lightId = this._light.id;
  53149. serializationObject.mapSize = shadowMap.getRenderSize();
  53150. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  53151. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  53152. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  53153. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  53154. serializationObject.usePoissonSampling = this.usePoissonSampling;
  53155. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  53156. serializationObject.depthScale = this.depthScale;
  53157. serializationObject.darkness = this.getDarkness();
  53158. serializationObject.blurBoxOffset = this.blurBoxOffset;
  53159. serializationObject.blurKernel = this.blurKernel;
  53160. serializationObject.blurScale = this.blurScale;
  53161. serializationObject.useKernelBlur = this.useKernelBlur;
  53162. serializationObject.transparencyShadow = this._transparencyShadow;
  53163. serializationObject.renderList = [];
  53164. if (shadowMap.renderList) {
  53165. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  53166. var mesh = shadowMap.renderList[meshIndex];
  53167. serializationObject.renderList.push(mesh.id);
  53168. }
  53169. }
  53170. return serializationObject;
  53171. };
  53172. /**
  53173. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  53174. */
  53175. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  53176. //casting to point light, as light is missing the position attr and typescript complains.
  53177. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  53178. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  53179. var shadowMap = shadowGenerator.getShadowMap();
  53180. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  53181. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  53182. meshes.forEach(function (mesh) {
  53183. if (!shadowMap) {
  53184. return;
  53185. }
  53186. if (!shadowMap.renderList) {
  53187. shadowMap.renderList = [];
  53188. }
  53189. shadowMap.renderList.push(mesh);
  53190. });
  53191. }
  53192. if (parsedShadowGenerator.usePoissonSampling) {
  53193. shadowGenerator.usePoissonSampling = true;
  53194. }
  53195. else if (parsedShadowGenerator.useExponentialShadowMap) {
  53196. shadowGenerator.useExponentialShadowMap = true;
  53197. }
  53198. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  53199. shadowGenerator.useBlurExponentialShadowMap = true;
  53200. }
  53201. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  53202. shadowGenerator.useCloseExponentialShadowMap = true;
  53203. }
  53204. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  53205. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  53206. }
  53207. else if (parsedShadowGenerator.useVarianceShadowMap) {
  53208. shadowGenerator.useExponentialShadowMap = true;
  53209. }
  53210. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  53211. shadowGenerator.useBlurExponentialShadowMap = true;
  53212. }
  53213. if (parsedShadowGenerator.depthScale) {
  53214. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  53215. }
  53216. if (parsedShadowGenerator.blurScale) {
  53217. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  53218. }
  53219. if (parsedShadowGenerator.blurBoxOffset) {
  53220. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  53221. }
  53222. if (parsedShadowGenerator.useKernelBlur) {
  53223. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  53224. }
  53225. if (parsedShadowGenerator.blurKernel) {
  53226. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  53227. }
  53228. if (parsedShadowGenerator.bias !== undefined) {
  53229. shadowGenerator.bias = parsedShadowGenerator.bias;
  53230. }
  53231. if (parsedShadowGenerator.darkness) {
  53232. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  53233. }
  53234. if (parsedShadowGenerator.transparencyShadow) {
  53235. shadowGenerator.setTransparencyShadow(true);
  53236. }
  53237. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  53238. return shadowGenerator;
  53239. };
  53240. ShadowGenerator._FILTER_NONE = 0;
  53241. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  53242. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  53243. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  53244. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  53245. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  53246. return ShadowGenerator;
  53247. }());
  53248. BABYLON.ShadowGenerator = ShadowGenerator;
  53249. })(BABYLON || (BABYLON = {}));
  53250. //# sourceMappingURL=babylon.shadowGenerator.js.map
  53251. var BABYLON;
  53252. (function (BABYLON) {
  53253. var DefaultLoadingScreen = /** @class */ (function () {
  53254. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  53255. if (_loadingText === void 0) { _loadingText = ""; }
  53256. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  53257. var _this = this;
  53258. this._renderingCanvas = _renderingCanvas;
  53259. this._loadingText = _loadingText;
  53260. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  53261. // Resize
  53262. this._resizeLoadingUI = function () {
  53263. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  53264. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  53265. if (!_this._loadingDiv) {
  53266. return;
  53267. }
  53268. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  53269. _this._loadingDiv.style.left = canvasRect.left + "px";
  53270. _this._loadingDiv.style.top = canvasRect.top + "px";
  53271. _this._loadingDiv.style.width = canvasRect.width + "px";
  53272. _this._loadingDiv.style.height = canvasRect.height + "px";
  53273. };
  53274. }
  53275. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  53276. if (this._loadingDiv) {
  53277. // Do not add a loading screen if there is already one
  53278. return;
  53279. }
  53280. this._loadingDiv = document.createElement("div");
  53281. this._loadingDiv.id = "babylonjsLoadingDiv";
  53282. this._loadingDiv.style.opacity = "0";
  53283. this._loadingDiv.style.transition = "opacity 1.5s ease";
  53284. this._loadingDiv.style.pointerEvents = "none";
  53285. // Loading text
  53286. this._loadingTextDiv = document.createElement("div");
  53287. this._loadingTextDiv.style.position = "absolute";
  53288. this._loadingTextDiv.style.left = "0";
  53289. this._loadingTextDiv.style.top = "50%";
  53290. this._loadingTextDiv.style.marginTop = "80px";
  53291. this._loadingTextDiv.style.width = "100%";
  53292. this._loadingTextDiv.style.height = "20px";
  53293. this._loadingTextDiv.style.fontFamily = "Arial";
  53294. this._loadingTextDiv.style.fontSize = "14px";
  53295. this._loadingTextDiv.style.color = "white";
  53296. this._loadingTextDiv.style.textAlign = "center";
  53297. this._loadingTextDiv.innerHTML = "Loading";
  53298. this._loadingDiv.appendChild(this._loadingTextDiv);
  53299. //set the predefined text
  53300. this._loadingTextDiv.innerHTML = this._loadingText;
  53301. // Generating keyframes
  53302. var style = document.createElement('style');
  53303. style.type = 'text/css';
  53304. 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 }";
  53305. style.innerHTML = keyFrames;
  53306. document.getElementsByTagName('head')[0].appendChild(style);
  53307. // Loading img
  53308. var imgBack = new Image();
  53309. 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";
  53310. imgBack.style.position = "absolute";
  53311. imgBack.style.left = "50%";
  53312. imgBack.style.top = "50%";
  53313. imgBack.style.marginLeft = "-60px";
  53314. imgBack.style.marginTop = "-60px";
  53315. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  53316. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  53317. imgBack.style.transformOrigin = "50% 50%";
  53318. imgBack.style.webkitTransformOrigin = "50% 50%";
  53319. this._loadingDiv.appendChild(imgBack);
  53320. this._resizeLoadingUI();
  53321. window.addEventListener("resize", this._resizeLoadingUI);
  53322. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  53323. document.body.appendChild(this._loadingDiv);
  53324. this._loadingDiv.style.opacity = "1";
  53325. };
  53326. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  53327. var _this = this;
  53328. if (!this._loadingDiv) {
  53329. return;
  53330. }
  53331. var onTransitionEnd = function () {
  53332. if (!_this._loadingDiv) {
  53333. return;
  53334. }
  53335. document.body.removeChild(_this._loadingDiv);
  53336. window.removeEventListener("resize", _this._resizeLoadingUI);
  53337. _this._loadingDiv = null;
  53338. };
  53339. this._loadingDiv.style.opacity = "0";
  53340. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  53341. };
  53342. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  53343. set: function (text) {
  53344. this._loadingText = text;
  53345. if (this._loadingTextDiv) {
  53346. this._loadingTextDiv.innerHTML = this._loadingText;
  53347. }
  53348. },
  53349. enumerable: true,
  53350. configurable: true
  53351. });
  53352. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  53353. get: function () {
  53354. return this._loadingDivBackgroundColor;
  53355. },
  53356. set: function (color) {
  53357. this._loadingDivBackgroundColor = color;
  53358. if (!this._loadingDiv) {
  53359. return;
  53360. }
  53361. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  53362. },
  53363. enumerable: true,
  53364. configurable: true
  53365. });
  53366. return DefaultLoadingScreen;
  53367. }());
  53368. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  53369. })(BABYLON || (BABYLON = {}));
  53370. //# sourceMappingURL=babylon.loadingScreen.js.map
  53371. var BABYLON;
  53372. (function (BABYLON) {
  53373. var SceneLoaderProgressEvent = /** @class */ (function () {
  53374. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  53375. this.lengthComputable = lengthComputable;
  53376. this.loaded = loaded;
  53377. this.total = total;
  53378. }
  53379. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  53380. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  53381. };
  53382. return SceneLoaderProgressEvent;
  53383. }());
  53384. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  53385. var SceneLoader = /** @class */ (function () {
  53386. function SceneLoader() {
  53387. }
  53388. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  53389. get: function () {
  53390. return 0;
  53391. },
  53392. enumerable: true,
  53393. configurable: true
  53394. });
  53395. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  53396. get: function () {
  53397. return 1;
  53398. },
  53399. enumerable: true,
  53400. configurable: true
  53401. });
  53402. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  53403. get: function () {
  53404. return 2;
  53405. },
  53406. enumerable: true,
  53407. configurable: true
  53408. });
  53409. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  53410. get: function () {
  53411. return 3;
  53412. },
  53413. enumerable: true,
  53414. configurable: true
  53415. });
  53416. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  53417. get: function () {
  53418. return SceneLoader._ForceFullSceneLoadingForIncremental;
  53419. },
  53420. set: function (value) {
  53421. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  53422. },
  53423. enumerable: true,
  53424. configurable: true
  53425. });
  53426. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  53427. get: function () {
  53428. return SceneLoader._ShowLoadingScreen;
  53429. },
  53430. set: function (value) {
  53431. SceneLoader._ShowLoadingScreen = value;
  53432. },
  53433. enumerable: true,
  53434. configurable: true
  53435. });
  53436. Object.defineProperty(SceneLoader, "loggingLevel", {
  53437. get: function () {
  53438. return SceneLoader._loggingLevel;
  53439. },
  53440. set: function (value) {
  53441. SceneLoader._loggingLevel = value;
  53442. },
  53443. enumerable: true,
  53444. configurable: true
  53445. });
  53446. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  53447. get: function () {
  53448. return SceneLoader._CleanBoneMatrixWeights;
  53449. },
  53450. set: function (value) {
  53451. SceneLoader._CleanBoneMatrixWeights = value;
  53452. },
  53453. enumerable: true,
  53454. configurable: true
  53455. });
  53456. SceneLoader._getDefaultPlugin = function () {
  53457. return SceneLoader._registeredPlugins[".babylon"];
  53458. };
  53459. SceneLoader._getPluginForExtension = function (extension) {
  53460. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  53461. if (registeredPlugin) {
  53462. return registeredPlugin;
  53463. }
  53464. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  53465. return SceneLoader._getDefaultPlugin();
  53466. };
  53467. SceneLoader._getPluginForDirectLoad = function (data) {
  53468. for (var extension in SceneLoader._registeredPlugins) {
  53469. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  53470. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  53471. return SceneLoader._registeredPlugins[extension];
  53472. }
  53473. }
  53474. return SceneLoader._getDefaultPlugin();
  53475. };
  53476. SceneLoader._getPluginForFilename = function (sceneFilename) {
  53477. if (sceneFilename.name) {
  53478. sceneFilename = sceneFilename.name;
  53479. }
  53480. var queryStringPosition = sceneFilename.indexOf("?");
  53481. if (queryStringPosition !== -1) {
  53482. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  53483. }
  53484. var dotPosition = sceneFilename.lastIndexOf(".");
  53485. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  53486. return SceneLoader._getPluginForExtension(extension);
  53487. };
  53488. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  53489. SceneLoader._getDirectLoad = function (sceneFilename) {
  53490. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  53491. return sceneFilename.substr(5);
  53492. }
  53493. return null;
  53494. };
  53495. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  53496. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  53497. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  53498. var plugin;
  53499. if (registeredPlugin.plugin.createPlugin) {
  53500. plugin = registeredPlugin.plugin.createPlugin();
  53501. }
  53502. else {
  53503. plugin = registeredPlugin.plugin;
  53504. }
  53505. var useArrayBuffer = registeredPlugin.isBinary;
  53506. var database;
  53507. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  53508. var dataCallback = function (data, responseURL) {
  53509. if (scene.isDisposed) {
  53510. onError("Scene has been disposed");
  53511. return;
  53512. }
  53513. scene.database = database;
  53514. onSuccess(plugin, data, responseURL);
  53515. };
  53516. var manifestChecked = function (success) {
  53517. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress ? function (event) {
  53518. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  53519. } : undefined, database, useArrayBuffer, function (request, exception) {
  53520. if (request) {
  53521. onError(request.status + " " + request.statusText, exception);
  53522. }
  53523. });
  53524. };
  53525. if (directLoad) {
  53526. dataCallback(directLoad);
  53527. return plugin;
  53528. }
  53529. if (rootUrl.indexOf("file:") === -1) {
  53530. if (scene.getEngine().enableOfflineSupport) {
  53531. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  53532. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  53533. }
  53534. else {
  53535. manifestChecked(true);
  53536. }
  53537. }
  53538. else {
  53539. var fileOrString = sceneFilename;
  53540. if (fileOrString.name) {
  53541. BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  53542. }
  53543. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  53544. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  53545. }
  53546. else {
  53547. onError("Unable to find file named " + sceneFilename);
  53548. }
  53549. }
  53550. return plugin;
  53551. };
  53552. // Public functions
  53553. SceneLoader.GetPluginForExtension = function (extension) {
  53554. return SceneLoader._getPluginForExtension(extension).plugin;
  53555. };
  53556. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  53557. return !!SceneLoader._registeredPlugins[extension];
  53558. };
  53559. SceneLoader.RegisterPlugin = function (plugin) {
  53560. if (typeof plugin.extensions === "string") {
  53561. var extension = plugin.extensions;
  53562. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  53563. plugin: plugin,
  53564. isBinary: false
  53565. };
  53566. }
  53567. else {
  53568. var extensions = plugin.extensions;
  53569. Object.keys(extensions).forEach(function (extension) {
  53570. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  53571. plugin: plugin,
  53572. isBinary: extensions[extension].isBinary
  53573. };
  53574. });
  53575. }
  53576. };
  53577. /**
  53578. * Import meshes into a scene
  53579. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  53580. * @param rootUrl a string that defines the root url for scene and resources
  53581. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  53582. * @param scene the instance of BABYLON.Scene to append to
  53583. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  53584. * @param onProgress a callback with a progress event for each file being loaded
  53585. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  53586. */
  53587. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  53588. if (onSuccess === void 0) { onSuccess = null; }
  53589. if (onProgress === void 0) { onProgress = null; }
  53590. if (onError === void 0) { onError = null; }
  53591. if (pluginExtension === void 0) { pluginExtension = null; }
  53592. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  53593. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  53594. return null;
  53595. }
  53596. var loadingToken = {};
  53597. scene._addPendingData(loadingToken);
  53598. var errorHandler = function (message, exception) {
  53599. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  53600. if (onError) {
  53601. onError(scene, errorMessage, exception);
  53602. }
  53603. else {
  53604. BABYLON.Tools.Error(errorMessage);
  53605. // should the exception be thrown?
  53606. }
  53607. scene._removePendingData(loadingToken);
  53608. };
  53609. var progressHandler = onProgress ? function (event) {
  53610. try {
  53611. onProgress(event);
  53612. }
  53613. catch (e) {
  53614. errorHandler("Error in onProgress callback", e);
  53615. }
  53616. } : undefined;
  53617. var successHandler = function (meshes, particleSystems, skeletons) {
  53618. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  53619. if (onSuccess) {
  53620. try {
  53621. onSuccess(meshes, particleSystems, skeletons);
  53622. }
  53623. catch (e) {
  53624. errorHandler("Error in onSuccess callback", e);
  53625. }
  53626. }
  53627. scene._removePendingData(loadingToken);
  53628. };
  53629. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  53630. if (plugin.rewriteRootURL) {
  53631. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  53632. }
  53633. if (plugin.importMesh) {
  53634. var syncedPlugin = plugin;
  53635. var meshes = new Array();
  53636. var particleSystems = new Array();
  53637. var skeletons = new Array();
  53638. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  53639. return;
  53640. }
  53641. scene.loadingPluginName = plugin.name;
  53642. successHandler(meshes, particleSystems, skeletons);
  53643. }
  53644. else {
  53645. var asyncedPlugin = plugin;
  53646. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  53647. scene.loadingPluginName = plugin.name;
  53648. successHandler(meshes, particleSystems, skeletons);
  53649. }, progressHandler, errorHandler);
  53650. }
  53651. }, progressHandler, errorHandler, pluginExtension);
  53652. };
  53653. /**
  53654. * Load a scene
  53655. * @param rootUrl a string that defines the root url for scene and resources
  53656. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  53657. * @param engine is the instance of BABYLON.Engine to use to create the scene
  53658. * @param onSuccess a callback with the scene when import succeeds
  53659. * @param onProgress a callback with a progress event for each file being loaded
  53660. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  53661. */
  53662. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  53663. if (onSuccess === void 0) { onSuccess = null; }
  53664. if (onProgress === void 0) { onProgress = null; }
  53665. if (onError === void 0) { onError = null; }
  53666. if (pluginExtension === void 0) { pluginExtension = null; }
  53667. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  53668. };
  53669. /**
  53670. * Append a scene
  53671. * @param rootUrl a string that defines the root url for scene and resources
  53672. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  53673. * @param scene is the instance of BABYLON.Scene to append to
  53674. * @param onSuccess a callback with the scene when import succeeds
  53675. * @param onProgress a callback with a progress event for each file being loaded
  53676. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  53677. */
  53678. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  53679. if (onSuccess === void 0) { onSuccess = null; }
  53680. if (onProgress === void 0) { onProgress = null; }
  53681. if (onError === void 0) { onError = null; }
  53682. if (pluginExtension === void 0) { pluginExtension = null; }
  53683. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  53684. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  53685. return null;
  53686. }
  53687. if (SceneLoader.ShowLoadingScreen) {
  53688. scene.getEngine().displayLoadingUI();
  53689. }
  53690. var loadingToken = {};
  53691. scene._addPendingData(loadingToken);
  53692. var errorHandler = function (message, exception) {
  53693. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  53694. if (onError) {
  53695. onError(scene, errorMessage, exception);
  53696. }
  53697. else {
  53698. BABYLON.Tools.Error(errorMessage);
  53699. // should the exception be thrown?
  53700. }
  53701. scene._removePendingData(loadingToken);
  53702. scene.getEngine().hideLoadingUI();
  53703. };
  53704. var progressHandler = onProgress ? function (event) {
  53705. try {
  53706. onProgress(event);
  53707. }
  53708. catch (e) {
  53709. errorHandler("Error in onProgress callback", e);
  53710. }
  53711. } : undefined;
  53712. var successHandler = function () {
  53713. if (onSuccess) {
  53714. try {
  53715. onSuccess(scene);
  53716. }
  53717. catch (e) {
  53718. errorHandler("Error in onSuccess callback", e);
  53719. }
  53720. }
  53721. scene._removePendingData(loadingToken);
  53722. };
  53723. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  53724. if (plugin.load) {
  53725. var syncedPlugin = plugin;
  53726. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  53727. return;
  53728. }
  53729. scene.loadingPluginName = plugin.name;
  53730. successHandler();
  53731. }
  53732. else {
  53733. var asyncedPlugin = plugin;
  53734. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  53735. scene.loadingPluginName = plugin.name;
  53736. successHandler();
  53737. }, progressHandler, errorHandler);
  53738. }
  53739. if (SceneLoader.ShowLoadingScreen) {
  53740. scene.executeWhenReady(function () {
  53741. scene.getEngine().hideLoadingUI();
  53742. });
  53743. }
  53744. }, progressHandler, errorHandler, pluginExtension);
  53745. };
  53746. // Flags
  53747. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  53748. SceneLoader._ShowLoadingScreen = true;
  53749. SceneLoader._CleanBoneMatrixWeights = false;
  53750. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  53751. // Members
  53752. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  53753. SceneLoader._registeredPlugins = {};
  53754. return SceneLoader;
  53755. }());
  53756. BABYLON.SceneLoader = SceneLoader;
  53757. ;
  53758. })(BABYLON || (BABYLON = {}));
  53759. //# sourceMappingURL=babylon.sceneLoader.js.map
  53760. var BABYLON;
  53761. (function (BABYLON) {
  53762. var Internals;
  53763. (function (Internals) {
  53764. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  53765. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  53766. var parsedMaterial = parsedData.materials[index];
  53767. if (parsedMaterial.id === id) {
  53768. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  53769. }
  53770. }
  53771. return null;
  53772. };
  53773. var isDescendantOf = function (mesh, names, hierarchyIds) {
  53774. for (var i in names) {
  53775. if (mesh.name === names[i]) {
  53776. hierarchyIds.push(mesh.id);
  53777. return true;
  53778. }
  53779. }
  53780. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  53781. hierarchyIds.push(mesh.id);
  53782. return true;
  53783. }
  53784. return false;
  53785. };
  53786. var logOperation = function (operation, producer) {
  53787. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  53788. };
  53789. BABYLON.SceneLoader.RegisterPlugin({
  53790. name: "babylon.js",
  53791. extensions: ".babylon",
  53792. canDirectLoad: function (data) {
  53793. if (data.indexOf("babylon") !== -1) {
  53794. return true;
  53795. }
  53796. return false;
  53797. },
  53798. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  53799. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  53800. // when SceneLoader.debugLogging = true (default), or exception encountered.
  53801. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  53802. // and avoid problems with multiple concurrent .babylon loads.
  53803. var log = "importMesh has failed JSON parse";
  53804. try {
  53805. var parsedData = JSON.parse(data);
  53806. log = "";
  53807. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  53808. if (!meshesNames) {
  53809. meshesNames = null;
  53810. }
  53811. else if (!Array.isArray(meshesNames)) {
  53812. meshesNames = [meshesNames];
  53813. }
  53814. var hierarchyIds = new Array();
  53815. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  53816. var loadedSkeletonsIds = [];
  53817. var loadedMaterialsIds = [];
  53818. var index;
  53819. var cache;
  53820. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  53821. var parsedMesh = parsedData.meshes[index];
  53822. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  53823. if (meshesNames !== null) {
  53824. // Remove found mesh name from list.
  53825. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  53826. }
  53827. //Geometry?
  53828. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  53829. //does the file contain geometries?
  53830. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  53831. //find the correct geometry and add it to the scene
  53832. var found = false;
  53833. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  53834. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  53835. return;
  53836. }
  53837. else {
  53838. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  53839. if (parsedGeometryData.id === parsedMesh.geometryId) {
  53840. switch (geometryType) {
  53841. case "boxes":
  53842. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  53843. break;
  53844. case "spheres":
  53845. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  53846. break;
  53847. case "cylinders":
  53848. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  53849. break;
  53850. case "toruses":
  53851. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  53852. break;
  53853. case "grounds":
  53854. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  53855. break;
  53856. case "planes":
  53857. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  53858. break;
  53859. case "torusKnots":
  53860. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  53861. break;
  53862. case "vertexData":
  53863. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  53864. break;
  53865. }
  53866. found = true;
  53867. }
  53868. });
  53869. }
  53870. });
  53871. if (found === false) {
  53872. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  53873. }
  53874. }
  53875. }
  53876. // Material ?
  53877. if (parsedMesh.materialId) {
  53878. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  53879. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  53880. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  53881. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  53882. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  53883. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  53884. var subMatId = parsedMultiMaterial.materials[matIndex];
  53885. loadedMaterialsIds.push(subMatId);
  53886. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  53887. log += "\n\tMaterial " + mat.toString(fullDetails);
  53888. }
  53889. loadedMaterialsIds.push(parsedMultiMaterial.id);
  53890. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  53891. materialFound = true;
  53892. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  53893. break;
  53894. }
  53895. }
  53896. }
  53897. if (materialFound === false) {
  53898. loadedMaterialsIds.push(parsedMesh.materialId);
  53899. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  53900. if (!mat) {
  53901. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  53902. }
  53903. else {
  53904. log += "\n\tMaterial " + mat.toString(fullDetails);
  53905. }
  53906. }
  53907. }
  53908. // Skeleton ?
  53909. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  53910. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  53911. if (skeletonAlreadyLoaded === false) {
  53912. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  53913. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  53914. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  53915. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  53916. skeletons.push(skeleton);
  53917. loadedSkeletonsIds.push(parsedSkeleton.id);
  53918. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  53919. }
  53920. }
  53921. }
  53922. }
  53923. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  53924. meshes.push(mesh);
  53925. log += "\n\tMesh " + mesh.toString(fullDetails);
  53926. }
  53927. }
  53928. // Connecting parents
  53929. var currentMesh;
  53930. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  53931. currentMesh = scene.meshes[index];
  53932. if (currentMesh._waitingParentId) {
  53933. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  53934. currentMesh._waitingParentId = null;
  53935. }
  53936. }
  53937. // freeze and compute world matrix application
  53938. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  53939. currentMesh = scene.meshes[index];
  53940. if (currentMesh._waitingFreezeWorldMatrix) {
  53941. currentMesh.freezeWorldMatrix();
  53942. currentMesh._waitingFreezeWorldMatrix = null;
  53943. }
  53944. else {
  53945. currentMesh.computeWorldMatrix(true);
  53946. }
  53947. }
  53948. }
  53949. // Particles
  53950. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  53951. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  53952. var parsedParticleSystem = parsedData.particleSystems[index];
  53953. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  53954. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  53955. }
  53956. }
  53957. }
  53958. return true;
  53959. }
  53960. catch (err) {
  53961. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  53962. if (onError) {
  53963. onError(msg, err);
  53964. }
  53965. else {
  53966. BABYLON.Tools.Log(msg);
  53967. throw err;
  53968. }
  53969. }
  53970. finally {
  53971. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  53972. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  53973. }
  53974. }
  53975. return false;
  53976. },
  53977. load: function (scene, data, rootUrl, onError) {
  53978. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  53979. // when SceneLoader.debugLogging = true (default), or exception encountered.
  53980. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  53981. // and avoid problems with multiple concurrent .babylon loads.
  53982. var log = "importScene has failed JSON parse";
  53983. try {
  53984. var parsedData = JSON.parse(data);
  53985. log = "";
  53986. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  53987. // Scene
  53988. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  53989. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  53990. }
  53991. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  53992. scene.autoClear = parsedData.autoClear;
  53993. }
  53994. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  53995. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  53996. }
  53997. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  53998. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  53999. }
  54000. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  54001. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  54002. }
  54003. // Fog
  54004. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  54005. scene.fogMode = parsedData.fogMode;
  54006. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  54007. scene.fogStart = parsedData.fogStart;
  54008. scene.fogEnd = parsedData.fogEnd;
  54009. scene.fogDensity = parsedData.fogDensity;
  54010. log += "\tFog mode for scene: ";
  54011. switch (scene.fogMode) {
  54012. // getters not compiling, so using hardcoded
  54013. case 1:
  54014. log += "exp\n";
  54015. break;
  54016. case 2:
  54017. log += "exp2\n";
  54018. break;
  54019. case 3:
  54020. log += "linear\n";
  54021. break;
  54022. }
  54023. }
  54024. //Physics
  54025. if (parsedData.physicsEnabled) {
  54026. var physicsPlugin;
  54027. if (parsedData.physicsEngine === "cannon") {
  54028. physicsPlugin = new BABYLON.CannonJSPlugin();
  54029. }
  54030. else if (parsedData.physicsEngine === "oimo") {
  54031. physicsPlugin = new BABYLON.OimoJSPlugin();
  54032. }
  54033. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  54034. //else - default engine, which is currently oimo
  54035. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  54036. scene.enablePhysics(physicsGravity, physicsPlugin);
  54037. }
  54038. // Metadata
  54039. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  54040. scene.metadata = parsedData.metadata;
  54041. }
  54042. //collisions, if defined. otherwise, default is true
  54043. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  54044. scene.collisionsEnabled = parsedData.collisionsEnabled;
  54045. }
  54046. scene.workerCollisions = !!parsedData.workerCollisions;
  54047. var index;
  54048. var cache;
  54049. // Lights
  54050. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  54051. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  54052. var parsedLight = parsedData.lights[index];
  54053. var light = BABYLON.Light.Parse(parsedLight, scene);
  54054. if (light) {
  54055. log += (index === 0 ? "\n\tLights:" : "");
  54056. log += "\n\t\t" + light.toString(fullDetails);
  54057. }
  54058. }
  54059. }
  54060. // Animations
  54061. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  54062. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  54063. var parsedAnimation = parsedData.animations[index];
  54064. var animation = BABYLON.Animation.Parse(parsedAnimation);
  54065. scene.animations.push(animation);
  54066. log += (index === 0 ? "\n\tAnimations:" : "");
  54067. log += "\n\t\t" + animation.toString(fullDetails);
  54068. }
  54069. }
  54070. if (parsedData.autoAnimate) {
  54071. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  54072. }
  54073. // Materials
  54074. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  54075. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  54076. var parsedMaterial = parsedData.materials[index];
  54077. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  54078. log += (index === 0 ? "\n\tMaterials:" : "");
  54079. log += "\n\t\t" + mat.toString(fullDetails);
  54080. }
  54081. }
  54082. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  54083. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  54084. var parsedMultiMaterial = parsedData.multiMaterials[index];
  54085. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  54086. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  54087. log += "\n\t\t" + mmat.toString(fullDetails);
  54088. }
  54089. }
  54090. // Morph targets
  54091. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  54092. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  54093. var managerData = _a[_i];
  54094. BABYLON.MorphTargetManager.Parse(managerData, scene);
  54095. }
  54096. }
  54097. // Skeletons
  54098. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  54099. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  54100. var parsedSkeleton = parsedData.skeletons[index];
  54101. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  54102. log += (index === 0 ? "\n\tSkeletons:" : "");
  54103. log += "\n\t\t" + skeleton.toString(fullDetails);
  54104. }
  54105. }
  54106. // Geometries
  54107. var geometries = parsedData.geometries;
  54108. if (geometries !== undefined && geometries !== null) {
  54109. // Boxes
  54110. var boxes = geometries.boxes;
  54111. if (boxes !== undefined && boxes !== null) {
  54112. for (index = 0, cache = boxes.length; index < cache; index++) {
  54113. var parsedBox = boxes[index];
  54114. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  54115. }
  54116. }
  54117. // Spheres
  54118. var spheres = geometries.spheres;
  54119. if (spheres !== undefined && spheres !== null) {
  54120. for (index = 0, cache = spheres.length; index < cache; index++) {
  54121. var parsedSphere = spheres[index];
  54122. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  54123. }
  54124. }
  54125. // Cylinders
  54126. var cylinders = geometries.cylinders;
  54127. if (cylinders !== undefined && cylinders !== null) {
  54128. for (index = 0, cache = cylinders.length; index < cache; index++) {
  54129. var parsedCylinder = cylinders[index];
  54130. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  54131. }
  54132. }
  54133. // Toruses
  54134. var toruses = geometries.toruses;
  54135. if (toruses !== undefined && toruses !== null) {
  54136. for (index = 0, cache = toruses.length; index < cache; index++) {
  54137. var parsedTorus = toruses[index];
  54138. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  54139. }
  54140. }
  54141. // Grounds
  54142. var grounds = geometries.grounds;
  54143. if (grounds !== undefined && grounds !== null) {
  54144. for (index = 0, cache = grounds.length; index < cache; index++) {
  54145. var parsedGround = grounds[index];
  54146. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  54147. }
  54148. }
  54149. // Planes
  54150. var planes = geometries.planes;
  54151. if (planes !== undefined && planes !== null) {
  54152. for (index = 0, cache = planes.length; index < cache; index++) {
  54153. var parsedPlane = planes[index];
  54154. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  54155. }
  54156. }
  54157. // TorusKnots
  54158. var torusKnots = geometries.torusKnots;
  54159. if (torusKnots !== undefined && torusKnots !== null) {
  54160. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  54161. var parsedTorusKnot = torusKnots[index];
  54162. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  54163. }
  54164. }
  54165. // VertexData
  54166. var vertexData = geometries.vertexData;
  54167. if (vertexData !== undefined && vertexData !== null) {
  54168. for (index = 0, cache = vertexData.length; index < cache; index++) {
  54169. var parsedVertexData = vertexData[index];
  54170. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  54171. }
  54172. }
  54173. }
  54174. // Transform nodes
  54175. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  54176. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  54177. var parsedTransformNode = parsedData.transformNodes[index];
  54178. BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  54179. }
  54180. }
  54181. // Meshes
  54182. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  54183. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  54184. var parsedMesh = parsedData.meshes[index];
  54185. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  54186. log += (index === 0 ? "\n\tMeshes:" : "");
  54187. log += "\n\t\t" + mesh.toString(fullDetails);
  54188. }
  54189. }
  54190. // Cameras
  54191. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  54192. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  54193. var parsedCamera = parsedData.cameras[index];
  54194. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  54195. log += (index === 0 ? "\n\tCameras:" : "");
  54196. log += "\n\t\t" + camera.toString(fullDetails);
  54197. }
  54198. }
  54199. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  54200. scene.setActiveCameraByID(parsedData.activeCameraID);
  54201. }
  54202. // Browsing all the graph to connect the dots
  54203. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  54204. var camera = scene.cameras[index];
  54205. if (camera._waitingParentId) {
  54206. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  54207. camera._waitingParentId = null;
  54208. }
  54209. }
  54210. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  54211. var light_1 = scene.lights[index];
  54212. if (light_1 && light_1._waitingParentId) {
  54213. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  54214. light_1._waitingParentId = null;
  54215. }
  54216. }
  54217. // Sounds
  54218. var loadedSounds = [];
  54219. var loadedSound;
  54220. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  54221. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  54222. var parsedSound = parsedData.sounds[index];
  54223. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  54224. if (!parsedSound.url)
  54225. parsedSound.url = parsedSound.name;
  54226. if (!loadedSounds[parsedSound.url]) {
  54227. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  54228. loadedSounds[parsedSound.url] = loadedSound;
  54229. }
  54230. else {
  54231. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  54232. }
  54233. }
  54234. else {
  54235. new BABYLON.Sound(parsedSound.name, null, scene);
  54236. }
  54237. }
  54238. }
  54239. loadedSounds = [];
  54240. // Connect parents & children and parse actions
  54241. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  54242. var transformNode = scene.transformNodes[index];
  54243. if (transformNode._waitingParentId) {
  54244. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  54245. transformNode._waitingParentId = null;
  54246. }
  54247. }
  54248. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  54249. var mesh = scene.meshes[index];
  54250. if (mesh._waitingParentId) {
  54251. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  54252. mesh._waitingParentId = null;
  54253. }
  54254. if (mesh._waitingActions) {
  54255. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  54256. mesh._waitingActions = null;
  54257. }
  54258. }
  54259. // freeze world matrix application
  54260. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  54261. var currentMesh = scene.meshes[index];
  54262. if (currentMesh._waitingFreezeWorldMatrix) {
  54263. currentMesh.freezeWorldMatrix();
  54264. currentMesh._waitingFreezeWorldMatrix = null;
  54265. }
  54266. else {
  54267. currentMesh.computeWorldMatrix(true);
  54268. }
  54269. }
  54270. // Particles Systems
  54271. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  54272. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  54273. var parsedParticleSystem = parsedData.particleSystems[index];
  54274. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  54275. }
  54276. }
  54277. // Environment texture
  54278. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  54279. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  54280. if (parsedData.createDefaultSkybox === true) {
  54281. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  54282. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  54283. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  54284. }
  54285. }
  54286. // Lens flares
  54287. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  54288. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  54289. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  54290. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  54291. }
  54292. }
  54293. // Shadows
  54294. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  54295. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  54296. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  54297. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  54298. }
  54299. }
  54300. // Lights exclusions / inclusions
  54301. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  54302. var light_2 = scene.lights[index];
  54303. // Excluded check
  54304. if (light_2._excludedMeshesIds.length > 0) {
  54305. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  54306. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  54307. if (excludedMesh) {
  54308. light_2.excludedMeshes.push(excludedMesh);
  54309. }
  54310. }
  54311. light_2._excludedMeshesIds = [];
  54312. }
  54313. // Included check
  54314. if (light_2._includedOnlyMeshesIds.length > 0) {
  54315. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  54316. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  54317. if (includedOnlyMesh) {
  54318. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  54319. }
  54320. }
  54321. light_2._includedOnlyMeshesIds = [];
  54322. }
  54323. }
  54324. // Actions (scene)
  54325. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  54326. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  54327. }
  54328. // Finish
  54329. return true;
  54330. }
  54331. catch (err) {
  54332. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  54333. if (onError) {
  54334. onError(msg, err);
  54335. }
  54336. else {
  54337. BABYLON.Tools.Log(msg);
  54338. throw err;
  54339. }
  54340. }
  54341. finally {
  54342. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  54343. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  54344. }
  54345. }
  54346. return false;
  54347. }
  54348. });
  54349. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54350. })(BABYLON || (BABYLON = {}));
  54351. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  54352. var BABYLON;
  54353. (function (BABYLON) {
  54354. var FilesInput = /** @class */ (function () {
  54355. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  54356. this.onProcessFileCallback = function () { return true; };
  54357. this._engine = engine;
  54358. this._currentScene = scene;
  54359. this._sceneLoadedCallback = sceneLoadedCallback;
  54360. this._progressCallback = progressCallback;
  54361. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  54362. this._textureLoadingCallback = textureLoadingCallback;
  54363. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  54364. this._onReloadCallback = onReloadCallback;
  54365. this._errorCallback = errorCallback;
  54366. }
  54367. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  54368. var _this = this;
  54369. if (elementToMonitor) {
  54370. this._elementToMonitor = elementToMonitor;
  54371. this._dragEnterHandler = function (e) { _this.drag(e); };
  54372. this._dragOverHandler = function (e) { _this.drag(e); };
  54373. this._dropHandler = function (e) { _this.drop(e); };
  54374. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  54375. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  54376. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  54377. }
  54378. };
  54379. FilesInput.prototype.dispose = function () {
  54380. if (!this._elementToMonitor) {
  54381. return;
  54382. }
  54383. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  54384. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  54385. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  54386. };
  54387. FilesInput.prototype.renderFunction = function () {
  54388. if (this._additionalRenderLoopLogicCallback) {
  54389. this._additionalRenderLoopLogicCallback();
  54390. }
  54391. if (this._currentScene) {
  54392. if (this._textureLoadingCallback) {
  54393. var remaining = this._currentScene.getWaitingItemsCount();
  54394. if (remaining > 0) {
  54395. this._textureLoadingCallback(remaining);
  54396. }
  54397. }
  54398. this._currentScene.render();
  54399. }
  54400. };
  54401. FilesInput.prototype.drag = function (e) {
  54402. e.stopPropagation();
  54403. e.preventDefault();
  54404. };
  54405. FilesInput.prototype.drop = function (eventDrop) {
  54406. eventDrop.stopPropagation();
  54407. eventDrop.preventDefault();
  54408. this.loadFiles(eventDrop);
  54409. };
  54410. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  54411. var _this = this;
  54412. var reader = folder.createReader();
  54413. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  54414. reader.readEntries(function (entries) {
  54415. remaining.count += entries.length;
  54416. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  54417. var entry = entries_1[_i];
  54418. if (entry.isFile) {
  54419. entry.file(function (file) {
  54420. file.correctName = relativePath + file.name;
  54421. files.push(file);
  54422. if (--remaining.count === 0) {
  54423. callback();
  54424. }
  54425. });
  54426. }
  54427. else if (entry.isDirectory) {
  54428. _this._traverseFolder(entry, files, remaining, callback);
  54429. }
  54430. }
  54431. if (--remaining.count) {
  54432. callback();
  54433. }
  54434. });
  54435. };
  54436. FilesInput.prototype._processFiles = function (files) {
  54437. for (var i = 0; i < files.length; i++) {
  54438. var name = files[i].correctName.toLowerCase();
  54439. var extension = name.split('.').pop();
  54440. if (!this.onProcessFileCallback(files[i], name, extension)) {
  54441. continue;
  54442. }
  54443. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  54444. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  54445. this._sceneFileToLoad = files[i];
  54446. }
  54447. else {
  54448. FilesInput.FilesToLoad[name] = files[i];
  54449. }
  54450. }
  54451. };
  54452. FilesInput.prototype.loadFiles = function (event) {
  54453. var _this = this;
  54454. if (this._startingProcessingFilesCallback)
  54455. this._startingProcessingFilesCallback();
  54456. // Handling data transfer via drag'n'drop
  54457. if (event && event.dataTransfer && event.dataTransfer.files) {
  54458. this._filesToLoad = event.dataTransfer.files;
  54459. }
  54460. // Handling files from input files
  54461. if (event && event.target && event.target.files) {
  54462. this._filesToLoad = event.target.files;
  54463. }
  54464. if (this._filesToLoad && this._filesToLoad.length > 0) {
  54465. var files_1 = new Array();
  54466. var folders = [];
  54467. var items = event.dataTransfer ? event.dataTransfer.items : null;
  54468. for (var i = 0; i < this._filesToLoad.length; i++) {
  54469. var fileToLoad = this._filesToLoad[i];
  54470. var name_1 = fileToLoad.name.toLowerCase();
  54471. var entry = void 0;
  54472. fileToLoad.correctName = name_1;
  54473. if (items) {
  54474. var item = items[i];
  54475. if (item.getAsEntry) {
  54476. entry = item.getAsEntry();
  54477. }
  54478. else if (item.webkitGetAsEntry) {
  54479. entry = item.webkitGetAsEntry();
  54480. }
  54481. }
  54482. if (!entry) {
  54483. files_1.push(fileToLoad);
  54484. }
  54485. else {
  54486. if (entry.isDirectory) {
  54487. folders.push(entry);
  54488. }
  54489. else {
  54490. files_1.push(fileToLoad);
  54491. }
  54492. }
  54493. }
  54494. if (folders.length === 0) {
  54495. this._processFiles(files_1);
  54496. this._processReload();
  54497. }
  54498. else {
  54499. var remaining = { count: folders.length };
  54500. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  54501. var folder = folders_1[_i];
  54502. this._traverseFolder(folder, files_1, remaining, function () {
  54503. _this._processFiles(files_1);
  54504. if (remaining.count === 0) {
  54505. _this._processReload();
  54506. }
  54507. });
  54508. }
  54509. }
  54510. }
  54511. };
  54512. FilesInput.prototype._processReload = function () {
  54513. if (this._onReloadCallback) {
  54514. this._onReloadCallback(this._sceneFileToLoad);
  54515. }
  54516. else {
  54517. this.reload();
  54518. }
  54519. };
  54520. FilesInput.prototype.reload = function () {
  54521. var _this = this;
  54522. // If a scene file has been provided
  54523. if (this._sceneFileToLoad) {
  54524. if (this._currentScene) {
  54525. if (BABYLON.Tools.errorsCount > 0) {
  54526. BABYLON.Tools.ClearLogCache();
  54527. }
  54528. this._engine.stopRenderLoop();
  54529. this._currentScene.dispose();
  54530. }
  54531. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  54532. _this._currentScene = newScene;
  54533. if (_this._sceneLoadedCallback) {
  54534. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  54535. }
  54536. // Wait for textures and shaders to be ready
  54537. _this._currentScene.executeWhenReady(function () {
  54538. _this._engine.runRenderLoop(function () {
  54539. _this.renderFunction();
  54540. });
  54541. });
  54542. }, function (progress) {
  54543. if (_this._progressCallback) {
  54544. _this._progressCallback(progress);
  54545. }
  54546. }, function (scene, message) {
  54547. _this._currentScene = scene;
  54548. if (_this._errorCallback) {
  54549. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  54550. }
  54551. });
  54552. }
  54553. else {
  54554. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  54555. }
  54556. };
  54557. FilesInput.FilesToLoad = {};
  54558. return FilesInput;
  54559. }());
  54560. BABYLON.FilesInput = FilesInput;
  54561. })(BABYLON || (BABYLON = {}));
  54562. //# sourceMappingURL=babylon.filesInput.js.map
  54563. var BABYLON;
  54564. (function (BABYLON) {
  54565. /**
  54566. * This class implement a typical dictionary using a string as key and the generic type T as value.
  54567. * The underlying implementation relies on an associative array to ensure the best performances.
  54568. * The value can be anything including 'null' but except 'undefined'
  54569. */
  54570. var StringDictionary = /** @class */ (function () {
  54571. function StringDictionary() {
  54572. this._count = 0;
  54573. this._data = {};
  54574. }
  54575. /**
  54576. * This will clear this dictionary and copy the content from the 'source' one.
  54577. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  54578. * @param source the dictionary to take the content from and copy to this dictionary
  54579. */
  54580. StringDictionary.prototype.copyFrom = function (source) {
  54581. var _this = this;
  54582. this.clear();
  54583. source.forEach(function (t, v) { return _this.add(t, v); });
  54584. };
  54585. /**
  54586. * Get a value based from its key
  54587. * @param key the given key to get the matching value from
  54588. * @return the value if found, otherwise undefined is returned
  54589. */
  54590. StringDictionary.prototype.get = function (key) {
  54591. var val = this._data[key];
  54592. if (val !== undefined) {
  54593. return val;
  54594. }
  54595. return undefined;
  54596. };
  54597. /**
  54598. * Get a value from its key or add it if it doesn't exist.
  54599. * This method will ensure you that a given key/data will be present in the dictionary.
  54600. * @param key the given key to get the matching value from
  54601. * @param factory the factory that will create the value if the key is not present in the dictionary.
  54602. * The factory will only be invoked if there's no data for the given key.
  54603. * @return the value corresponding to the key.
  54604. */
  54605. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  54606. var val = this.get(key);
  54607. if (val !== undefined) {
  54608. return val;
  54609. }
  54610. val = factory(key);
  54611. if (val) {
  54612. this.add(key, val);
  54613. }
  54614. return val;
  54615. };
  54616. /**
  54617. * Get a value from its key if present in the dictionary otherwise add it
  54618. * @param key the key to get the value from
  54619. * @param val if there's no such key/value pair in the dictionary add it with this value
  54620. * @return the value corresponding to the key
  54621. */
  54622. StringDictionary.prototype.getOrAdd = function (key, val) {
  54623. var curVal = this.get(key);
  54624. if (curVal !== undefined) {
  54625. return curVal;
  54626. }
  54627. this.add(key, val);
  54628. return val;
  54629. };
  54630. /**
  54631. * Check if there's a given key in the dictionary
  54632. * @param key the key to check for
  54633. * @return true if the key is present, false otherwise
  54634. */
  54635. StringDictionary.prototype.contains = function (key) {
  54636. return this._data[key] !== undefined;
  54637. };
  54638. /**
  54639. * Add a new key and its corresponding value
  54640. * @param key the key to add
  54641. * @param value the value corresponding to the key
  54642. * @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
  54643. */
  54644. StringDictionary.prototype.add = function (key, value) {
  54645. if (this._data[key] !== undefined) {
  54646. return false;
  54647. }
  54648. this._data[key] = value;
  54649. ++this._count;
  54650. return true;
  54651. };
  54652. StringDictionary.prototype.set = function (key, value) {
  54653. if (this._data[key] === undefined) {
  54654. return false;
  54655. }
  54656. this._data[key] = value;
  54657. return true;
  54658. };
  54659. /**
  54660. * Get the element of the given key and remove it from the dictionary
  54661. * @param key
  54662. */
  54663. StringDictionary.prototype.getAndRemove = function (key) {
  54664. var val = this.get(key);
  54665. if (val !== undefined) {
  54666. delete this._data[key];
  54667. --this._count;
  54668. return val;
  54669. }
  54670. return null;
  54671. };
  54672. /**
  54673. * Remove a key/value from the dictionary.
  54674. * @param key the key to remove
  54675. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  54676. */
  54677. StringDictionary.prototype.remove = function (key) {
  54678. if (this.contains(key)) {
  54679. delete this._data[key];
  54680. --this._count;
  54681. return true;
  54682. }
  54683. return false;
  54684. };
  54685. /**
  54686. * Clear the whole content of the dictionary
  54687. */
  54688. StringDictionary.prototype.clear = function () {
  54689. this._data = {};
  54690. this._count = 0;
  54691. };
  54692. Object.defineProperty(StringDictionary.prototype, "count", {
  54693. get: function () {
  54694. return this._count;
  54695. },
  54696. enumerable: true,
  54697. configurable: true
  54698. });
  54699. /**
  54700. * Execute a callback on each key/val of the dictionary.
  54701. * Note that you can remove any element in this dictionary in the callback implementation
  54702. * @param callback the callback to execute on a given key/value pair
  54703. */
  54704. StringDictionary.prototype.forEach = function (callback) {
  54705. for (var cur in this._data) {
  54706. var val = this._data[cur];
  54707. callback(cur, val);
  54708. }
  54709. };
  54710. /**
  54711. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  54712. * If the callback returns null or undefined the method will iterate to the next key/value pair
  54713. * Note that you can remove any element in this dictionary in the callback implementation
  54714. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  54715. */
  54716. StringDictionary.prototype.first = function (callback) {
  54717. for (var cur in this._data) {
  54718. var val = this._data[cur];
  54719. var res = callback(cur, val);
  54720. if (res) {
  54721. return res;
  54722. }
  54723. }
  54724. return null;
  54725. };
  54726. return StringDictionary;
  54727. }());
  54728. BABYLON.StringDictionary = StringDictionary;
  54729. })(BABYLON || (BABYLON = {}));
  54730. //# sourceMappingURL=babylon.stringDictionary.js.map
  54731. var BABYLON;
  54732. (function (BABYLON) {
  54733. var Tags = /** @class */ (function () {
  54734. function Tags() {
  54735. }
  54736. Tags.EnableFor = function (obj) {
  54737. obj._tags = obj._tags || {};
  54738. obj.hasTags = function () {
  54739. return Tags.HasTags(obj);
  54740. };
  54741. obj.addTags = function (tagsString) {
  54742. return Tags.AddTagsTo(obj, tagsString);
  54743. };
  54744. obj.removeTags = function (tagsString) {
  54745. return Tags.RemoveTagsFrom(obj, tagsString);
  54746. };
  54747. obj.matchesTagsQuery = function (tagsQuery) {
  54748. return Tags.MatchesQuery(obj, tagsQuery);
  54749. };
  54750. };
  54751. Tags.DisableFor = function (obj) {
  54752. delete obj._tags;
  54753. delete obj.hasTags;
  54754. delete obj.addTags;
  54755. delete obj.removeTags;
  54756. delete obj.matchesTagsQuery;
  54757. };
  54758. Tags.HasTags = function (obj) {
  54759. if (!obj._tags) {
  54760. return false;
  54761. }
  54762. return !BABYLON.Tools.IsEmpty(obj._tags);
  54763. };
  54764. Tags.GetTags = function (obj, asString) {
  54765. if (asString === void 0) { asString = true; }
  54766. if (!obj._tags) {
  54767. return null;
  54768. }
  54769. if (asString) {
  54770. var tagsArray = [];
  54771. for (var tag in obj._tags) {
  54772. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  54773. tagsArray.push(tag);
  54774. }
  54775. }
  54776. return tagsArray.join(" ");
  54777. }
  54778. else {
  54779. return obj._tags;
  54780. }
  54781. };
  54782. // the tags 'true' and 'false' are reserved and cannot be used as tags
  54783. // a tag cannot start with '||', '&&', and '!'
  54784. // it cannot contain whitespaces
  54785. Tags.AddTagsTo = function (obj, tagsString) {
  54786. if (!tagsString) {
  54787. return;
  54788. }
  54789. if (typeof tagsString !== "string") {
  54790. return;
  54791. }
  54792. var tags = tagsString.split(" ");
  54793. tags.forEach(function (tag, index, array) {
  54794. Tags._AddTagTo(obj, tag);
  54795. });
  54796. };
  54797. Tags._AddTagTo = function (obj, tag) {
  54798. tag = tag.trim();
  54799. if (tag === "" || tag === "true" || tag === "false") {
  54800. return;
  54801. }
  54802. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  54803. return;
  54804. }
  54805. Tags.EnableFor(obj);
  54806. obj._tags[tag] = true;
  54807. };
  54808. Tags.RemoveTagsFrom = function (obj, tagsString) {
  54809. if (!Tags.HasTags(obj)) {
  54810. return;
  54811. }
  54812. var tags = tagsString.split(" ");
  54813. for (var t in tags) {
  54814. Tags._RemoveTagFrom(obj, tags[t]);
  54815. }
  54816. };
  54817. Tags._RemoveTagFrom = function (obj, tag) {
  54818. delete obj._tags[tag];
  54819. };
  54820. Tags.MatchesQuery = function (obj, tagsQuery) {
  54821. if (tagsQuery === undefined) {
  54822. return true;
  54823. }
  54824. if (tagsQuery === "") {
  54825. return Tags.HasTags(obj);
  54826. }
  54827. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  54828. };
  54829. return Tags;
  54830. }());
  54831. BABYLON.Tags = Tags;
  54832. })(BABYLON || (BABYLON = {}));
  54833. //# sourceMappingURL=babylon.tags.js.map
  54834. var BABYLON;
  54835. (function (BABYLON) {
  54836. var Internals;
  54837. (function (Internals) {
  54838. var AndOrNotEvaluator = /** @class */ (function () {
  54839. function AndOrNotEvaluator() {
  54840. }
  54841. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  54842. if (!query.match(/\([^\(\)]*\)/g)) {
  54843. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  54844. }
  54845. else {
  54846. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  54847. // remove parenthesis
  54848. r = r.slice(1, r.length - 1);
  54849. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  54850. });
  54851. }
  54852. if (query === "true") {
  54853. return true;
  54854. }
  54855. if (query === "false") {
  54856. return false;
  54857. }
  54858. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  54859. };
  54860. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  54861. evaluateCallback = evaluateCallback || (function (r) {
  54862. return r === "true" ? true : false;
  54863. });
  54864. var result;
  54865. var or = parenthesisContent.split("||");
  54866. for (var i in or) {
  54867. if (or.hasOwnProperty(i)) {
  54868. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  54869. var and = ori.split("&&");
  54870. if (and.length > 1) {
  54871. for (var j = 0; j < and.length; ++j) {
  54872. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  54873. if (andj !== "true" && andj !== "false") {
  54874. if (andj[0] === "!") {
  54875. result = !evaluateCallback(andj.substring(1));
  54876. }
  54877. else {
  54878. result = evaluateCallback(andj);
  54879. }
  54880. }
  54881. else {
  54882. result = andj === "true" ? true : false;
  54883. }
  54884. if (!result) {
  54885. ori = "false";
  54886. break;
  54887. }
  54888. }
  54889. }
  54890. if (result || ori === "true") {
  54891. result = true;
  54892. break;
  54893. }
  54894. // result equals false (or undefined)
  54895. if (ori !== "true" && ori !== "false") {
  54896. if (ori[0] === "!") {
  54897. result = !evaluateCallback(ori.substring(1));
  54898. }
  54899. else {
  54900. result = evaluateCallback(ori);
  54901. }
  54902. }
  54903. else {
  54904. result = ori === "true" ? true : false;
  54905. }
  54906. }
  54907. }
  54908. // the whole parenthesis scope is replaced by 'true' or 'false'
  54909. return result ? "true" : "false";
  54910. };
  54911. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  54912. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  54913. // remove whitespaces
  54914. r = r.replace(/[\s]/g, function () { return ""; });
  54915. return r.length % 2 ? "!" : "";
  54916. });
  54917. booleanString = booleanString.trim();
  54918. if (booleanString === "!true") {
  54919. booleanString = "false";
  54920. }
  54921. else if (booleanString === "!false") {
  54922. booleanString = "true";
  54923. }
  54924. return booleanString;
  54925. };
  54926. return AndOrNotEvaluator;
  54927. }());
  54928. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  54929. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54930. })(BABYLON || (BABYLON = {}));
  54931. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  54932. var BABYLON;
  54933. (function (BABYLON) {
  54934. var Database = /** @class */ (function () {
  54935. function Database(urlToScene, callbackManifestChecked) {
  54936. // Handling various flavors of prefixed version of IndexedDB
  54937. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  54938. this.callbackManifestChecked = callbackManifestChecked;
  54939. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  54940. this.db = null;
  54941. this._enableSceneOffline = false;
  54942. this._enableTexturesOffline = false;
  54943. this.manifestVersionFound = 0;
  54944. this.mustUpdateRessources = false;
  54945. this.hasReachedQuota = false;
  54946. if (!Database.IDBStorageEnabled) {
  54947. this.callbackManifestChecked(true);
  54948. }
  54949. else {
  54950. this.checkManifestFile();
  54951. }
  54952. }
  54953. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  54954. get: function () {
  54955. return this._enableSceneOffline;
  54956. },
  54957. enumerable: true,
  54958. configurable: true
  54959. });
  54960. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  54961. get: function () {
  54962. return this._enableTexturesOffline;
  54963. },
  54964. enumerable: true,
  54965. configurable: true
  54966. });
  54967. Database.prototype.checkManifestFile = function () {
  54968. var _this = this;
  54969. var noManifestFile = function () {
  54970. _this._enableSceneOffline = false;
  54971. _this._enableTexturesOffline = false;
  54972. _this.callbackManifestChecked(false);
  54973. };
  54974. var timeStampUsed = false;
  54975. var manifestURL = this.currentSceneUrl + ".manifest";
  54976. var xhr = new XMLHttpRequest();
  54977. if (navigator.onLine) {
  54978. // Adding a timestamp to by-pass browsers' cache
  54979. timeStampUsed = true;
  54980. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  54981. }
  54982. xhr.open("GET", manifestURL, true);
  54983. xhr.addEventListener("load", function () {
  54984. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  54985. try {
  54986. var manifestFile = JSON.parse(xhr.response);
  54987. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  54988. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  54989. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  54990. _this.manifestVersionFound = manifestFile.version;
  54991. }
  54992. if (_this.callbackManifestChecked) {
  54993. _this.callbackManifestChecked(true);
  54994. }
  54995. }
  54996. catch (ex) {
  54997. noManifestFile();
  54998. }
  54999. }
  55000. else {
  55001. noManifestFile();
  55002. }
  55003. }, false);
  55004. xhr.addEventListener("error", function (event) {
  55005. if (timeStampUsed) {
  55006. timeStampUsed = false;
  55007. // Let's retry without the timeStamp
  55008. // It could fail when coupled with HTML5 Offline API
  55009. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  55010. xhr.open("GET", retryManifestURL, true);
  55011. xhr.send();
  55012. }
  55013. else {
  55014. noManifestFile();
  55015. }
  55016. }, false);
  55017. try {
  55018. xhr.send();
  55019. }
  55020. catch (ex) {
  55021. BABYLON.Tools.Error("Error on XHR send request.");
  55022. this.callbackManifestChecked(false);
  55023. }
  55024. };
  55025. Database.prototype.openAsync = function (successCallback, errorCallback) {
  55026. var _this = this;
  55027. var handleError = function () {
  55028. _this.isSupported = false;
  55029. if (errorCallback)
  55030. errorCallback();
  55031. };
  55032. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  55033. // Your browser doesn't support IndexedDB
  55034. this.isSupported = false;
  55035. if (errorCallback)
  55036. errorCallback();
  55037. }
  55038. else {
  55039. // If the DB hasn't been opened or created yet
  55040. if (!this.db) {
  55041. this.hasReachedQuota = false;
  55042. this.isSupported = true;
  55043. var request = this.idbFactory.open("babylonjs", 1);
  55044. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  55045. request.onerror = function (event) {
  55046. handleError();
  55047. };
  55048. // executes when a version change transaction cannot complete due to other active transactions
  55049. request.onblocked = function (event) {
  55050. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  55051. handleError();
  55052. };
  55053. // DB has been opened successfully
  55054. request.onsuccess = function (event) {
  55055. _this.db = request.result;
  55056. successCallback();
  55057. };
  55058. // Initialization of the DB. Creating Scenes & Textures stores
  55059. request.onupgradeneeded = function (event) {
  55060. _this.db = (event.target).result;
  55061. if (_this.db) {
  55062. try {
  55063. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  55064. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  55065. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  55066. }
  55067. catch (ex) {
  55068. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  55069. handleError();
  55070. }
  55071. }
  55072. };
  55073. }
  55074. else {
  55075. if (successCallback)
  55076. successCallback();
  55077. }
  55078. }
  55079. };
  55080. Database.prototype.loadImageFromDB = function (url, image) {
  55081. var _this = this;
  55082. var completeURL = Database.ReturnFullUrlLocation(url);
  55083. var saveAndLoadImage = function () {
  55084. if (!_this.hasReachedQuota && _this.db !== null) {
  55085. // the texture is not yet in the DB, let's try to save it
  55086. _this._saveImageIntoDBAsync(completeURL, image);
  55087. }
  55088. else {
  55089. image.src = url;
  55090. }
  55091. };
  55092. if (!this.mustUpdateRessources) {
  55093. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  55094. }
  55095. else {
  55096. saveAndLoadImage();
  55097. }
  55098. };
  55099. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  55100. if (this.isSupported && this.db !== null) {
  55101. var texture;
  55102. var transaction = this.db.transaction(["textures"]);
  55103. transaction.onabort = function (event) {
  55104. image.src = url;
  55105. };
  55106. transaction.oncomplete = function (event) {
  55107. var blobTextureURL;
  55108. if (texture) {
  55109. var URL = window.URL || window.webkitURL;
  55110. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  55111. image.onerror = function () {
  55112. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  55113. image.src = url;
  55114. };
  55115. image.src = blobTextureURL;
  55116. }
  55117. else {
  55118. notInDBCallback();
  55119. }
  55120. };
  55121. var getRequest = transaction.objectStore("textures").get(url);
  55122. getRequest.onsuccess = function (event) {
  55123. texture = (event.target).result;
  55124. };
  55125. getRequest.onerror = function (event) {
  55126. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  55127. image.src = url;
  55128. };
  55129. }
  55130. else {
  55131. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  55132. image.src = url;
  55133. }
  55134. };
  55135. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  55136. var _this = this;
  55137. if (this.isSupported) {
  55138. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  55139. var generateBlobUrl = function () {
  55140. var blobTextureURL;
  55141. if (blob) {
  55142. var URL = window.URL || window.webkitURL;
  55143. try {
  55144. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  55145. }
  55146. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  55147. catch (ex) {
  55148. blobTextureURL = URL.createObjectURL(blob);
  55149. }
  55150. }
  55151. if (blobTextureURL) {
  55152. image.src = blobTextureURL;
  55153. }
  55154. };
  55155. if (Database.IsUASupportingBlobStorage) {
  55156. var xhr = new XMLHttpRequest(), blob;
  55157. xhr.open("GET", url, true);
  55158. xhr.responseType = "blob";
  55159. xhr.addEventListener("load", function () {
  55160. if (xhr.status === 200 && _this.db) {
  55161. // Blob as response (XHR2)
  55162. blob = xhr.response;
  55163. var transaction = _this.db.transaction(["textures"], "readwrite");
  55164. // the transaction could abort because of a QuotaExceededError error
  55165. transaction.onabort = function (event) {
  55166. try {
  55167. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  55168. var srcElement = (event.srcElement || event.target);
  55169. var error = srcElement.error;
  55170. if (error && error.name === "QuotaExceededError") {
  55171. _this.hasReachedQuota = true;
  55172. }
  55173. }
  55174. catch (ex) { }
  55175. generateBlobUrl();
  55176. };
  55177. transaction.oncomplete = function (event) {
  55178. generateBlobUrl();
  55179. };
  55180. var newTexture = { textureUrl: url, data: blob };
  55181. try {
  55182. // Put the blob into the dabase
  55183. var addRequest = transaction.objectStore("textures").put(newTexture);
  55184. addRequest.onsuccess = function (event) {
  55185. };
  55186. addRequest.onerror = function (event) {
  55187. generateBlobUrl();
  55188. };
  55189. }
  55190. catch (ex) {
  55191. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  55192. if (ex.code === 25) {
  55193. Database.IsUASupportingBlobStorage = false;
  55194. }
  55195. image.src = url;
  55196. }
  55197. }
  55198. else {
  55199. image.src = url;
  55200. }
  55201. }, false);
  55202. xhr.addEventListener("error", function (event) {
  55203. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  55204. image.src = url;
  55205. }, false);
  55206. xhr.send();
  55207. }
  55208. else {
  55209. image.src = url;
  55210. }
  55211. }
  55212. else {
  55213. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  55214. image.src = url;
  55215. }
  55216. };
  55217. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  55218. var _this = this;
  55219. var updateVersion = function () {
  55220. // the version is not yet in the DB or we need to update it
  55221. _this._saveVersionIntoDBAsync(url, versionLoaded);
  55222. };
  55223. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  55224. };
  55225. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  55226. var _this = this;
  55227. if (this.isSupported && this.db) {
  55228. var version;
  55229. try {
  55230. var transaction = this.db.transaction(["versions"]);
  55231. transaction.oncomplete = function (event) {
  55232. if (version) {
  55233. // If the version in the JSON file is > than the version in DB
  55234. if (_this.manifestVersionFound > version.data) {
  55235. _this.mustUpdateRessources = true;
  55236. updateInDBCallback();
  55237. }
  55238. else {
  55239. callback(version.data);
  55240. }
  55241. }
  55242. else {
  55243. _this.mustUpdateRessources = true;
  55244. updateInDBCallback();
  55245. }
  55246. };
  55247. transaction.onabort = function (event) {
  55248. callback(-1);
  55249. };
  55250. var getRequest = transaction.objectStore("versions").get(url);
  55251. getRequest.onsuccess = function (event) {
  55252. version = (event.target).result;
  55253. };
  55254. getRequest.onerror = function (event) {
  55255. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  55256. callback(-1);
  55257. };
  55258. }
  55259. catch (ex) {
  55260. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  55261. callback(-1);
  55262. }
  55263. }
  55264. else {
  55265. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  55266. callback(-1);
  55267. }
  55268. };
  55269. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  55270. var _this = this;
  55271. if (this.isSupported && !this.hasReachedQuota && this.db) {
  55272. try {
  55273. // Open a transaction to the database
  55274. var transaction = this.db.transaction(["versions"], "readwrite");
  55275. // the transaction could abort because of a QuotaExceededError error
  55276. transaction.onabort = function (event) {
  55277. try {
  55278. var error = event.srcElement['error'];
  55279. if (error && error.name === "QuotaExceededError") {
  55280. _this.hasReachedQuota = true;
  55281. }
  55282. }
  55283. catch (ex) { }
  55284. callback(-1);
  55285. };
  55286. transaction.oncomplete = function (event) {
  55287. callback(_this.manifestVersionFound);
  55288. };
  55289. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  55290. // Put the scene into the database
  55291. var addRequest = transaction.objectStore("versions").put(newVersion);
  55292. addRequest.onsuccess = function (event) {
  55293. };
  55294. addRequest.onerror = function (event) {
  55295. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  55296. };
  55297. }
  55298. catch (ex) {
  55299. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  55300. callback(-1);
  55301. }
  55302. }
  55303. else {
  55304. callback(-1);
  55305. }
  55306. };
  55307. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  55308. var _this = this;
  55309. var completeUrl = Database.ReturnFullUrlLocation(url);
  55310. var saveAndLoadFile = function () {
  55311. // the scene is not yet in the DB, let's try to save it
  55312. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  55313. };
  55314. this._checkVersionFromDB(completeUrl, function (version) {
  55315. if (version !== -1) {
  55316. if (!_this.mustUpdateRessources) {
  55317. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  55318. }
  55319. else {
  55320. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  55321. }
  55322. }
  55323. else {
  55324. if (errorCallback) {
  55325. errorCallback();
  55326. }
  55327. }
  55328. });
  55329. };
  55330. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  55331. if (this.isSupported && this.db) {
  55332. var targetStore;
  55333. if (url.indexOf(".babylon") !== -1) {
  55334. targetStore = "scenes";
  55335. }
  55336. else {
  55337. targetStore = "textures";
  55338. }
  55339. var file;
  55340. var transaction = this.db.transaction([targetStore]);
  55341. transaction.oncomplete = function (event) {
  55342. if (file) {
  55343. callback(file.data);
  55344. }
  55345. else {
  55346. notInDBCallback();
  55347. }
  55348. };
  55349. transaction.onabort = function (event) {
  55350. notInDBCallback();
  55351. };
  55352. var getRequest = transaction.objectStore(targetStore).get(url);
  55353. getRequest.onsuccess = function (event) {
  55354. file = (event.target).result;
  55355. };
  55356. getRequest.onerror = function (event) {
  55357. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  55358. notInDBCallback();
  55359. };
  55360. }
  55361. else {
  55362. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  55363. callback();
  55364. }
  55365. };
  55366. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  55367. var _this = this;
  55368. if (this.isSupported) {
  55369. var targetStore;
  55370. if (url.indexOf(".babylon") !== -1) {
  55371. targetStore = "scenes";
  55372. }
  55373. else {
  55374. targetStore = "textures";
  55375. }
  55376. // Create XHR
  55377. var xhr = new XMLHttpRequest();
  55378. var fileData;
  55379. xhr.open("GET", url, true);
  55380. if (useArrayBuffer) {
  55381. xhr.responseType = "arraybuffer";
  55382. }
  55383. if (progressCallback) {
  55384. xhr.onprogress = progressCallback;
  55385. }
  55386. xhr.addEventListener("load", function () {
  55387. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  55388. // Blob as response (XHR2)
  55389. //fileData = xhr.responseText;
  55390. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  55391. if (!_this.hasReachedQuota && _this.db) {
  55392. // Open a transaction to the database
  55393. var transaction = _this.db.transaction([targetStore], "readwrite");
  55394. // the transaction could abort because of a QuotaExceededError error
  55395. transaction.onabort = function (event) {
  55396. try {
  55397. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  55398. var error = event.srcElement['error'];
  55399. if (error && error.name === "QuotaExceededError") {
  55400. _this.hasReachedQuota = true;
  55401. }
  55402. }
  55403. catch (ex) { }
  55404. callback(fileData);
  55405. };
  55406. transaction.oncomplete = function (event) {
  55407. callback(fileData);
  55408. };
  55409. var newFile;
  55410. if (targetStore === "scenes") {
  55411. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  55412. }
  55413. else {
  55414. newFile = { textureUrl: url, data: fileData };
  55415. }
  55416. try {
  55417. // Put the scene into the database
  55418. var addRequest = transaction.objectStore(targetStore).put(newFile);
  55419. addRequest.onsuccess = function (event) {
  55420. };
  55421. addRequest.onerror = function (event) {
  55422. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  55423. };
  55424. }
  55425. catch (ex) {
  55426. callback(fileData);
  55427. }
  55428. }
  55429. else {
  55430. callback(fileData);
  55431. }
  55432. }
  55433. else {
  55434. callback();
  55435. }
  55436. }, false);
  55437. xhr.addEventListener("error", function (event) {
  55438. BABYLON.Tools.Error("error on XHR request.");
  55439. callback();
  55440. }, false);
  55441. xhr.send();
  55442. }
  55443. else {
  55444. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  55445. callback();
  55446. }
  55447. };
  55448. Database.IsUASupportingBlobStorage = true;
  55449. Database.IDBStorageEnabled = true;
  55450. Database.parseURL = function (url) {
  55451. var a = document.createElement('a');
  55452. a.href = url;
  55453. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  55454. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  55455. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  55456. return absLocation;
  55457. };
  55458. Database.ReturnFullUrlLocation = function (url) {
  55459. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  55460. return (Database.parseURL(window.location.href) + url);
  55461. }
  55462. else {
  55463. return url;
  55464. }
  55465. };
  55466. return Database;
  55467. }());
  55468. BABYLON.Database = Database;
  55469. })(BABYLON || (BABYLON = {}));
  55470. //# sourceMappingURL=babylon.database.js.map
  55471. var BABYLON;
  55472. (function (BABYLON) {
  55473. var FresnelParameters = /** @class */ (function () {
  55474. function FresnelParameters() {
  55475. this._isEnabled = true;
  55476. this.leftColor = BABYLON.Color3.White();
  55477. this.rightColor = BABYLON.Color3.Black();
  55478. this.bias = 0;
  55479. this.power = 1;
  55480. }
  55481. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  55482. get: function () {
  55483. return this._isEnabled;
  55484. },
  55485. set: function (value) {
  55486. if (this._isEnabled === value) {
  55487. return;
  55488. }
  55489. this._isEnabled = value;
  55490. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  55491. },
  55492. enumerable: true,
  55493. configurable: true
  55494. });
  55495. FresnelParameters.prototype.clone = function () {
  55496. var newFresnelParameters = new FresnelParameters();
  55497. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  55498. return newFresnelParameters;
  55499. };
  55500. FresnelParameters.prototype.serialize = function () {
  55501. var serializationObject = {};
  55502. serializationObject.isEnabled = this.isEnabled;
  55503. serializationObject.leftColor = this.leftColor;
  55504. serializationObject.rightColor = this.rightColor;
  55505. serializationObject.bias = this.bias;
  55506. serializationObject.power = this.power;
  55507. return serializationObject;
  55508. };
  55509. FresnelParameters.Parse = function (parsedFresnelParameters) {
  55510. var fresnelParameters = new FresnelParameters();
  55511. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  55512. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  55513. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  55514. fresnelParameters.bias = parsedFresnelParameters.bias;
  55515. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  55516. return fresnelParameters;
  55517. };
  55518. return FresnelParameters;
  55519. }());
  55520. BABYLON.FresnelParameters = FresnelParameters;
  55521. })(BABYLON || (BABYLON = {}));
  55522. //# sourceMappingURL=babylon.fresnelParameters.js.map
  55523. var BABYLON;
  55524. (function (BABYLON) {
  55525. var MultiMaterial = /** @class */ (function (_super) {
  55526. __extends(MultiMaterial, _super);
  55527. function MultiMaterial(name, scene) {
  55528. var _this = _super.call(this, name, scene, true) || this;
  55529. scene.multiMaterials.push(_this);
  55530. _this.subMaterials = new Array();
  55531. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  55532. return _this;
  55533. }
  55534. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  55535. get: function () {
  55536. return this._subMaterials;
  55537. },
  55538. set: function (value) {
  55539. this._subMaterials = value;
  55540. this._hookArray(value);
  55541. },
  55542. enumerable: true,
  55543. configurable: true
  55544. });
  55545. MultiMaterial.prototype._hookArray = function (array) {
  55546. var _this = this;
  55547. var oldPush = array.push;
  55548. array.push = function () {
  55549. var items = [];
  55550. for (var _i = 0; _i < arguments.length; _i++) {
  55551. items[_i] = arguments[_i];
  55552. }
  55553. var result = oldPush.apply(array, items);
  55554. _this._markAllSubMeshesAsTexturesDirty();
  55555. return result;
  55556. };
  55557. var oldSplice = array.splice;
  55558. array.splice = function (index, deleteCount) {
  55559. var deleted = oldSplice.apply(array, [index, deleteCount]);
  55560. _this._markAllSubMeshesAsTexturesDirty();
  55561. return deleted;
  55562. };
  55563. };
  55564. // Properties
  55565. MultiMaterial.prototype.getSubMaterial = function (index) {
  55566. if (index < 0 || index >= this.subMaterials.length) {
  55567. return this.getScene().defaultMaterial;
  55568. }
  55569. return this.subMaterials[index];
  55570. };
  55571. MultiMaterial.prototype.getActiveTextures = function () {
  55572. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  55573. if (subMaterial) {
  55574. return subMaterial.getActiveTextures();
  55575. }
  55576. else {
  55577. return [];
  55578. }
  55579. }));
  55580. var _a;
  55581. };
  55582. // Methods
  55583. MultiMaterial.prototype.getClassName = function () {
  55584. return "MultiMaterial";
  55585. };
  55586. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  55587. for (var index = 0; index < this.subMaterials.length; index++) {
  55588. var subMaterial = this.subMaterials[index];
  55589. if (subMaterial) {
  55590. if (subMaterial.storeEffectOnSubMeshes) {
  55591. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  55592. return false;
  55593. }
  55594. continue;
  55595. }
  55596. if (!subMaterial.isReady(mesh)) {
  55597. return false;
  55598. }
  55599. }
  55600. }
  55601. return true;
  55602. };
  55603. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  55604. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  55605. for (var index = 0; index < this.subMaterials.length; index++) {
  55606. var subMaterial = null;
  55607. var current = this.subMaterials[index];
  55608. if (cloneChildren && current) {
  55609. subMaterial = current.clone(name + "-" + current.name);
  55610. }
  55611. else {
  55612. subMaterial = this.subMaterials[index];
  55613. }
  55614. newMultiMaterial.subMaterials.push(subMaterial);
  55615. }
  55616. return newMultiMaterial;
  55617. };
  55618. MultiMaterial.prototype.serialize = function () {
  55619. var serializationObject = {};
  55620. serializationObject.name = this.name;
  55621. serializationObject.id = this.id;
  55622. if (BABYLON.Tags) {
  55623. serializationObject.tags = BABYLON.Tags.GetTags(this);
  55624. }
  55625. serializationObject.materials = [];
  55626. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  55627. var subMat = this.subMaterials[matIndex];
  55628. if (subMat) {
  55629. serializationObject.materials.push(subMat.id);
  55630. }
  55631. else {
  55632. serializationObject.materials.push(null);
  55633. }
  55634. }
  55635. return serializationObject;
  55636. };
  55637. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  55638. var scene = this.getScene();
  55639. if (!scene) {
  55640. return;
  55641. }
  55642. var index = scene.multiMaterials.indexOf(this);
  55643. if (index >= 0) {
  55644. scene.multiMaterials.splice(index, 1);
  55645. }
  55646. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  55647. };
  55648. return MultiMaterial;
  55649. }(BABYLON.Material));
  55650. BABYLON.MultiMaterial = MultiMaterial;
  55651. })(BABYLON || (BABYLON = {}));
  55652. //# sourceMappingURL=babylon.multiMaterial.js.map
  55653. var BABYLON;
  55654. (function (BABYLON) {
  55655. var FreeCameraTouchInput = /** @class */ (function () {
  55656. function FreeCameraTouchInput() {
  55657. this._offsetX = null;
  55658. this._offsetY = null;
  55659. this._pointerPressed = new Array();
  55660. this.touchAngularSensibility = 200000.0;
  55661. this.touchMoveSensibility = 250.0;
  55662. }
  55663. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  55664. var _this = this;
  55665. var previousPosition = null;
  55666. if (this._pointerInput === undefined) {
  55667. this._onLostFocus = function (evt) {
  55668. _this._offsetX = null;
  55669. _this._offsetY = null;
  55670. };
  55671. this._pointerInput = function (p, s) {
  55672. var evt = p.event;
  55673. if (evt.pointerType === "mouse") {
  55674. return;
  55675. }
  55676. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  55677. if (!noPreventDefault) {
  55678. evt.preventDefault();
  55679. }
  55680. _this._pointerPressed.push(evt.pointerId);
  55681. if (_this._pointerPressed.length !== 1) {
  55682. return;
  55683. }
  55684. previousPosition = {
  55685. x: evt.clientX,
  55686. y: evt.clientY
  55687. };
  55688. }
  55689. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  55690. if (!noPreventDefault) {
  55691. evt.preventDefault();
  55692. }
  55693. var index = _this._pointerPressed.indexOf(evt.pointerId);
  55694. if (index === -1) {
  55695. return;
  55696. }
  55697. _this._pointerPressed.splice(index, 1);
  55698. if (index != 0) {
  55699. return;
  55700. }
  55701. previousPosition = null;
  55702. _this._offsetX = null;
  55703. _this._offsetY = null;
  55704. }
  55705. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  55706. if (!noPreventDefault) {
  55707. evt.preventDefault();
  55708. }
  55709. if (!previousPosition) {
  55710. return;
  55711. }
  55712. var index = _this._pointerPressed.indexOf(evt.pointerId);
  55713. if (index != 0) {
  55714. return;
  55715. }
  55716. _this._offsetX = evt.clientX - previousPosition.x;
  55717. _this._offsetY = -(evt.clientY - previousPosition.y);
  55718. }
  55719. };
  55720. }
  55721. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  55722. if (this._onLostFocus) {
  55723. element.addEventListener("blur", this._onLostFocus);
  55724. }
  55725. };
  55726. FreeCameraTouchInput.prototype.detachControl = function (element) {
  55727. if (this._pointerInput && element) {
  55728. if (this._observer) {
  55729. this.camera.getScene().onPointerObservable.remove(this._observer);
  55730. this._observer = null;
  55731. }
  55732. if (this._onLostFocus) {
  55733. element.removeEventListener("blur", this._onLostFocus);
  55734. this._onLostFocus = null;
  55735. }
  55736. this._pointerPressed = [];
  55737. this._offsetX = null;
  55738. this._offsetY = null;
  55739. }
  55740. };
  55741. FreeCameraTouchInput.prototype.checkInputs = function () {
  55742. if (this._offsetX && this._offsetY) {
  55743. var camera = this.camera;
  55744. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  55745. if (this._pointerPressed.length > 1) {
  55746. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  55747. }
  55748. else {
  55749. var speed = camera._computeLocalCameraSpeed();
  55750. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  55751. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  55752. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  55753. }
  55754. }
  55755. };
  55756. FreeCameraTouchInput.prototype.getClassName = function () {
  55757. return "FreeCameraTouchInput";
  55758. };
  55759. FreeCameraTouchInput.prototype.getSimpleName = function () {
  55760. return "touch";
  55761. };
  55762. __decorate([
  55763. BABYLON.serialize()
  55764. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  55765. __decorate([
  55766. BABYLON.serialize()
  55767. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  55768. return FreeCameraTouchInput;
  55769. }());
  55770. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  55771. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  55772. })(BABYLON || (BABYLON = {}));
  55773. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  55774. var BABYLON;
  55775. (function (BABYLON) {
  55776. // We're mainly based on the logic defined into the FreeCamera code
  55777. var TouchCamera = /** @class */ (function (_super) {
  55778. __extends(TouchCamera, _super);
  55779. //-- end properties for backward compatibility for inputs
  55780. function TouchCamera(name, position, scene) {
  55781. var _this = _super.call(this, name, position, scene) || this;
  55782. _this.inputs.addTouch();
  55783. _this._setupInputs();
  55784. return _this;
  55785. }
  55786. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  55787. //-- Begin properties for backward compatibility for inputs
  55788. get: function () {
  55789. var touch = this.inputs.attached["touch"];
  55790. if (touch)
  55791. return touch.touchAngularSensibility;
  55792. return 0;
  55793. },
  55794. set: function (value) {
  55795. var touch = this.inputs.attached["touch"];
  55796. if (touch)
  55797. touch.touchAngularSensibility = value;
  55798. },
  55799. enumerable: true,
  55800. configurable: true
  55801. });
  55802. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  55803. get: function () {
  55804. var touch = this.inputs.attached["touch"];
  55805. if (touch)
  55806. return touch.touchMoveSensibility;
  55807. return 0;
  55808. },
  55809. set: function (value) {
  55810. var touch = this.inputs.attached["touch"];
  55811. if (touch)
  55812. touch.touchMoveSensibility = value;
  55813. },
  55814. enumerable: true,
  55815. configurable: true
  55816. });
  55817. TouchCamera.prototype.getClassName = function () {
  55818. return "TouchCamera";
  55819. };
  55820. TouchCamera.prototype._setupInputs = function () {
  55821. var mouse = this.inputs.attached["mouse"];
  55822. if (mouse) {
  55823. mouse.touchEnabled = false;
  55824. }
  55825. };
  55826. return TouchCamera;
  55827. }(BABYLON.FreeCamera));
  55828. BABYLON.TouchCamera = TouchCamera;
  55829. })(BABYLON || (BABYLON = {}));
  55830. //# sourceMappingURL=babylon.touchCamera.js.map
  55831. var BABYLON;
  55832. (function (BABYLON) {
  55833. var ProceduralTexture = /** @class */ (function (_super) {
  55834. __extends(ProceduralTexture, _super);
  55835. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  55836. if (fallbackTexture === void 0) { fallbackTexture = null; }
  55837. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55838. if (isCube === void 0) { isCube = false; }
  55839. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  55840. _this.isCube = isCube;
  55841. _this.isEnabled = true;
  55842. _this._currentRefreshId = -1;
  55843. _this._refreshRate = 1;
  55844. _this._vertexBuffers = {};
  55845. _this._uniforms = new Array();
  55846. _this._samplers = new Array();
  55847. _this._textures = {};
  55848. _this._floats = {};
  55849. _this._floatsArrays = {};
  55850. _this._colors3 = {};
  55851. _this._colors4 = {};
  55852. _this._vectors2 = {};
  55853. _this._vectors3 = {};
  55854. _this._matrices = {};
  55855. _this._fallbackTextureUsed = false;
  55856. scene._proceduralTextures.push(_this);
  55857. _this._engine = scene.getEngine();
  55858. _this.name = name;
  55859. _this.isRenderTarget = true;
  55860. _this._size = size;
  55861. _this._generateMipMaps = generateMipMaps;
  55862. _this.setFragment(fragment);
  55863. _this._fallbackTexture = fallbackTexture;
  55864. if (isCube) {
  55865. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  55866. _this.setFloat("face", 0);
  55867. }
  55868. else {
  55869. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  55870. }
  55871. // VBO
  55872. var vertices = [];
  55873. vertices.push(1, 1);
  55874. vertices.push(-1, 1);
  55875. vertices.push(-1, -1);
  55876. vertices.push(1, -1);
  55877. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  55878. _this._createIndexBuffer();
  55879. return _this;
  55880. }
  55881. ProceduralTexture.prototype._createIndexBuffer = function () {
  55882. var engine = this._engine;
  55883. // Indices
  55884. var indices = [];
  55885. indices.push(0);
  55886. indices.push(1);
  55887. indices.push(2);
  55888. indices.push(0);
  55889. indices.push(2);
  55890. indices.push(3);
  55891. this._indexBuffer = engine.createIndexBuffer(indices);
  55892. };
  55893. ProceduralTexture.prototype._rebuild = function () {
  55894. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  55895. if (vb) {
  55896. vb._rebuild();
  55897. }
  55898. this._createIndexBuffer();
  55899. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  55900. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  55901. }
  55902. };
  55903. ProceduralTexture.prototype.reset = function () {
  55904. if (this._effect === undefined) {
  55905. return;
  55906. }
  55907. var engine = this._engine;
  55908. engine._releaseEffect(this._effect);
  55909. };
  55910. ProceduralTexture.prototype.isReady = function () {
  55911. var _this = this;
  55912. var engine = this._engine;
  55913. var shaders;
  55914. if (!this._fragment) {
  55915. return false;
  55916. }
  55917. if (this._fallbackTextureUsed) {
  55918. return true;
  55919. }
  55920. if (this._fragment.fragmentElement !== undefined) {
  55921. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  55922. }
  55923. else {
  55924. shaders = { vertex: "procedural", fragment: this._fragment };
  55925. }
  55926. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  55927. _this.releaseInternalTexture();
  55928. if (_this._fallbackTexture) {
  55929. _this._texture = _this._fallbackTexture._texture;
  55930. if (_this._texture) {
  55931. _this._texture.incrementReferences();
  55932. }
  55933. }
  55934. _this._fallbackTextureUsed = true;
  55935. });
  55936. return this._effect.isReady();
  55937. };
  55938. ProceduralTexture.prototype.resetRefreshCounter = function () {
  55939. this._currentRefreshId = -1;
  55940. };
  55941. ProceduralTexture.prototype.setFragment = function (fragment) {
  55942. this._fragment = fragment;
  55943. };
  55944. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  55945. get: function () {
  55946. return this._refreshRate;
  55947. },
  55948. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  55949. set: function (value) {
  55950. this._refreshRate = value;
  55951. this.resetRefreshCounter();
  55952. },
  55953. enumerable: true,
  55954. configurable: true
  55955. });
  55956. ProceduralTexture.prototype._shouldRender = function () {
  55957. if (!this.isEnabled || !this.isReady() || !this._texture) {
  55958. return false;
  55959. }
  55960. if (this._fallbackTextureUsed) {
  55961. return false;
  55962. }
  55963. if (this._currentRefreshId === -1) {
  55964. this._currentRefreshId = 1;
  55965. return true;
  55966. }
  55967. if (this.refreshRate === this._currentRefreshId) {
  55968. this._currentRefreshId = 1;
  55969. return true;
  55970. }
  55971. this._currentRefreshId++;
  55972. return false;
  55973. };
  55974. ProceduralTexture.prototype.getRenderSize = function () {
  55975. return this._size;
  55976. };
  55977. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  55978. if (this._fallbackTextureUsed) {
  55979. return;
  55980. }
  55981. this.releaseInternalTexture();
  55982. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  55983. };
  55984. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  55985. if (this._uniforms.indexOf(uniformName) === -1) {
  55986. this._uniforms.push(uniformName);
  55987. }
  55988. };
  55989. ProceduralTexture.prototype.setTexture = function (name, texture) {
  55990. if (this._samplers.indexOf(name) === -1) {
  55991. this._samplers.push(name);
  55992. }
  55993. this._textures[name] = texture;
  55994. return this;
  55995. };
  55996. ProceduralTexture.prototype.setFloat = function (name, value) {
  55997. this._checkUniform(name);
  55998. this._floats[name] = value;
  55999. return this;
  56000. };
  56001. ProceduralTexture.prototype.setFloats = function (name, value) {
  56002. this._checkUniform(name);
  56003. this._floatsArrays[name] = value;
  56004. return this;
  56005. };
  56006. ProceduralTexture.prototype.setColor3 = function (name, value) {
  56007. this._checkUniform(name);
  56008. this._colors3[name] = value;
  56009. return this;
  56010. };
  56011. ProceduralTexture.prototype.setColor4 = function (name, value) {
  56012. this._checkUniform(name);
  56013. this._colors4[name] = value;
  56014. return this;
  56015. };
  56016. ProceduralTexture.prototype.setVector2 = function (name, value) {
  56017. this._checkUniform(name);
  56018. this._vectors2[name] = value;
  56019. return this;
  56020. };
  56021. ProceduralTexture.prototype.setVector3 = function (name, value) {
  56022. this._checkUniform(name);
  56023. this._vectors3[name] = value;
  56024. return this;
  56025. };
  56026. ProceduralTexture.prototype.setMatrix = function (name, value) {
  56027. this._checkUniform(name);
  56028. this._matrices[name] = value;
  56029. return this;
  56030. };
  56031. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  56032. var scene = this.getScene();
  56033. if (!scene) {
  56034. return;
  56035. }
  56036. var engine = this._engine;
  56037. // Render
  56038. engine.enableEffect(this._effect);
  56039. engine.setState(false);
  56040. // Texture
  56041. for (var name in this._textures) {
  56042. this._effect.setTexture(name, this._textures[name]);
  56043. }
  56044. // Float
  56045. for (name in this._floats) {
  56046. this._effect.setFloat(name, this._floats[name]);
  56047. }
  56048. // Floats
  56049. for (name in this._floatsArrays) {
  56050. this._effect.setArray(name, this._floatsArrays[name]);
  56051. }
  56052. // Color3
  56053. for (name in this._colors3) {
  56054. this._effect.setColor3(name, this._colors3[name]);
  56055. }
  56056. // Color4
  56057. for (name in this._colors4) {
  56058. var color = this._colors4[name];
  56059. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  56060. }
  56061. // Vector2
  56062. for (name in this._vectors2) {
  56063. this._effect.setVector2(name, this._vectors2[name]);
  56064. }
  56065. // Vector3
  56066. for (name in this._vectors3) {
  56067. this._effect.setVector3(name, this._vectors3[name]);
  56068. }
  56069. // Matrix
  56070. for (name in this._matrices) {
  56071. this._effect.setMatrix(name, this._matrices[name]);
  56072. }
  56073. if (!this._texture) {
  56074. return;
  56075. }
  56076. if (this.isCube) {
  56077. for (var face = 0; face < 6; face++) {
  56078. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  56079. // VBOs
  56080. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  56081. this._effect.setFloat("face", face);
  56082. // Clear
  56083. engine.clear(scene.clearColor, true, true, true);
  56084. // Draw order
  56085. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  56086. // Mipmaps
  56087. if (face === 5) {
  56088. engine.generateMipMapsForCubemap(this._texture);
  56089. }
  56090. }
  56091. }
  56092. else {
  56093. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  56094. // VBOs
  56095. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  56096. // Clear
  56097. engine.clear(scene.clearColor, true, true, true);
  56098. // Draw order
  56099. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  56100. }
  56101. // Unbind
  56102. engine.unBindFramebuffer(this._texture, this.isCube);
  56103. if (this.onGenerated) {
  56104. this.onGenerated();
  56105. }
  56106. };
  56107. ProceduralTexture.prototype.clone = function () {
  56108. var textureSize = this.getSize();
  56109. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  56110. // Base texture
  56111. newTexture.hasAlpha = this.hasAlpha;
  56112. newTexture.level = this.level;
  56113. // RenderTarget Texture
  56114. newTexture.coordinatesMode = this.coordinatesMode;
  56115. return newTexture;
  56116. };
  56117. ProceduralTexture.prototype.dispose = function () {
  56118. var scene = this.getScene();
  56119. if (!scene) {
  56120. return;
  56121. }
  56122. var index = scene._proceduralTextures.indexOf(this);
  56123. if (index >= 0) {
  56124. scene._proceduralTextures.splice(index, 1);
  56125. }
  56126. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  56127. if (vertexBuffer) {
  56128. vertexBuffer.dispose();
  56129. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  56130. }
  56131. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  56132. this._indexBuffer = null;
  56133. }
  56134. _super.prototype.dispose.call(this);
  56135. };
  56136. return ProceduralTexture;
  56137. }(BABYLON.Texture));
  56138. BABYLON.ProceduralTexture = ProceduralTexture;
  56139. })(BABYLON || (BABYLON = {}));
  56140. //# sourceMappingURL=babylon.proceduralTexture.js.map
  56141. var BABYLON;
  56142. (function (BABYLON) {
  56143. var CustomProceduralTexture = /** @class */ (function (_super) {
  56144. __extends(CustomProceduralTexture, _super);
  56145. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  56146. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  56147. _this._animate = true;
  56148. _this._time = 0;
  56149. _this._texturePath = texturePath;
  56150. //Try to load json
  56151. _this.loadJson(texturePath);
  56152. _this.refreshRate = 1;
  56153. return _this;
  56154. }
  56155. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  56156. var _this = this;
  56157. var noConfigFile = function () {
  56158. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  56159. try {
  56160. _this.setFragment(_this._texturePath);
  56161. }
  56162. catch (ex) {
  56163. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  56164. }
  56165. };
  56166. var configFileUrl = jsonUrl + "/config.json";
  56167. var xhr = new XMLHttpRequest();
  56168. xhr.open("GET", configFileUrl, true);
  56169. xhr.addEventListener("load", function () {
  56170. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  56171. try {
  56172. _this._config = JSON.parse(xhr.response);
  56173. _this.updateShaderUniforms();
  56174. _this.updateTextures();
  56175. _this.setFragment(_this._texturePath + "/custom");
  56176. _this._animate = _this._config.animate;
  56177. _this.refreshRate = _this._config.refreshrate;
  56178. }
  56179. catch (ex) {
  56180. noConfigFile();
  56181. }
  56182. }
  56183. else {
  56184. noConfigFile();
  56185. }
  56186. }, false);
  56187. xhr.addEventListener("error", function () {
  56188. noConfigFile();
  56189. }, false);
  56190. try {
  56191. xhr.send();
  56192. }
  56193. catch (ex) {
  56194. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  56195. }
  56196. };
  56197. CustomProceduralTexture.prototype.isReady = function () {
  56198. if (!_super.prototype.isReady.call(this)) {
  56199. return false;
  56200. }
  56201. for (var name in this._textures) {
  56202. var texture = this._textures[name];
  56203. if (!texture.isReady()) {
  56204. return false;
  56205. }
  56206. }
  56207. return true;
  56208. };
  56209. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  56210. var scene = this.getScene();
  56211. if (this._animate && scene) {
  56212. this._time += scene.getAnimationRatio() * 0.03;
  56213. this.updateShaderUniforms();
  56214. }
  56215. _super.prototype.render.call(this, useCameraPostProcess);
  56216. };
  56217. CustomProceduralTexture.prototype.updateTextures = function () {
  56218. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  56219. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  56220. }
  56221. };
  56222. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  56223. if (this._config) {
  56224. for (var j = 0; j < this._config.uniforms.length; j++) {
  56225. var uniform = this._config.uniforms[j];
  56226. switch (uniform.type) {
  56227. case "float":
  56228. this.setFloat(uniform.name, uniform.value);
  56229. break;
  56230. case "color3":
  56231. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  56232. break;
  56233. case "color4":
  56234. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  56235. break;
  56236. case "vector2":
  56237. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  56238. break;
  56239. case "vector3":
  56240. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  56241. break;
  56242. }
  56243. }
  56244. }
  56245. this.setFloat("time", this._time);
  56246. };
  56247. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  56248. get: function () {
  56249. return this._animate;
  56250. },
  56251. set: function (value) {
  56252. this._animate = value;
  56253. },
  56254. enumerable: true,
  56255. configurable: true
  56256. });
  56257. return CustomProceduralTexture;
  56258. }(BABYLON.ProceduralTexture));
  56259. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  56260. })(BABYLON || (BABYLON = {}));
  56261. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  56262. var BABYLON;
  56263. (function (BABYLON) {
  56264. var FreeCameraGamepadInput = /** @class */ (function () {
  56265. function FreeCameraGamepadInput() {
  56266. this.gamepadAngularSensibility = 200;
  56267. this.gamepadMoveSensibility = 40;
  56268. // private members
  56269. this._cameraTransform = BABYLON.Matrix.Identity();
  56270. this._deltaTransform = BABYLON.Vector3.Zero();
  56271. this._vector3 = BABYLON.Vector3.Zero();
  56272. this._vector2 = BABYLON.Vector2.Zero();
  56273. }
  56274. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  56275. var _this = this;
  56276. var manager = this.camera.getScene().gamepadManager;
  56277. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  56278. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  56279. // prioritize XBOX gamepads.
  56280. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  56281. _this.gamepad = gamepad;
  56282. }
  56283. }
  56284. });
  56285. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  56286. if (_this.gamepad === gamepad) {
  56287. _this.gamepad = null;
  56288. }
  56289. });
  56290. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  56291. };
  56292. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  56293. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  56294. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  56295. this.gamepad = null;
  56296. };
  56297. FreeCameraGamepadInput.prototype.checkInputs = function () {
  56298. if (this.gamepad && this.gamepad.leftStick) {
  56299. var camera = this.camera;
  56300. var LSValues = this.gamepad.leftStick;
  56301. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  56302. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  56303. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  56304. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  56305. var RSValues = this.gamepad.rightStick;
  56306. if (RSValues) {
  56307. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  56308. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  56309. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  56310. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  56311. }
  56312. else {
  56313. RSValues = { x: 0, y: 0 };
  56314. }
  56315. if (!camera.rotationQuaternion) {
  56316. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  56317. }
  56318. else {
  56319. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  56320. }
  56321. var speed = camera._computeLocalCameraSpeed() * 50.0;
  56322. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  56323. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  56324. camera.cameraDirection.addInPlace(this._deltaTransform);
  56325. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  56326. camera.cameraRotation.addInPlace(this._vector2);
  56327. }
  56328. };
  56329. FreeCameraGamepadInput.prototype.getClassName = function () {
  56330. return "FreeCameraGamepadInput";
  56331. };
  56332. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  56333. return "gamepad";
  56334. };
  56335. __decorate([
  56336. BABYLON.serialize()
  56337. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  56338. __decorate([
  56339. BABYLON.serialize()
  56340. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  56341. return FreeCameraGamepadInput;
  56342. }());
  56343. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  56344. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  56345. })(BABYLON || (BABYLON = {}));
  56346. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  56347. var BABYLON;
  56348. (function (BABYLON) {
  56349. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  56350. function ArcRotateCameraGamepadInput() {
  56351. this.gamepadRotationSensibility = 80;
  56352. this.gamepadMoveSensibility = 40;
  56353. }
  56354. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  56355. var _this = this;
  56356. var manager = this.camera.getScene().gamepadManager;
  56357. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  56358. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  56359. // prioritize XBOX gamepads.
  56360. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  56361. _this.gamepad = gamepad;
  56362. }
  56363. }
  56364. });
  56365. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  56366. if (_this.gamepad === gamepad) {
  56367. _this.gamepad = null;
  56368. }
  56369. });
  56370. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  56371. };
  56372. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  56373. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  56374. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  56375. this.gamepad = null;
  56376. };
  56377. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  56378. if (this.gamepad) {
  56379. var camera = this.camera;
  56380. var RSValues = this.gamepad.rightStick;
  56381. if (RSValues) {
  56382. if (RSValues.x != 0) {
  56383. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  56384. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  56385. camera.inertialAlphaOffset += normalizedRX;
  56386. }
  56387. }
  56388. if (RSValues.y != 0) {
  56389. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  56390. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  56391. camera.inertialBetaOffset += normalizedRY;
  56392. }
  56393. }
  56394. }
  56395. var LSValues = this.gamepad.leftStick;
  56396. if (LSValues && LSValues.y != 0) {
  56397. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  56398. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  56399. this.camera.inertialRadiusOffset -= normalizedLY;
  56400. }
  56401. }
  56402. }
  56403. };
  56404. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  56405. return "ArcRotateCameraGamepadInput";
  56406. };
  56407. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  56408. return "gamepad";
  56409. };
  56410. __decorate([
  56411. BABYLON.serialize()
  56412. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  56413. __decorate([
  56414. BABYLON.serialize()
  56415. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  56416. return ArcRotateCameraGamepadInput;
  56417. }());
  56418. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  56419. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  56420. })(BABYLON || (BABYLON = {}));
  56421. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  56422. var BABYLON;
  56423. (function (BABYLON) {
  56424. var GamepadManager = /** @class */ (function () {
  56425. function GamepadManager(_scene) {
  56426. var _this = this;
  56427. this._scene = _scene;
  56428. this._babylonGamepads = [];
  56429. this._oneGamepadConnected = false;
  56430. this._isMonitoring = false;
  56431. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  56432. if (!BABYLON.Tools.IsWindowObjectExist()) {
  56433. this._gamepadEventSupported = false;
  56434. }
  56435. else {
  56436. this._gamepadEventSupported = 'GamepadEvent' in window;
  56437. this._gamepadSupport = (navigator.getGamepads ||
  56438. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  56439. }
  56440. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  56441. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  56442. for (var i in _this._babylonGamepads) {
  56443. var gamepad = _this._babylonGamepads[i];
  56444. if (gamepad && gamepad._isConnected) {
  56445. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  56446. }
  56447. }
  56448. });
  56449. this._onGamepadConnectedEvent = function (evt) {
  56450. var gamepad = evt.gamepad;
  56451. if (gamepad.index in _this._babylonGamepads) {
  56452. if (_this._babylonGamepads[gamepad.index].isConnected) {
  56453. return;
  56454. }
  56455. }
  56456. var newGamepad;
  56457. if (_this._babylonGamepads[gamepad.index]) {
  56458. newGamepad = _this._babylonGamepads[gamepad.index];
  56459. newGamepad.browserGamepad = gamepad;
  56460. newGamepad._isConnected = true;
  56461. }
  56462. else {
  56463. newGamepad = _this._addNewGamepad(gamepad);
  56464. }
  56465. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  56466. _this._startMonitoringGamepads();
  56467. };
  56468. this._onGamepadDisconnectedEvent = function (evt) {
  56469. var gamepad = evt.gamepad;
  56470. // Remove the gamepad from the list of gamepads to monitor.
  56471. for (var i in _this._babylonGamepads) {
  56472. if (_this._babylonGamepads[i].index === gamepad.index) {
  56473. var disconnectedGamepad = _this._babylonGamepads[i];
  56474. disconnectedGamepad._isConnected = false;
  56475. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  56476. break;
  56477. }
  56478. }
  56479. };
  56480. if (this._gamepadSupport) {
  56481. //first add already-connected gamepads
  56482. this._updateGamepadObjects();
  56483. if (this._babylonGamepads.length) {
  56484. this._startMonitoringGamepads();
  56485. }
  56486. // Checking if the gamepad connected event is supported (like in Firefox)
  56487. if (this._gamepadEventSupported) {
  56488. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  56489. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  56490. }
  56491. else {
  56492. this._startMonitoringGamepads();
  56493. }
  56494. }
  56495. }
  56496. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  56497. get: function () {
  56498. return this._babylonGamepads;
  56499. },
  56500. enumerable: true,
  56501. configurable: true
  56502. });
  56503. GamepadManager.prototype.getGamepadByType = function (type) {
  56504. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  56505. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  56506. var gamepad = _a[_i];
  56507. if (gamepad && gamepad.type === type) {
  56508. return gamepad;
  56509. }
  56510. }
  56511. return null;
  56512. };
  56513. GamepadManager.prototype.dispose = function () {
  56514. if (this._gamepadEventSupported) {
  56515. if (this._onGamepadConnectedEvent) {
  56516. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  56517. }
  56518. if (this._onGamepadDisconnectedEvent) {
  56519. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  56520. }
  56521. this._onGamepadConnectedEvent = null;
  56522. this._onGamepadDisconnectedEvent = null;
  56523. }
  56524. this._babylonGamepads.forEach(function (gamepad) {
  56525. gamepad.dispose();
  56526. });
  56527. this.onGamepadConnectedObservable.clear();
  56528. this.onGamepadDisconnectedObservable.clear();
  56529. this._oneGamepadConnected = false;
  56530. this._stopMonitoringGamepads();
  56531. this._babylonGamepads = [];
  56532. };
  56533. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  56534. if (!this._oneGamepadConnected) {
  56535. this._oneGamepadConnected = true;
  56536. }
  56537. var newGamepad;
  56538. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  56539. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  56540. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  56541. }
  56542. else if (gamepad.pose) {
  56543. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  56544. }
  56545. else {
  56546. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  56547. }
  56548. this._babylonGamepads[newGamepad.index] = newGamepad;
  56549. return newGamepad;
  56550. };
  56551. GamepadManager.prototype._startMonitoringGamepads = function () {
  56552. if (!this._isMonitoring) {
  56553. this._isMonitoring = true;
  56554. //back-comp
  56555. if (!this._scene) {
  56556. this._checkGamepadsStatus();
  56557. }
  56558. }
  56559. };
  56560. GamepadManager.prototype._stopMonitoringGamepads = function () {
  56561. this._isMonitoring = false;
  56562. };
  56563. GamepadManager.prototype._checkGamepadsStatus = function () {
  56564. var _this = this;
  56565. // Hack to be compatible Chrome
  56566. this._updateGamepadObjects();
  56567. for (var i in this._babylonGamepads) {
  56568. var gamepad = this._babylonGamepads[i];
  56569. if (!gamepad || !gamepad.isConnected) {
  56570. continue;
  56571. }
  56572. gamepad.update();
  56573. }
  56574. if (this._isMonitoring && !this._scene) {
  56575. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  56576. }
  56577. };
  56578. // This function is called only on Chrome, which does not properly support
  56579. // connection/disconnection events and forces you to recopy again the gamepad object
  56580. GamepadManager.prototype._updateGamepadObjects = function () {
  56581. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  56582. for (var i = 0; i < gamepads.length; i++) {
  56583. if (gamepads[i]) {
  56584. if (!this._babylonGamepads[gamepads[i].index]) {
  56585. var newGamepad = this._addNewGamepad(gamepads[i]);
  56586. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  56587. }
  56588. else {
  56589. // Forced to copy again this object for Chrome for unknown reason
  56590. this._babylonGamepads[i].browserGamepad = gamepads[i];
  56591. if (!this._babylonGamepads[i].isConnected) {
  56592. this._babylonGamepads[i]._isConnected = true;
  56593. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  56594. }
  56595. }
  56596. }
  56597. }
  56598. };
  56599. return GamepadManager;
  56600. }());
  56601. BABYLON.GamepadManager = GamepadManager;
  56602. })(BABYLON || (BABYLON = {}));
  56603. //# sourceMappingURL=babylon.gamepadManager.js.map
  56604. var BABYLON;
  56605. (function (BABYLON) {
  56606. var StickValues = /** @class */ (function () {
  56607. function StickValues(x, y) {
  56608. this.x = x;
  56609. this.y = y;
  56610. }
  56611. return StickValues;
  56612. }());
  56613. BABYLON.StickValues = StickValues;
  56614. var Gamepad = /** @class */ (function () {
  56615. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  56616. if (leftStickX === void 0) { leftStickX = 0; }
  56617. if (leftStickY === void 0) { leftStickY = 1; }
  56618. if (rightStickX === void 0) { rightStickX = 2; }
  56619. if (rightStickY === void 0) { rightStickY = 3; }
  56620. this.id = id;
  56621. this.index = index;
  56622. this.browserGamepad = browserGamepad;
  56623. this._isConnected = true;
  56624. this._invertLeftStickY = false;
  56625. this.type = Gamepad.GAMEPAD;
  56626. this._leftStickAxisX = leftStickX;
  56627. this._leftStickAxisY = leftStickY;
  56628. this._rightStickAxisX = rightStickX;
  56629. this._rightStickAxisY = rightStickY;
  56630. if (this.browserGamepad.axes.length >= 2) {
  56631. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  56632. }
  56633. if (this.browserGamepad.axes.length >= 4) {
  56634. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  56635. }
  56636. }
  56637. Object.defineProperty(Gamepad.prototype, "isConnected", {
  56638. get: function () {
  56639. return this._isConnected;
  56640. },
  56641. enumerable: true,
  56642. configurable: true
  56643. });
  56644. Gamepad.prototype.onleftstickchanged = function (callback) {
  56645. this._onleftstickchanged = callback;
  56646. };
  56647. Gamepad.prototype.onrightstickchanged = function (callback) {
  56648. this._onrightstickchanged = callback;
  56649. };
  56650. Object.defineProperty(Gamepad.prototype, "leftStick", {
  56651. get: function () {
  56652. return this._leftStick;
  56653. },
  56654. set: function (newValues) {
  56655. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  56656. this._onleftstickchanged(newValues);
  56657. }
  56658. this._leftStick = newValues;
  56659. },
  56660. enumerable: true,
  56661. configurable: true
  56662. });
  56663. Object.defineProperty(Gamepad.prototype, "rightStick", {
  56664. get: function () {
  56665. return this._rightStick;
  56666. },
  56667. set: function (newValues) {
  56668. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  56669. this._onrightstickchanged(newValues);
  56670. }
  56671. this._rightStick = newValues;
  56672. },
  56673. enumerable: true,
  56674. configurable: true
  56675. });
  56676. Gamepad.prototype.update = function () {
  56677. if (this._leftStick) {
  56678. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  56679. if (this._invertLeftStickY) {
  56680. this.leftStick.y *= -1;
  56681. }
  56682. }
  56683. if (this._rightStick) {
  56684. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  56685. }
  56686. };
  56687. Gamepad.prototype.dispose = function () {
  56688. };
  56689. Gamepad.GAMEPAD = 0;
  56690. Gamepad.GENERIC = 1;
  56691. Gamepad.XBOX = 2;
  56692. Gamepad.POSE_ENABLED = 3;
  56693. return Gamepad;
  56694. }());
  56695. BABYLON.Gamepad = Gamepad;
  56696. var GenericPad = /** @class */ (function (_super) {
  56697. __extends(GenericPad, _super);
  56698. function GenericPad(id, index, browserGamepad) {
  56699. var _this = _super.call(this, id, index, browserGamepad) || this;
  56700. _this.onButtonDownObservable = new BABYLON.Observable();
  56701. _this.onButtonUpObservable = new BABYLON.Observable();
  56702. _this.type = Gamepad.GENERIC;
  56703. _this._buttons = new Array(browserGamepad.buttons.length);
  56704. return _this;
  56705. }
  56706. GenericPad.prototype.onbuttondown = function (callback) {
  56707. this._onbuttondown = callback;
  56708. };
  56709. GenericPad.prototype.onbuttonup = function (callback) {
  56710. this._onbuttonup = callback;
  56711. };
  56712. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  56713. if (newValue !== currentValue) {
  56714. if (newValue === 1) {
  56715. if (this._onbuttondown) {
  56716. this._onbuttondown(buttonIndex);
  56717. }
  56718. this.onButtonDownObservable.notifyObservers(buttonIndex);
  56719. }
  56720. if (newValue === 0) {
  56721. if (this._onbuttonup) {
  56722. this._onbuttonup(buttonIndex);
  56723. }
  56724. this.onButtonUpObservable.notifyObservers(buttonIndex);
  56725. }
  56726. }
  56727. return newValue;
  56728. };
  56729. GenericPad.prototype.update = function () {
  56730. _super.prototype.update.call(this);
  56731. for (var index = 0; index < this._buttons.length; index++) {
  56732. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  56733. }
  56734. };
  56735. GenericPad.prototype.dispose = function () {
  56736. _super.prototype.dispose.call(this);
  56737. this.onButtonDownObservable.clear();
  56738. this.onButtonUpObservable.clear();
  56739. };
  56740. return GenericPad;
  56741. }(Gamepad));
  56742. BABYLON.GenericPad = GenericPad;
  56743. })(BABYLON || (BABYLON = {}));
  56744. //# sourceMappingURL=babylon.gamepad.js.map
  56745. var BABYLON;
  56746. (function (BABYLON) {
  56747. var Xbox360Button;
  56748. (function (Xbox360Button) {
  56749. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  56750. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  56751. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  56752. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  56753. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  56754. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  56755. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  56756. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  56757. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  56758. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  56759. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  56760. var Xbox360Dpad;
  56761. (function (Xbox360Dpad) {
  56762. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  56763. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  56764. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  56765. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  56766. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  56767. var Xbox360Pad = /** @class */ (function (_super) {
  56768. __extends(Xbox360Pad, _super);
  56769. function Xbox360Pad(id, index, gamepad, xboxOne) {
  56770. if (xboxOne === void 0) { xboxOne = false; }
  56771. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  56772. _this._leftTrigger = 0;
  56773. _this._rightTrigger = 0;
  56774. _this.onButtonDownObservable = new BABYLON.Observable();
  56775. _this.onButtonUpObservable = new BABYLON.Observable();
  56776. _this.onPadDownObservable = new BABYLON.Observable();
  56777. _this.onPadUpObservable = new BABYLON.Observable();
  56778. _this._buttonA = 0;
  56779. _this._buttonB = 0;
  56780. _this._buttonX = 0;
  56781. _this._buttonY = 0;
  56782. _this._buttonBack = 0;
  56783. _this._buttonStart = 0;
  56784. _this._buttonLB = 0;
  56785. _this._buttonRB = 0;
  56786. _this._buttonLeftStick = 0;
  56787. _this._buttonRightStick = 0;
  56788. _this._dPadUp = 0;
  56789. _this._dPadDown = 0;
  56790. _this._dPadLeft = 0;
  56791. _this._dPadRight = 0;
  56792. _this._isXboxOnePad = false;
  56793. _this.type = BABYLON.Gamepad.XBOX;
  56794. _this._isXboxOnePad = xboxOne;
  56795. return _this;
  56796. }
  56797. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  56798. this._onlefttriggerchanged = callback;
  56799. };
  56800. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  56801. this._onrighttriggerchanged = callback;
  56802. };
  56803. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  56804. get: function () {
  56805. return this._leftTrigger;
  56806. },
  56807. set: function (newValue) {
  56808. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  56809. this._onlefttriggerchanged(newValue);
  56810. }
  56811. this._leftTrigger = newValue;
  56812. },
  56813. enumerable: true,
  56814. configurable: true
  56815. });
  56816. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  56817. get: function () {
  56818. return this._rightTrigger;
  56819. },
  56820. set: function (newValue) {
  56821. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  56822. this._onrighttriggerchanged(newValue);
  56823. }
  56824. this._rightTrigger = newValue;
  56825. },
  56826. enumerable: true,
  56827. configurable: true
  56828. });
  56829. Xbox360Pad.prototype.onbuttondown = function (callback) {
  56830. this._onbuttondown = callback;
  56831. };
  56832. Xbox360Pad.prototype.onbuttonup = function (callback) {
  56833. this._onbuttonup = callback;
  56834. };
  56835. Xbox360Pad.prototype.ondpaddown = function (callback) {
  56836. this._ondpaddown = callback;
  56837. };
  56838. Xbox360Pad.prototype.ondpadup = function (callback) {
  56839. this._ondpadup = callback;
  56840. };
  56841. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  56842. if (newValue !== currentValue) {
  56843. if (newValue === 1) {
  56844. if (this._onbuttondown) {
  56845. this._onbuttondown(buttonType);
  56846. }
  56847. this.onButtonDownObservable.notifyObservers(buttonType);
  56848. }
  56849. if (newValue === 0) {
  56850. if (this._onbuttonup) {
  56851. this._onbuttonup(buttonType);
  56852. }
  56853. this.onButtonUpObservable.notifyObservers(buttonType);
  56854. }
  56855. }
  56856. return newValue;
  56857. };
  56858. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  56859. if (newValue !== currentValue) {
  56860. if (newValue === 1) {
  56861. if (this._ondpaddown) {
  56862. this._ondpaddown(buttonType);
  56863. }
  56864. this.onPadDownObservable.notifyObservers(buttonType);
  56865. }
  56866. if (newValue === 0) {
  56867. if (this._ondpadup) {
  56868. this._ondpadup(buttonType);
  56869. }
  56870. this.onPadUpObservable.notifyObservers(buttonType);
  56871. }
  56872. }
  56873. return newValue;
  56874. };
  56875. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  56876. get: function () {
  56877. return this._buttonA;
  56878. },
  56879. set: function (value) {
  56880. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  56881. },
  56882. enumerable: true,
  56883. configurable: true
  56884. });
  56885. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  56886. get: function () {
  56887. return this._buttonB;
  56888. },
  56889. set: function (value) {
  56890. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  56891. },
  56892. enumerable: true,
  56893. configurable: true
  56894. });
  56895. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  56896. get: function () {
  56897. return this._buttonX;
  56898. },
  56899. set: function (value) {
  56900. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  56901. },
  56902. enumerable: true,
  56903. configurable: true
  56904. });
  56905. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  56906. get: function () {
  56907. return this._buttonY;
  56908. },
  56909. set: function (value) {
  56910. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  56911. },
  56912. enumerable: true,
  56913. configurable: true
  56914. });
  56915. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  56916. get: function () {
  56917. return this._buttonStart;
  56918. },
  56919. set: function (value) {
  56920. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  56921. },
  56922. enumerable: true,
  56923. configurable: true
  56924. });
  56925. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  56926. get: function () {
  56927. return this._buttonBack;
  56928. },
  56929. set: function (value) {
  56930. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  56931. },
  56932. enumerable: true,
  56933. configurable: true
  56934. });
  56935. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  56936. get: function () {
  56937. return this._buttonLB;
  56938. },
  56939. set: function (value) {
  56940. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  56941. },
  56942. enumerable: true,
  56943. configurable: true
  56944. });
  56945. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  56946. get: function () {
  56947. return this._buttonRB;
  56948. },
  56949. set: function (value) {
  56950. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  56951. },
  56952. enumerable: true,
  56953. configurable: true
  56954. });
  56955. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  56956. get: function () {
  56957. return this._buttonLeftStick;
  56958. },
  56959. set: function (value) {
  56960. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  56961. },
  56962. enumerable: true,
  56963. configurable: true
  56964. });
  56965. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  56966. get: function () {
  56967. return this._buttonRightStick;
  56968. },
  56969. set: function (value) {
  56970. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  56971. },
  56972. enumerable: true,
  56973. configurable: true
  56974. });
  56975. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  56976. get: function () {
  56977. return this._dPadUp;
  56978. },
  56979. set: function (value) {
  56980. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  56981. },
  56982. enumerable: true,
  56983. configurable: true
  56984. });
  56985. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  56986. get: function () {
  56987. return this._dPadDown;
  56988. },
  56989. set: function (value) {
  56990. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  56991. },
  56992. enumerable: true,
  56993. configurable: true
  56994. });
  56995. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  56996. get: function () {
  56997. return this._dPadLeft;
  56998. },
  56999. set: function (value) {
  57000. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  57001. },
  57002. enumerable: true,
  57003. configurable: true
  57004. });
  57005. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  57006. get: function () {
  57007. return this._dPadRight;
  57008. },
  57009. set: function (value) {
  57010. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  57011. },
  57012. enumerable: true,
  57013. configurable: true
  57014. });
  57015. Xbox360Pad.prototype.update = function () {
  57016. _super.prototype.update.call(this);
  57017. if (this._isXboxOnePad) {
  57018. this.buttonA = this.browserGamepad.buttons[0].value;
  57019. this.buttonB = this.browserGamepad.buttons[1].value;
  57020. this.buttonX = this.browserGamepad.buttons[2].value;
  57021. this.buttonY = this.browserGamepad.buttons[3].value;
  57022. this.buttonLB = this.browserGamepad.buttons[4].value;
  57023. this.buttonRB = this.browserGamepad.buttons[5].value;
  57024. this.leftTrigger = this.browserGamepad.axes[2];
  57025. this.rightTrigger = this.browserGamepad.axes[5];
  57026. this.buttonBack = this.browserGamepad.buttons[9].value;
  57027. this.buttonStart = this.browserGamepad.buttons[8].value;
  57028. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  57029. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  57030. this.dPadUp = this.browserGamepad.buttons[11].value;
  57031. this.dPadDown = this.browserGamepad.buttons[12].value;
  57032. this.dPadLeft = this.browserGamepad.buttons[13].value;
  57033. this.dPadRight = this.browserGamepad.buttons[14].value;
  57034. }
  57035. else {
  57036. this.buttonA = this.browserGamepad.buttons[0].value;
  57037. this.buttonB = this.browserGamepad.buttons[1].value;
  57038. this.buttonX = this.browserGamepad.buttons[2].value;
  57039. this.buttonY = this.browserGamepad.buttons[3].value;
  57040. this.buttonLB = this.browserGamepad.buttons[4].value;
  57041. this.buttonRB = this.browserGamepad.buttons[5].value;
  57042. this.leftTrigger = this.browserGamepad.buttons[6].value;
  57043. this.rightTrigger = this.browserGamepad.buttons[7].value;
  57044. this.buttonBack = this.browserGamepad.buttons[8].value;
  57045. this.buttonStart = this.browserGamepad.buttons[9].value;
  57046. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  57047. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  57048. this.dPadUp = this.browserGamepad.buttons[12].value;
  57049. this.dPadDown = this.browserGamepad.buttons[13].value;
  57050. this.dPadLeft = this.browserGamepad.buttons[14].value;
  57051. this.dPadRight = this.browserGamepad.buttons[15].value;
  57052. }
  57053. };
  57054. Xbox360Pad.prototype.dispose = function () {
  57055. _super.prototype.dispose.call(this);
  57056. this.onButtonDownObservable.clear();
  57057. this.onButtonUpObservable.clear();
  57058. this.onPadDownObservable.clear();
  57059. this.onPadUpObservable.clear();
  57060. };
  57061. return Xbox360Pad;
  57062. }(BABYLON.Gamepad));
  57063. BABYLON.Xbox360Pad = Xbox360Pad;
  57064. })(BABYLON || (BABYLON = {}));
  57065. //# sourceMappingURL=babylon.xboxGamepad.js.map
  57066. var BABYLON;
  57067. (function (BABYLON) {
  57068. var PoseEnabledControllerType;
  57069. (function (PoseEnabledControllerType) {
  57070. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  57071. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  57072. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  57073. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  57074. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  57075. var PoseEnabledControllerHelper = /** @class */ (function () {
  57076. function PoseEnabledControllerHelper() {
  57077. }
  57078. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  57079. // Oculus Touch
  57080. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  57081. return new BABYLON.OculusTouchController(vrGamepad);
  57082. }
  57083. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  57084. return new BABYLON.WindowsMotionController(vrGamepad);
  57085. }
  57086. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  57087. return new BABYLON.ViveController(vrGamepad);
  57088. }
  57089. else {
  57090. return new BABYLON.GenericController(vrGamepad);
  57091. }
  57092. };
  57093. return PoseEnabledControllerHelper;
  57094. }());
  57095. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  57096. var PoseEnabledController = /** @class */ (function (_super) {
  57097. __extends(PoseEnabledController, _super);
  57098. function PoseEnabledController(browserGamepad) {
  57099. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  57100. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  57101. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  57102. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  57103. // Represents device position and rotation in babylon space
  57104. _this.devicePosition = BABYLON.Vector3.Zero();
  57105. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  57106. _this.deviceScaleFactor = 1;
  57107. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  57108. _this._deviceToWorld = BABYLON.Matrix.Identity();
  57109. _this._workingMatrix = BABYLON.Matrix.Identity();
  57110. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  57111. _this.controllerType = PoseEnabledControllerType.GENERIC;
  57112. _this.position = BABYLON.Vector3.Zero();
  57113. _this.rotationQuaternion = new BABYLON.Quaternion();
  57114. _this._calculatedPosition = BABYLON.Vector3.Zero();
  57115. _this._calculatedRotation = new BABYLON.Quaternion();
  57116. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  57117. return _this;
  57118. }
  57119. PoseEnabledController.prototype.update = function () {
  57120. _super.prototype.update.call(this);
  57121. var pose = this.browserGamepad.pose;
  57122. this.updateFromDevice(pose);
  57123. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  57124. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  57125. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  57126. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  57127. if (this._mesh) {
  57128. this._mesh.position.copyFrom(this.devicePosition);
  57129. if (this._mesh.rotationQuaternion) {
  57130. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  57131. }
  57132. }
  57133. };
  57134. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  57135. if (poseData) {
  57136. this.rawPose = poseData;
  57137. if (poseData.position) {
  57138. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  57139. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  57140. this._deviceRoomPosition.z *= -1;
  57141. }
  57142. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  57143. this._calculatedPosition.addInPlace(this.position);
  57144. }
  57145. var pose = this.rawPose;
  57146. if (poseData.orientation && pose.orientation) {
  57147. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  57148. if (this._mesh) {
  57149. if (this._mesh.getScene().useRightHandedSystem) {
  57150. this._deviceRoomRotationQuaternion.z *= -1;
  57151. this._deviceRoomRotationQuaternion.w *= -1;
  57152. }
  57153. else {
  57154. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  57155. }
  57156. }
  57157. // if the camera is set, rotate to the camera's rotation
  57158. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  57159. }
  57160. }
  57161. };
  57162. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  57163. if (this._mesh) {
  57164. this._mesh.parent = null;
  57165. }
  57166. this._mesh = mesh;
  57167. if (this._poseControlledCamera) {
  57168. this._mesh.parent = this._poseControlledCamera;
  57169. }
  57170. if (!this._mesh.rotationQuaternion) {
  57171. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  57172. }
  57173. };
  57174. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  57175. this._poseControlledCamera = camera;
  57176. if (this._mesh) {
  57177. this._mesh.parent = this._poseControlledCamera;
  57178. }
  57179. };
  57180. PoseEnabledController.prototype.dispose = function () {
  57181. if (this._mesh) {
  57182. this._mesh.dispose();
  57183. }
  57184. this._mesh = null;
  57185. _super.prototype.dispose.call(this);
  57186. };
  57187. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  57188. get: function () {
  57189. return this._mesh;
  57190. },
  57191. enumerable: true,
  57192. configurable: true
  57193. });
  57194. PoseEnabledController.prototype.getForwardRay = function (length) {
  57195. if (length === void 0) { length = 100; }
  57196. if (!this.mesh) {
  57197. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  57198. }
  57199. var m = this.mesh.getWorldMatrix();
  57200. var origin = m.getTranslation();
  57201. var forward = new BABYLON.Vector3(0, 0, -1);
  57202. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  57203. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  57204. return new BABYLON.Ray(origin, direction, length);
  57205. };
  57206. return PoseEnabledController;
  57207. }(BABYLON.Gamepad));
  57208. BABYLON.PoseEnabledController = PoseEnabledController;
  57209. })(BABYLON || (BABYLON = {}));
  57210. //# sourceMappingURL=babylon.poseEnabledController.js.map
  57211. var BABYLON;
  57212. (function (BABYLON) {
  57213. var WebVRController = /** @class */ (function (_super) {
  57214. __extends(WebVRController, _super);
  57215. function WebVRController(vrGamepad) {
  57216. var _this = _super.call(this, vrGamepad) || this;
  57217. // Observables
  57218. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  57219. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  57220. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  57221. _this.onPadStateChangedObservable = new BABYLON.Observable();
  57222. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  57223. _this.pad = { x: 0, y: 0 };
  57224. // avoid GC, store state in a tmp object
  57225. _this._changes = {
  57226. pressChanged: false,
  57227. touchChanged: false,
  57228. valueChanged: false,
  57229. changed: false
  57230. };
  57231. _this._buttons = new Array(vrGamepad.buttons.length);
  57232. _this.hand = vrGamepad.hand;
  57233. return _this;
  57234. }
  57235. WebVRController.prototype.onButtonStateChange = function (callback) {
  57236. this._onButtonStateChange = callback;
  57237. };
  57238. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  57239. get: function () {
  57240. return this._defaultModel;
  57241. },
  57242. enumerable: true,
  57243. configurable: true
  57244. });
  57245. WebVRController.prototype.update = function () {
  57246. _super.prototype.update.call(this);
  57247. for (var index = 0; index < this._buttons.length; index++) {
  57248. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  57249. }
  57250. ;
  57251. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  57252. this.pad.x = this.leftStick.x;
  57253. this.pad.y = this.leftStick.y;
  57254. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  57255. }
  57256. };
  57257. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  57258. if (!newState) {
  57259. newState = {
  57260. pressed: false,
  57261. touched: false,
  57262. value: 0
  57263. };
  57264. }
  57265. if (!currentState) {
  57266. this._buttons[buttonIndex] = {
  57267. pressed: newState.pressed,
  57268. touched: newState.touched,
  57269. value: newState.value
  57270. };
  57271. return;
  57272. }
  57273. this._checkChanges(newState, currentState);
  57274. if (this._changes.changed) {
  57275. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  57276. this.handleButtonChange(buttonIndex, newState, this._changes);
  57277. }
  57278. this._buttons[buttonIndex].pressed = newState.pressed;
  57279. this._buttons[buttonIndex].touched = newState.touched;
  57280. // oculus triggers are never 0, thou not touched.
  57281. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  57282. };
  57283. WebVRController.prototype._checkChanges = function (newState, currentState) {
  57284. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  57285. this._changes.touchChanged = newState.touched !== currentState.touched;
  57286. this._changes.valueChanged = newState.value !== currentState.value;
  57287. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  57288. return this._changes;
  57289. };
  57290. WebVRController.prototype.dispose = function () {
  57291. _super.prototype.dispose.call(this);
  57292. this.onTriggerStateChangedObservable.clear();
  57293. this.onMainButtonStateChangedObservable.clear();
  57294. this.onSecondaryButtonStateChangedObservable.clear();
  57295. this.onPadStateChangedObservable.clear();
  57296. this.onPadValuesChangedObservable.clear();
  57297. };
  57298. return WebVRController;
  57299. }(BABYLON.PoseEnabledController));
  57300. BABYLON.WebVRController = WebVRController;
  57301. })(BABYLON || (BABYLON = {}));
  57302. //# sourceMappingURL=babylon.webVRController.js.map
  57303. var BABYLON;
  57304. (function (BABYLON) {
  57305. var OculusTouchController = /** @class */ (function (_super) {
  57306. __extends(OculusTouchController, _super);
  57307. function OculusTouchController(vrGamepad) {
  57308. var _this = _super.call(this, vrGamepad) || this;
  57309. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  57310. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  57311. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  57312. return _this;
  57313. }
  57314. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  57315. var _this = this;
  57316. var meshName;
  57317. // Hand
  57318. if (this.hand === 'left') {
  57319. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  57320. }
  57321. else {
  57322. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  57323. }
  57324. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  57325. /*
  57326. Parent Mesh name: oculus_touch_left
  57327. - body
  57328. - trigger
  57329. - thumbstick
  57330. - grip
  57331. - button_y
  57332. - button_x
  57333. - button_enter
  57334. */
  57335. _this._defaultModel = newMeshes[1];
  57336. _this.attachToMesh(_this._defaultModel);
  57337. if (meshLoaded) {
  57338. meshLoaded(_this._defaultModel);
  57339. }
  57340. });
  57341. };
  57342. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  57343. // helper getters for left and right hand.
  57344. get: function () {
  57345. if (this.hand === 'right') {
  57346. return this.onMainButtonStateChangedObservable;
  57347. }
  57348. else {
  57349. throw new Error('No A button on left hand');
  57350. }
  57351. },
  57352. enumerable: true,
  57353. configurable: true
  57354. });
  57355. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  57356. get: function () {
  57357. if (this.hand === 'right') {
  57358. return this.onSecondaryButtonStateChangedObservable;
  57359. }
  57360. else {
  57361. throw new Error('No B button on left hand');
  57362. }
  57363. },
  57364. enumerable: true,
  57365. configurable: true
  57366. });
  57367. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  57368. get: function () {
  57369. if (this.hand === 'left') {
  57370. return this.onMainButtonStateChangedObservable;
  57371. }
  57372. else {
  57373. throw new Error('No X button on right hand');
  57374. }
  57375. },
  57376. enumerable: true,
  57377. configurable: true
  57378. });
  57379. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  57380. get: function () {
  57381. if (this.hand === 'left') {
  57382. return this.onSecondaryButtonStateChangedObservable;
  57383. }
  57384. else {
  57385. throw new Error('No Y button on right hand');
  57386. }
  57387. },
  57388. enumerable: true,
  57389. configurable: true
  57390. });
  57391. /*
  57392. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  57393. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  57394. 2) secondary trigger (same)
  57395. 3) A (right) X (left), touch, pressed = value
  57396. 4) B / Y
  57397. 5) thumb rest
  57398. */
  57399. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  57400. var notifyObject = state; //{ state: state, changes: changes };
  57401. var triggerDirection = this.hand === 'right' ? -1 : 1;
  57402. switch (buttonIdx) {
  57403. case 0:
  57404. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  57405. return;
  57406. case 1:// index trigger
  57407. if (this._defaultModel) {
  57408. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  57409. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  57410. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  57411. }
  57412. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  57413. return;
  57414. case 2:// secondary trigger
  57415. if (this._defaultModel) {
  57416. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  57417. }
  57418. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  57419. return;
  57420. case 3:
  57421. if (this._defaultModel) {
  57422. if (notifyObject.pressed) {
  57423. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  57424. }
  57425. else {
  57426. (this._defaultModel.getChildren()[1]).position.y = 0;
  57427. }
  57428. }
  57429. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  57430. return;
  57431. case 4:
  57432. if (this._defaultModel) {
  57433. if (notifyObject.pressed) {
  57434. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  57435. }
  57436. else {
  57437. (this._defaultModel.getChildren()[2]).position.y = 0;
  57438. }
  57439. }
  57440. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  57441. return;
  57442. case 5:
  57443. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  57444. return;
  57445. }
  57446. };
  57447. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  57448. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  57449. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  57450. return OculusTouchController;
  57451. }(BABYLON.WebVRController));
  57452. BABYLON.OculusTouchController = OculusTouchController;
  57453. })(BABYLON || (BABYLON = {}));
  57454. //# sourceMappingURL=babylon.oculusTouchController.js.map
  57455. var BABYLON;
  57456. (function (BABYLON) {
  57457. var ViveController = /** @class */ (function (_super) {
  57458. __extends(ViveController, _super);
  57459. function ViveController(vrGamepad) {
  57460. var _this = _super.call(this, vrGamepad) || this;
  57461. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  57462. _this._invertLeftStickY = true;
  57463. return _this;
  57464. }
  57465. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  57466. var _this = this;
  57467. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  57468. /*
  57469. Parent Mesh name: ViveWand
  57470. - body
  57471. - r_gripper
  57472. - l_gripper
  57473. - menu_button
  57474. - system_button
  57475. - trackpad
  57476. - trigger
  57477. - LED
  57478. */
  57479. _this._defaultModel = newMeshes[1];
  57480. _this.attachToMesh(_this._defaultModel);
  57481. if (meshLoaded) {
  57482. meshLoaded(_this._defaultModel);
  57483. }
  57484. });
  57485. };
  57486. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  57487. get: function () {
  57488. return this.onMainButtonStateChangedObservable;
  57489. },
  57490. enumerable: true,
  57491. configurable: true
  57492. });
  57493. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  57494. get: function () {
  57495. return this.onMainButtonStateChangedObservable;
  57496. },
  57497. enumerable: true,
  57498. configurable: true
  57499. });
  57500. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  57501. get: function () {
  57502. return this.onSecondaryButtonStateChangedObservable;
  57503. },
  57504. enumerable: true,
  57505. configurable: true
  57506. });
  57507. /**
  57508. * Vive mapping:
  57509. * 0: touchpad
  57510. * 1: trigger
  57511. * 2: left AND right buttons
  57512. * 3: menu button
  57513. */
  57514. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  57515. var notifyObject = state; //{ state: state, changes: changes };
  57516. switch (buttonIdx) {
  57517. case 0:
  57518. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  57519. return;
  57520. case 1:// index trigger
  57521. if (this._defaultModel) {
  57522. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  57523. }
  57524. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  57525. return;
  57526. case 2:// left AND right button
  57527. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  57528. return;
  57529. case 3:
  57530. if (this._defaultModel) {
  57531. if (notifyObject.pressed) {
  57532. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  57533. }
  57534. else {
  57535. (this._defaultModel.getChildren()[2]).position.y = 0;
  57536. }
  57537. }
  57538. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  57539. return;
  57540. }
  57541. };
  57542. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  57543. ViveController.MODEL_FILENAME = 'wand.babylon';
  57544. return ViveController;
  57545. }(BABYLON.WebVRController));
  57546. BABYLON.ViveController = ViveController;
  57547. })(BABYLON || (BABYLON = {}));
  57548. //# sourceMappingURL=babylon.viveController.js.map
  57549. var BABYLON;
  57550. (function (BABYLON) {
  57551. var GenericController = /** @class */ (function (_super) {
  57552. __extends(GenericController, _super);
  57553. function GenericController(vrGamepad) {
  57554. return _super.call(this, vrGamepad) || this;
  57555. }
  57556. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  57557. var _this = this;
  57558. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  57559. _this._defaultModel = newMeshes[1];
  57560. _this.attachToMesh(_this._defaultModel);
  57561. if (meshLoaded) {
  57562. meshLoaded(_this._defaultModel);
  57563. }
  57564. });
  57565. };
  57566. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  57567. console.log("Button id: " + buttonIdx + "state: ");
  57568. console.dir(state);
  57569. };
  57570. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  57571. GenericController.MODEL_FILENAME = 'generic.babylon';
  57572. return GenericController;
  57573. }(BABYLON.WebVRController));
  57574. BABYLON.GenericController = GenericController;
  57575. })(BABYLON || (BABYLON = {}));
  57576. //# sourceMappingURL=babylon.genericController.js.map
  57577. var BABYLON;
  57578. (function (BABYLON) {
  57579. var LoadedMeshInfo = /** @class */ (function () {
  57580. function LoadedMeshInfo() {
  57581. this.buttonMeshes = {};
  57582. this.axisMeshes = {};
  57583. }
  57584. return LoadedMeshInfo;
  57585. }());
  57586. var WindowsMotionController = /** @class */ (function (_super) {
  57587. __extends(WindowsMotionController, _super);
  57588. function WindowsMotionController(vrGamepad) {
  57589. var _this = _super.call(this, vrGamepad) || this;
  57590. _this._mapping = {
  57591. // Semantic button names
  57592. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  57593. // A mapping of the button name to glTF model node name
  57594. // that should be transformed by button value.
  57595. buttonMeshNames: {
  57596. 'trigger': 'SELECT',
  57597. 'menu': 'MENU',
  57598. 'grip': 'GRASP',
  57599. 'thumbstick': 'THUMBSTICK_PRESS',
  57600. 'trackpad': 'TOUCHPAD_PRESS'
  57601. },
  57602. // This mapping is used to translate from the Motion Controller to Babylon semantics
  57603. buttonObservableNames: {
  57604. 'trigger': 'onTriggerStateChangedObservable',
  57605. 'menu': 'onSecondaryButtonStateChangedObservable',
  57606. 'grip': 'onMainButtonStateChangedObservable',
  57607. 'thumbstick': 'onPadStateChangedObservable',
  57608. 'trackpad': 'onTrackpadChangedObservable'
  57609. },
  57610. // A mapping of the axis name to glTF model node name
  57611. // that should be transformed by axis value.
  57612. // This array mirrors the browserGamepad.axes array, such that
  57613. // the mesh corresponding to axis 0 is in this array index 0.
  57614. axisMeshNames: [
  57615. 'THUMBSTICK_X',
  57616. 'THUMBSTICK_Y',
  57617. 'TOUCHPAD_TOUCH_X',
  57618. 'TOUCHPAD_TOUCH_Y'
  57619. ],
  57620. pointingPoseMeshName: 'POINTING_POSE'
  57621. };
  57622. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  57623. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  57624. _this.trackpad = { x: 0, y: 0 };
  57625. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  57626. _this._loadedMeshInfo = null;
  57627. return _this;
  57628. }
  57629. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  57630. get: function () {
  57631. return this.onTriggerStateChangedObservable;
  57632. },
  57633. enumerable: true,
  57634. configurable: true
  57635. });
  57636. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  57637. get: function () {
  57638. return this.onSecondaryButtonStateChangedObservable;
  57639. },
  57640. enumerable: true,
  57641. configurable: true
  57642. });
  57643. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  57644. get: function () {
  57645. return this.onMainButtonStateChangedObservable;
  57646. },
  57647. enumerable: true,
  57648. configurable: true
  57649. });
  57650. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  57651. get: function () {
  57652. return this.onPadStateChangedObservable;
  57653. },
  57654. enumerable: true,
  57655. configurable: true
  57656. });
  57657. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  57658. get: function () {
  57659. return this.onTrackpadChangedObservable;
  57660. },
  57661. enumerable: true,
  57662. configurable: true
  57663. });
  57664. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  57665. get: function () {
  57666. return this.onTrackpadValuesChangedObservable;
  57667. },
  57668. enumerable: true,
  57669. configurable: true
  57670. });
  57671. /**
  57672. * Called once per frame by the engine.
  57673. */
  57674. WindowsMotionController.prototype.update = function () {
  57675. _super.prototype.update.call(this);
  57676. // Only need to animate axes if there is a loaded mesh
  57677. if (this._loadedMeshInfo) {
  57678. if (this.browserGamepad.axes) {
  57679. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  57680. this.trackpad.x = this.browserGamepad["axes"][2];
  57681. this.trackpad.y = this.browserGamepad["axes"][3];
  57682. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  57683. }
  57684. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  57685. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  57686. }
  57687. }
  57688. }
  57689. };
  57690. /**
  57691. * Called once for each button that changed state since the last frame
  57692. * @param buttonIdx Which button index changed
  57693. * @param state New state of the button
  57694. * @param changes Which properties on the state changed since last frame
  57695. */
  57696. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  57697. var buttonName = this._mapping.buttons[buttonIdx];
  57698. if (!buttonName) {
  57699. return;
  57700. }
  57701. // Only emit events for buttons that we know how to map from index to name
  57702. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  57703. if (observable) {
  57704. observable.notifyObservers(state);
  57705. }
  57706. this.lerpButtonTransform(buttonName, state.value);
  57707. };
  57708. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  57709. // If there is no loaded mesh, there is nothing to transform.
  57710. if (!this._loadedMeshInfo) {
  57711. return;
  57712. }
  57713. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  57714. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  57715. return;
  57716. }
  57717. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  57718. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  57719. };
  57720. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  57721. if (!this._loadedMeshInfo) {
  57722. return;
  57723. }
  57724. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  57725. if (!meshInfo) {
  57726. return;
  57727. }
  57728. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  57729. return;
  57730. }
  57731. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  57732. var lerpValue = axisValue * 0.5 + 0.5;
  57733. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  57734. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  57735. };
  57736. /**
  57737. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  57738. * @param scene scene in which to add meshes
  57739. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  57740. */
  57741. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  57742. var _this = this;
  57743. if (forceDefault === void 0) { forceDefault = false; }
  57744. var path;
  57745. var filename;
  57746. // Checking if GLB loader is present
  57747. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  57748. // Determine the device specific folder based on the ID suffix
  57749. var device = 'default';
  57750. if (this.id && !forceDefault) {
  57751. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  57752. device = ((match && match[0]) || device);
  57753. }
  57754. // Hand
  57755. if (this.hand === 'left') {
  57756. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  57757. }
  57758. else {
  57759. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  57760. }
  57761. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  57762. }
  57763. else {
  57764. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  57765. path = BABYLON.GenericController.MODEL_BASE_URL;
  57766. filename = BABYLON.GenericController.MODEL_FILENAME;
  57767. }
  57768. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  57769. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  57770. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  57771. if (!_this._loadedMeshInfo) {
  57772. return;
  57773. }
  57774. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  57775. _this.attachToMesh(_this._defaultModel);
  57776. if (meshLoaded) {
  57777. meshLoaded(_this._defaultModel);
  57778. }
  57779. }, null, function (scene, message) {
  57780. BABYLON.Tools.Log(message);
  57781. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  57782. if (!forceDefault) {
  57783. _this.initControllerMesh(scene, meshLoaded, true);
  57784. }
  57785. });
  57786. };
  57787. /**
  57788. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  57789. * can be transformed by button presses and axes values, based on this._mapping.
  57790. *
  57791. * @param scene scene in which the meshes exist
  57792. * @param meshes list of meshes that make up the controller model to process
  57793. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  57794. */
  57795. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  57796. var loadedMeshInfo = null;
  57797. // Create a new mesh to contain the glTF hierarchy
  57798. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  57799. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  57800. var childMesh = null;
  57801. for (var i = 0; i < meshes.length; i++) {
  57802. var mesh = meshes[i];
  57803. if (!mesh.parent) {
  57804. // Exclude controller meshes from picking results
  57805. mesh.isPickable = false;
  57806. // Handle root node, attach to the new parentMesh
  57807. childMesh = mesh;
  57808. break;
  57809. }
  57810. }
  57811. if (childMesh) {
  57812. childMesh.setParent(parentMesh);
  57813. // Create our mesh info. Note that this method will always return non-null.
  57814. loadedMeshInfo = this.createMeshInfo(parentMesh);
  57815. }
  57816. else {
  57817. BABYLON.Tools.Warn('Could not find root node in model file.');
  57818. }
  57819. return loadedMeshInfo;
  57820. };
  57821. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  57822. var loadedMeshInfo = new LoadedMeshInfo();
  57823. var i;
  57824. loadedMeshInfo.rootNode = rootNode;
  57825. // Reset the caches
  57826. loadedMeshInfo.buttonMeshes = {};
  57827. loadedMeshInfo.axisMeshes = {};
  57828. // Button Meshes
  57829. for (i = 0; i < this._mapping.buttons.length; i++) {
  57830. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  57831. if (!buttonMeshName) {
  57832. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  57833. continue;
  57834. }
  57835. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  57836. if (!buttonMesh) {
  57837. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  57838. continue;
  57839. }
  57840. var buttonMeshInfo = {
  57841. index: i,
  57842. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  57843. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  57844. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  57845. };
  57846. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  57847. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  57848. }
  57849. else {
  57850. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  57851. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  57852. '(VALUE: ' + !!buttonMeshInfo.value +
  57853. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  57854. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  57855. ')');
  57856. }
  57857. }
  57858. // Axis Meshes
  57859. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  57860. var axisMeshName = this._mapping.axisMeshNames[i];
  57861. if (!axisMeshName) {
  57862. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  57863. continue;
  57864. }
  57865. var axisMesh = getChildByName(rootNode, axisMeshName);
  57866. if (!axisMesh) {
  57867. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  57868. continue;
  57869. }
  57870. var axisMeshInfo = {
  57871. index: i,
  57872. value: getImmediateChildByName(axisMesh, 'VALUE'),
  57873. min: getImmediateChildByName(axisMesh, 'MIN'),
  57874. max: getImmediateChildByName(axisMesh, 'MAX')
  57875. };
  57876. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  57877. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  57878. }
  57879. else {
  57880. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  57881. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  57882. '(VALUE: ' + !!axisMeshInfo.value +
  57883. ', MIN: ' + !!axisMeshInfo.min +
  57884. ', MAX:' + !!axisMeshInfo.max +
  57885. ')');
  57886. }
  57887. }
  57888. // Pointing Ray
  57889. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  57890. if (!loadedMeshInfo.pointingPoseNode) {
  57891. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  57892. }
  57893. return loadedMeshInfo;
  57894. // Look through all children recursively. This will return null if no mesh exists with the given name.
  57895. function getChildByName(node, name) {
  57896. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  57897. }
  57898. // Look through only immediate children. This will return null if no mesh exists with the given name.
  57899. function getImmediateChildByName(node, name) {
  57900. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  57901. }
  57902. };
  57903. WindowsMotionController.prototype.getForwardRay = function (length) {
  57904. if (length === void 0) { length = 100; }
  57905. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  57906. return _super.prototype.getForwardRay.call(this, length);
  57907. }
  57908. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  57909. var origin = m.getTranslation();
  57910. var forward = new BABYLON.Vector3(0, 0, -1);
  57911. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  57912. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  57913. return new BABYLON.Ray(origin, direction, length);
  57914. };
  57915. WindowsMotionController.prototype.dispose = function () {
  57916. _super.prototype.dispose.call(this);
  57917. this.onTrackpadChangedObservable.clear();
  57918. };
  57919. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  57920. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  57921. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  57922. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  57923. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  57924. return WindowsMotionController;
  57925. }(BABYLON.WebVRController));
  57926. BABYLON.WindowsMotionController = WindowsMotionController;
  57927. })(BABYLON || (BABYLON = {}));
  57928. //# sourceMappingURL=babylon.windowsMotionController.js.map
  57929. var BABYLON;
  57930. (function (BABYLON) {
  57931. var FollowCamera = /** @class */ (function (_super) {
  57932. __extends(FollowCamera, _super);
  57933. function FollowCamera(name, position, scene, lockedTarget) {
  57934. if (lockedTarget === void 0) { lockedTarget = null; }
  57935. var _this = _super.call(this, name, position, scene) || this;
  57936. _this.radius = 12;
  57937. _this.rotationOffset = 0;
  57938. _this.heightOffset = 4;
  57939. _this.cameraAcceleration = 0.05;
  57940. _this.maxCameraSpeed = 20;
  57941. _this.lockedTarget = lockedTarget;
  57942. return _this;
  57943. }
  57944. FollowCamera.prototype.getRadians = function (degrees) {
  57945. return degrees * Math.PI / 180;
  57946. };
  57947. FollowCamera.prototype.follow = function (cameraTarget) {
  57948. if (!cameraTarget)
  57949. return;
  57950. var yRotation;
  57951. if (cameraTarget.rotationQuaternion) {
  57952. var rotMatrix = new BABYLON.Matrix();
  57953. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  57954. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  57955. }
  57956. else {
  57957. yRotation = cameraTarget.rotation.y;
  57958. }
  57959. var radians = this.getRadians(this.rotationOffset) + yRotation;
  57960. var targetPosition = cameraTarget.getAbsolutePosition();
  57961. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  57962. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  57963. var dx = targetX - this.position.x;
  57964. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  57965. var dz = (targetZ) - this.position.z;
  57966. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  57967. var vy = dy * this.cameraAcceleration;
  57968. var vz = dz * this.cameraAcceleration * 2;
  57969. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  57970. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  57971. }
  57972. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  57973. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  57974. }
  57975. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  57976. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  57977. }
  57978. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  57979. this.setTarget(targetPosition);
  57980. };
  57981. FollowCamera.prototype._checkInputs = function () {
  57982. _super.prototype._checkInputs.call(this);
  57983. if (this.lockedTarget) {
  57984. this.follow(this.lockedTarget);
  57985. }
  57986. };
  57987. FollowCamera.prototype.getClassName = function () {
  57988. return "FollowCamera";
  57989. };
  57990. __decorate([
  57991. BABYLON.serialize()
  57992. ], FollowCamera.prototype, "radius", void 0);
  57993. __decorate([
  57994. BABYLON.serialize()
  57995. ], FollowCamera.prototype, "rotationOffset", void 0);
  57996. __decorate([
  57997. BABYLON.serialize()
  57998. ], FollowCamera.prototype, "heightOffset", void 0);
  57999. __decorate([
  58000. BABYLON.serialize()
  58001. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  58002. __decorate([
  58003. BABYLON.serialize()
  58004. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  58005. __decorate([
  58006. BABYLON.serializeAsMeshReference("lockedTargetId")
  58007. ], FollowCamera.prototype, "lockedTarget", void 0);
  58008. return FollowCamera;
  58009. }(BABYLON.TargetCamera));
  58010. BABYLON.FollowCamera = FollowCamera;
  58011. var ArcFollowCamera = /** @class */ (function (_super) {
  58012. __extends(ArcFollowCamera, _super);
  58013. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  58014. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  58015. _this.alpha = alpha;
  58016. _this.beta = beta;
  58017. _this.radius = radius;
  58018. _this.target = target;
  58019. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  58020. _this.follow();
  58021. return _this;
  58022. }
  58023. ArcFollowCamera.prototype.follow = function () {
  58024. if (!this.target) {
  58025. return;
  58026. }
  58027. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  58028. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  58029. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  58030. var targetPosition = this.target.getAbsolutePosition();
  58031. this.position = targetPosition.add(this._cartesianCoordinates);
  58032. this.setTarget(targetPosition);
  58033. };
  58034. ArcFollowCamera.prototype._checkInputs = function () {
  58035. _super.prototype._checkInputs.call(this);
  58036. this.follow();
  58037. };
  58038. ArcFollowCamera.prototype.getClassName = function () {
  58039. return "ArcFollowCamera";
  58040. };
  58041. return ArcFollowCamera;
  58042. }(BABYLON.TargetCamera));
  58043. BABYLON.ArcFollowCamera = ArcFollowCamera;
  58044. })(BABYLON || (BABYLON = {}));
  58045. //# sourceMappingURL=babylon.followCamera.js.map
  58046. var BABYLON;
  58047. (function (BABYLON) {
  58048. // We're mainly based on the logic defined into the FreeCamera code
  58049. var UniversalCamera = /** @class */ (function (_super) {
  58050. __extends(UniversalCamera, _super);
  58051. //-- end properties for backward compatibility for inputs
  58052. function UniversalCamera(name, position, scene) {
  58053. var _this = _super.call(this, name, position, scene) || this;
  58054. _this.inputs.addGamepad();
  58055. return _this;
  58056. }
  58057. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  58058. //-- Begin properties for backward compatibility for inputs
  58059. get: function () {
  58060. var gamepad = this.inputs.attached["gamepad"];
  58061. if (gamepad)
  58062. return gamepad.gamepadAngularSensibility;
  58063. return 0;
  58064. },
  58065. set: function (value) {
  58066. var gamepad = this.inputs.attached["gamepad"];
  58067. if (gamepad)
  58068. gamepad.gamepadAngularSensibility = value;
  58069. },
  58070. enumerable: true,
  58071. configurable: true
  58072. });
  58073. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  58074. get: function () {
  58075. var gamepad = this.inputs.attached["gamepad"];
  58076. if (gamepad)
  58077. return gamepad.gamepadMoveSensibility;
  58078. return 0;
  58079. },
  58080. set: function (value) {
  58081. var gamepad = this.inputs.attached["gamepad"];
  58082. if (gamepad)
  58083. gamepad.gamepadMoveSensibility = value;
  58084. },
  58085. enumerable: true,
  58086. configurable: true
  58087. });
  58088. UniversalCamera.prototype.getClassName = function () {
  58089. return "UniversalCamera";
  58090. };
  58091. return UniversalCamera;
  58092. }(BABYLON.TouchCamera));
  58093. BABYLON.UniversalCamera = UniversalCamera;
  58094. })(BABYLON || (BABYLON = {}));
  58095. //# sourceMappingURL=babylon.universalCamera.js.map
  58096. var BABYLON;
  58097. (function (BABYLON) {
  58098. // We're mainly based on the logic defined into the FreeCamera code
  58099. var GamepadCamera = /** @class */ (function (_super) {
  58100. __extends(GamepadCamera, _super);
  58101. //-- end properties for backward compatibility for inputs
  58102. function GamepadCamera(name, position, scene) {
  58103. return _super.call(this, name, position, scene) || this;
  58104. }
  58105. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  58106. //-- Begin properties for backward compatibility for inputs
  58107. get: function () {
  58108. var gamepad = this.inputs.attached["gamepad"];
  58109. if (gamepad)
  58110. return gamepad.gamepadAngularSensibility;
  58111. return 0;
  58112. },
  58113. set: function (value) {
  58114. var gamepad = this.inputs.attached["gamepad"];
  58115. if (gamepad)
  58116. gamepad.gamepadAngularSensibility = value;
  58117. },
  58118. enumerable: true,
  58119. configurable: true
  58120. });
  58121. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  58122. get: function () {
  58123. var gamepad = this.inputs.attached["gamepad"];
  58124. if (gamepad)
  58125. return gamepad.gamepadMoveSensibility;
  58126. return 0;
  58127. },
  58128. set: function (value) {
  58129. var gamepad = this.inputs.attached["gamepad"];
  58130. if (gamepad)
  58131. gamepad.gamepadMoveSensibility = value;
  58132. },
  58133. enumerable: true,
  58134. configurable: true
  58135. });
  58136. GamepadCamera.prototype.getClassName = function () {
  58137. return "GamepadCamera";
  58138. };
  58139. return GamepadCamera;
  58140. }(BABYLON.UniversalCamera));
  58141. BABYLON.GamepadCamera = GamepadCamera;
  58142. })(BABYLON || (BABYLON = {}));
  58143. //# sourceMappingURL=babylon.gamepadCamera.js.map
  58144. var BABYLON;
  58145. (function (BABYLON) {
  58146. var PostProcessRenderPipelineManager = /** @class */ (function () {
  58147. function PostProcessRenderPipelineManager() {
  58148. this._renderPipelines = {};
  58149. }
  58150. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  58151. this._renderPipelines[renderPipeline._name] = renderPipeline;
  58152. };
  58153. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  58154. if (unique === void 0) { unique = false; }
  58155. var renderPipeline = this._renderPipelines[renderPipelineName];
  58156. if (!renderPipeline) {
  58157. return;
  58158. }
  58159. renderPipeline._attachCameras(cameras, unique);
  58160. };
  58161. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  58162. var renderPipeline = this._renderPipelines[renderPipelineName];
  58163. if (!renderPipeline) {
  58164. return;
  58165. }
  58166. renderPipeline._detachCameras(cameras);
  58167. };
  58168. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  58169. var renderPipeline = this._renderPipelines[renderPipelineName];
  58170. if (!renderPipeline) {
  58171. return;
  58172. }
  58173. renderPipeline._enableEffect(renderEffectName, cameras);
  58174. };
  58175. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  58176. var renderPipeline = this._renderPipelines[renderPipelineName];
  58177. if (!renderPipeline) {
  58178. return;
  58179. }
  58180. renderPipeline._disableEffect(renderEffectName, cameras);
  58181. };
  58182. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  58183. var renderPipeline = this._renderPipelines[renderPipelineName];
  58184. if (!renderPipeline) {
  58185. return;
  58186. }
  58187. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  58188. };
  58189. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  58190. var renderPipeline = this._renderPipelines[renderPipelineName];
  58191. if (!renderPipeline) {
  58192. return;
  58193. }
  58194. renderPipeline._disableDisplayOnlyPass(cameras);
  58195. };
  58196. PostProcessRenderPipelineManager.prototype.update = function () {
  58197. for (var renderPipelineName in this._renderPipelines) {
  58198. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  58199. var pipeline = this._renderPipelines[renderPipelineName];
  58200. if (!pipeline.isSupported) {
  58201. pipeline.dispose();
  58202. delete this._renderPipelines[renderPipelineName];
  58203. }
  58204. else {
  58205. pipeline._update();
  58206. }
  58207. }
  58208. }
  58209. };
  58210. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  58211. for (var renderPipelineName in this._renderPipelines) {
  58212. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  58213. var pipeline = this._renderPipelines[renderPipelineName];
  58214. pipeline._rebuild();
  58215. }
  58216. }
  58217. };
  58218. PostProcessRenderPipelineManager.prototype.dispose = function () {
  58219. for (var renderPipelineName in this._renderPipelines) {
  58220. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  58221. var pipeline = this._renderPipelines[renderPipelineName];
  58222. pipeline.dispose();
  58223. }
  58224. }
  58225. };
  58226. return PostProcessRenderPipelineManager;
  58227. }());
  58228. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  58229. })(BABYLON || (BABYLON = {}));
  58230. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  58231. var BABYLON;
  58232. (function (BABYLON) {
  58233. var PostProcessRenderPass = /** @class */ (function () {
  58234. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  58235. this._refCount = 0;
  58236. this._name = name;
  58237. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  58238. this.setRenderList(renderList);
  58239. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  58240. this._renderTexture.onAfterRenderObservable.add(afterRender);
  58241. this._scene = scene;
  58242. this._renderList = renderList;
  58243. }
  58244. // private
  58245. PostProcessRenderPass.prototype._incRefCount = function () {
  58246. if (this._refCount === 0) {
  58247. this._scene.customRenderTargets.push(this._renderTexture);
  58248. }
  58249. return ++this._refCount;
  58250. };
  58251. PostProcessRenderPass.prototype._decRefCount = function () {
  58252. this._refCount--;
  58253. if (this._refCount <= 0) {
  58254. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  58255. }
  58256. return this._refCount;
  58257. };
  58258. PostProcessRenderPass.prototype._update = function () {
  58259. this.setRenderList(this._renderList);
  58260. };
  58261. // public
  58262. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  58263. this._renderTexture.renderList = renderList;
  58264. };
  58265. PostProcessRenderPass.prototype.getRenderTexture = function () {
  58266. return this._renderTexture;
  58267. };
  58268. return PostProcessRenderPass;
  58269. }());
  58270. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  58271. })(BABYLON || (BABYLON = {}));
  58272. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  58273. var BABYLON;
  58274. (function (BABYLON) {
  58275. var PostProcessRenderEffect = /** @class */ (function () {
  58276. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  58277. this._name = name;
  58278. this._singleInstance = singleInstance || true;
  58279. this._getPostProcess = getPostProcess;
  58280. this._cameras = {};
  58281. this._indicesForCamera = {};
  58282. this._postProcesses = {};
  58283. this._renderPasses = {};
  58284. this._renderEffectAsPasses = {};
  58285. }
  58286. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  58287. get: function () {
  58288. for (var index in this._postProcesses) {
  58289. if (!this._postProcesses[index].isSupported) {
  58290. return false;
  58291. }
  58292. }
  58293. return true;
  58294. },
  58295. enumerable: true,
  58296. configurable: true
  58297. });
  58298. PostProcessRenderEffect.prototype._update = function () {
  58299. for (var renderPassName in this._renderPasses) {
  58300. this._renderPasses[renderPassName]._update();
  58301. }
  58302. };
  58303. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  58304. this._renderPasses[renderPass._name] = renderPass;
  58305. this._linkParameters();
  58306. };
  58307. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  58308. delete this._renderPasses[renderPass._name];
  58309. this._linkParameters();
  58310. };
  58311. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  58312. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  58313. this._linkParameters();
  58314. };
  58315. PostProcessRenderEffect.prototype.getPass = function (passName) {
  58316. for (var renderPassName in this._renderPasses) {
  58317. if (renderPassName === passName) {
  58318. return this._renderPasses[passName];
  58319. }
  58320. }
  58321. return null;
  58322. };
  58323. PostProcessRenderEffect.prototype.emptyPasses = function () {
  58324. this._renderPasses = {};
  58325. this._linkParameters();
  58326. };
  58327. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  58328. var cameraKey;
  58329. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58330. if (!cams) {
  58331. return;
  58332. }
  58333. for (var i = 0; i < cams.length; i++) {
  58334. var camera = cams[i];
  58335. var cameraName = camera.name;
  58336. if (this._singleInstance) {
  58337. cameraKey = 0;
  58338. }
  58339. else {
  58340. cameraKey = cameraName;
  58341. }
  58342. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  58343. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  58344. if (!this._indicesForCamera[cameraName]) {
  58345. this._indicesForCamera[cameraName] = [];
  58346. }
  58347. this._indicesForCamera[cameraName].push(index);
  58348. if (!this._cameras[cameraName]) {
  58349. this._cameras[cameraName] = camera;
  58350. }
  58351. for (var passName in this._renderPasses) {
  58352. this._renderPasses[passName]._incRefCount();
  58353. }
  58354. }
  58355. this._linkParameters();
  58356. };
  58357. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  58358. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58359. if (!cams) {
  58360. return;
  58361. }
  58362. for (var i = 0; i < cams.length; i++) {
  58363. var camera = cams[i];
  58364. var cameraName = camera.name;
  58365. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  58366. if (this._cameras[cameraName]) {
  58367. //this._indicesForCamera.splice(index, 1);
  58368. this._cameras[cameraName] = null;
  58369. }
  58370. for (var passName in this._renderPasses) {
  58371. this._renderPasses[passName]._decRefCount();
  58372. }
  58373. }
  58374. };
  58375. PostProcessRenderEffect.prototype._enable = function (cameras) {
  58376. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58377. if (!cams) {
  58378. return;
  58379. }
  58380. for (var i = 0; i < cams.length; i++) {
  58381. var camera = cams[i];
  58382. var cameraName = camera.name;
  58383. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  58384. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  58385. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  58386. }
  58387. }
  58388. for (var passName in this._renderPasses) {
  58389. this._renderPasses[passName]._incRefCount();
  58390. }
  58391. }
  58392. };
  58393. PostProcessRenderEffect.prototype._disable = function (cameras) {
  58394. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58395. if (!cams) {
  58396. return;
  58397. }
  58398. for (var i = 0; i < cams.length; i++) {
  58399. var camera = cams[i];
  58400. var cameraName = camera.Name;
  58401. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  58402. for (var passName in this._renderPasses) {
  58403. this._renderPasses[passName]._decRefCount();
  58404. }
  58405. }
  58406. };
  58407. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  58408. if (this._singleInstance) {
  58409. return this._postProcesses[0];
  58410. }
  58411. else {
  58412. if (!camera) {
  58413. return null;
  58414. }
  58415. return this._postProcesses[camera.name];
  58416. }
  58417. };
  58418. PostProcessRenderEffect.prototype._linkParameters = function () {
  58419. var _this = this;
  58420. for (var index in this._postProcesses) {
  58421. if (this.applyParameters) {
  58422. this.applyParameters(this._postProcesses[index]);
  58423. }
  58424. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  58425. _this._linkTextures(effect);
  58426. });
  58427. }
  58428. };
  58429. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  58430. for (var renderPassName in this._renderPasses) {
  58431. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  58432. }
  58433. for (var renderEffectName in this._renderEffectAsPasses) {
  58434. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  58435. }
  58436. };
  58437. return PostProcessRenderEffect;
  58438. }());
  58439. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  58440. })(BABYLON || (BABYLON = {}));
  58441. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  58442. var BABYLON;
  58443. (function (BABYLON) {
  58444. var PostProcessRenderPipeline = /** @class */ (function () {
  58445. function PostProcessRenderPipeline(engine, name) {
  58446. this._engine = engine;
  58447. this._name = name;
  58448. this._renderEffects = {};
  58449. this._renderEffectsForIsolatedPass = new Array();
  58450. this._cameras = [];
  58451. }
  58452. PostProcessRenderPipeline.prototype.getClassName = function () {
  58453. return "PostProcessRenderPipeline";
  58454. };
  58455. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  58456. get: function () {
  58457. for (var renderEffectName in this._renderEffects) {
  58458. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  58459. if (!this._renderEffects[renderEffectName].isSupported) {
  58460. return false;
  58461. }
  58462. }
  58463. }
  58464. return true;
  58465. },
  58466. enumerable: true,
  58467. configurable: true
  58468. });
  58469. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  58470. this._renderEffects[renderEffect._name] = renderEffect;
  58471. };
  58472. // private
  58473. PostProcessRenderPipeline.prototype._rebuild = function () {
  58474. };
  58475. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  58476. var renderEffects = this._renderEffects[renderEffectName];
  58477. if (!renderEffects) {
  58478. return;
  58479. }
  58480. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  58481. };
  58482. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  58483. var renderEffects = this._renderEffects[renderEffectName];
  58484. if (!renderEffects) {
  58485. return;
  58486. }
  58487. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  58488. };
  58489. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  58490. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58491. if (!cams) {
  58492. return;
  58493. }
  58494. var indicesToDelete = [];
  58495. var i;
  58496. for (i = 0; i < cams.length; i++) {
  58497. var camera = cams[i];
  58498. var cameraName = camera.name;
  58499. if (this._cameras.indexOf(camera) === -1) {
  58500. this._cameras[cameraName] = camera;
  58501. }
  58502. else if (unique) {
  58503. indicesToDelete.push(i);
  58504. }
  58505. }
  58506. for (i = 0; i < indicesToDelete.length; i++) {
  58507. cameras.splice(indicesToDelete[i], 1);
  58508. }
  58509. for (var renderEffectName in this._renderEffects) {
  58510. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  58511. this._renderEffects[renderEffectName]._attachCameras(cams);
  58512. }
  58513. }
  58514. };
  58515. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  58516. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58517. if (!cams) {
  58518. return;
  58519. }
  58520. for (var renderEffectName in this._renderEffects) {
  58521. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  58522. this._renderEffects[renderEffectName]._detachCameras(cams);
  58523. }
  58524. }
  58525. for (var i = 0; i < cams.length; i++) {
  58526. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  58527. }
  58528. };
  58529. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  58530. var _this = this;
  58531. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58532. if (!cams) {
  58533. return;
  58534. }
  58535. var pass = null;
  58536. var renderEffectName;
  58537. for (renderEffectName in this._renderEffects) {
  58538. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  58539. pass = this._renderEffects[renderEffectName].getPass(passName);
  58540. if (pass != null) {
  58541. break;
  58542. }
  58543. }
  58544. }
  58545. if (pass === null) {
  58546. return;
  58547. }
  58548. for (renderEffectName in this._renderEffects) {
  58549. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  58550. this._renderEffects[renderEffectName]._disable(cams);
  58551. }
  58552. }
  58553. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  58554. for (var i = 0; i < cams.length; i++) {
  58555. var camera = cams[i];
  58556. var cameraName = camera.name;
  58557. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, undefined, _this._engine, true); });
  58558. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  58559. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  58560. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  58561. }
  58562. };
  58563. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  58564. var _this = this;
  58565. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58566. if (!cams) {
  58567. return;
  58568. }
  58569. for (var i = 0; i < cams.length; i++) {
  58570. var camera = cams[i];
  58571. var cameraName = camera.name;
  58572. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, undefined, _this._engine, true); });
  58573. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  58574. }
  58575. for (var renderEffectName in this._renderEffects) {
  58576. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  58577. this._renderEffects[renderEffectName]._enable(cams);
  58578. }
  58579. }
  58580. };
  58581. PostProcessRenderPipeline.prototype._update = function () {
  58582. for (var renderEffectName in this._renderEffects) {
  58583. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  58584. this._renderEffects[renderEffectName]._update();
  58585. }
  58586. }
  58587. for (var i = 0; i < this._cameras.length; i++) {
  58588. var cameraName = this._cameras[i].name;
  58589. if (this._renderEffectsForIsolatedPass[cameraName]) {
  58590. this._renderEffectsForIsolatedPass[cameraName]._update();
  58591. }
  58592. }
  58593. };
  58594. PostProcessRenderPipeline.prototype._reset = function () {
  58595. this._renderEffects = {};
  58596. this._renderEffectsForIsolatedPass = new Array();
  58597. };
  58598. PostProcessRenderPipeline.prototype.dispose = function () {
  58599. // Must be implemented by children
  58600. };
  58601. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  58602. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  58603. __decorate([
  58604. BABYLON.serialize()
  58605. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  58606. return PostProcessRenderPipeline;
  58607. }());
  58608. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  58609. })(BABYLON || (BABYLON = {}));
  58610. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  58611. var BABYLON;
  58612. (function (BABYLON) {
  58613. var DepthRenderer = /** @class */ (function () {
  58614. function DepthRenderer(scene, type) {
  58615. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  58616. var _this = this;
  58617. this._scene = scene;
  58618. var engine = scene.getEngine();
  58619. // Render target
  58620. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  58621. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58622. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58623. this._depthMap.refreshRate = 1;
  58624. this._depthMap.renderParticles = false;
  58625. this._depthMap.renderList = null;
  58626. // set default depth value to 1.0 (far away)
  58627. this._depthMap.onClearObservable.add(function (engine) {
  58628. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  58629. });
  58630. // Custom render function
  58631. var renderSubMesh = function (subMesh) {
  58632. var mesh = subMesh.getRenderingMesh();
  58633. var scene = _this._scene;
  58634. var engine = scene.getEngine();
  58635. var material = subMesh.getMaterial();
  58636. if (!material) {
  58637. return;
  58638. }
  58639. // Culling and reverse (right handed system)
  58640. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  58641. // Managing instances
  58642. var batch = mesh._getInstancesRenderList(subMesh._id);
  58643. if (batch.mustReturn) {
  58644. return;
  58645. }
  58646. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  58647. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  58648. engine.enableEffect(_this._effect);
  58649. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  58650. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  58651. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  58652. // Alpha test
  58653. if (material && material.needAlphaTesting()) {
  58654. var alphaTexture = material.getAlphaTestTexture();
  58655. if (alphaTexture) {
  58656. _this._effect.setTexture("diffuseSampler", alphaTexture);
  58657. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  58658. }
  58659. }
  58660. // Bones
  58661. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  58662. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  58663. }
  58664. // Draw
  58665. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  58666. }
  58667. };
  58668. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  58669. var index;
  58670. if (depthOnlySubMeshes.length) {
  58671. engine.setColorWrite(false);
  58672. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  58673. renderSubMesh(depthOnlySubMeshes.data[index]);
  58674. }
  58675. engine.setColorWrite(true);
  58676. }
  58677. for (index = 0; index < opaqueSubMeshes.length; index++) {
  58678. renderSubMesh(opaqueSubMeshes.data[index]);
  58679. }
  58680. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  58681. renderSubMesh(alphaTestSubMeshes.data[index]);
  58682. }
  58683. };
  58684. }
  58685. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  58686. var material = subMesh.getMaterial();
  58687. if (material.disableDepthWrite) {
  58688. return false;
  58689. }
  58690. var defines = [];
  58691. var attribs = [BABYLON.VertexBuffer.PositionKind];
  58692. var mesh = subMesh.getMesh();
  58693. // Alpha test
  58694. if (material && material.needAlphaTesting()) {
  58695. defines.push("#define ALPHATEST");
  58696. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58697. attribs.push(BABYLON.VertexBuffer.UVKind);
  58698. defines.push("#define UV1");
  58699. }
  58700. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  58701. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  58702. defines.push("#define UV2");
  58703. }
  58704. }
  58705. // Bones
  58706. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58707. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58708. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58709. if (mesh.numBoneInfluencers > 4) {
  58710. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58711. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58712. }
  58713. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58714. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  58715. }
  58716. else {
  58717. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58718. }
  58719. // Instances
  58720. if (useInstances) {
  58721. defines.push("#define INSTANCES");
  58722. attribs.push("world0");
  58723. attribs.push("world1");
  58724. attribs.push("world2");
  58725. attribs.push("world3");
  58726. }
  58727. // Get correct effect
  58728. var join = defines.join("\n");
  58729. if (this._cachedDefines !== join) {
  58730. this._cachedDefines = join;
  58731. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  58732. }
  58733. return this._effect.isReady();
  58734. };
  58735. DepthRenderer.prototype.getDepthMap = function () {
  58736. return this._depthMap;
  58737. };
  58738. // Methods
  58739. DepthRenderer.prototype.dispose = function () {
  58740. this._depthMap.dispose();
  58741. };
  58742. return DepthRenderer;
  58743. }());
  58744. BABYLON.DepthRenderer = DepthRenderer;
  58745. })(BABYLON || (BABYLON = {}));
  58746. //# sourceMappingURL=babylon.depthRenderer.js.map
  58747. var BABYLON;
  58748. (function (BABYLON) {
  58749. var SSAORenderingPipeline = /** @class */ (function (_super) {
  58750. __extends(SSAORenderingPipeline, _super);
  58751. /**
  58752. * @constructor
  58753. * @param {string} name - The rendering pipeline name
  58754. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58755. * @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 }
  58756. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58757. */
  58758. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  58759. var _this = _super.call(this, scene.getEngine(), name) || this;
  58760. // Members
  58761. /**
  58762. * The PassPostProcess id in the pipeline that contains the original scene color
  58763. * @type {string}
  58764. */
  58765. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  58766. /**
  58767. * The SSAO PostProcess id in the pipeline
  58768. * @type {string}
  58769. */
  58770. _this.SSAORenderEffect = "SSAORenderEffect";
  58771. /**
  58772. * The horizontal blur PostProcess id in the pipeline
  58773. * @type {string}
  58774. */
  58775. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  58776. /**
  58777. * The vertical blur PostProcess id in the pipeline
  58778. * @type {string}
  58779. */
  58780. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  58781. /**
  58782. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  58783. * @type {string}
  58784. */
  58785. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  58786. /**
  58787. * The output strength of the SSAO post-process. Default value is 1.0.
  58788. * @type {number}
  58789. */
  58790. _this.totalStrength = 1.0;
  58791. /**
  58792. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  58793. * @type {number}
  58794. */
  58795. _this.radius = 0.0001;
  58796. /**
  58797. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  58798. * Must not be equal to fallOff and superior to fallOff.
  58799. * Default value is 0.975
  58800. * @type {number}
  58801. */
  58802. _this.area = 0.0075;
  58803. /**
  58804. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  58805. * Must not be equal to area and inferior to area.
  58806. * Default value is 0.0
  58807. * @type {number}
  58808. */
  58809. _this.fallOff = 0.000001;
  58810. /**
  58811. * The base color of the SSAO post-process
  58812. * The final result is "base + ssao" between [0, 1]
  58813. * @type {number}
  58814. */
  58815. _this.base = 0.5;
  58816. _this._firstUpdate = true;
  58817. _this._scene = scene;
  58818. // Set up assets
  58819. _this._createRandomTexture();
  58820. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  58821. var ssaoRatio = ratio.ssaoRatio || ratio;
  58822. var combineRatio = ratio.combineRatio || ratio;
  58823. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  58824. _this._createSSAOPostProcess(ssaoRatio);
  58825. _this._createBlurPostProcess(ssaoRatio);
  58826. _this._createSSAOCombinePostProcess(combineRatio);
  58827. // Set up pipeline
  58828. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  58829. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  58830. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  58831. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  58832. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  58833. // Finish
  58834. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58835. if (cameras)
  58836. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  58837. return _this;
  58838. }
  58839. // Public Methods
  58840. /**
  58841. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  58842. */
  58843. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  58844. if (disableDepthRender === void 0) { disableDepthRender = false; }
  58845. for (var i = 0; i < this._scene.cameras.length; i++) {
  58846. var camera = this._scene.cameras[i];
  58847. this._originalColorPostProcess.dispose(camera);
  58848. this._ssaoPostProcess.dispose(camera);
  58849. this._blurHPostProcess.dispose(camera);
  58850. this._blurVPostProcess.dispose(camera);
  58851. this._ssaoCombinePostProcess.dispose(camera);
  58852. }
  58853. this._randomTexture.dispose();
  58854. if (disableDepthRender)
  58855. this._scene.disableDepthRenderer();
  58856. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  58857. _super.prototype.dispose.call(this);
  58858. };
  58859. // Private Methods
  58860. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  58861. var _this = this;
  58862. var size = 16;
  58863. this._blurHPostProcess = new BABYLON.BlurPostProcess("BlurH", new BABYLON.Vector2(1, 0), size, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  58864. this._blurVPostProcess = new BABYLON.BlurPostProcess("BlurV", new BABYLON.Vector2(0, 1), size, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  58865. this._blurHPostProcess.onActivateObservable.add(function () {
  58866. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  58867. _this._blurHPostProcess.kernel = size * dw;
  58868. });
  58869. this._blurVPostProcess.onActivateObservable.add(function () {
  58870. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  58871. _this._blurVPostProcess.kernel = size * dw;
  58872. });
  58873. };
  58874. SSAORenderingPipeline.prototype._rebuild = function () {
  58875. this._firstUpdate = true;
  58876. _super.prototype._rebuild.call(this);
  58877. };
  58878. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  58879. var _this = this;
  58880. var numSamples = 16;
  58881. var sampleSphere = [
  58882. 0.5381, 0.1856, -0.4319,
  58883. 0.1379, 0.2486, 0.4430,
  58884. 0.3371, 0.5679, -0.0057,
  58885. -0.6999, -0.0451, -0.0019,
  58886. 0.0689, -0.1598, -0.8547,
  58887. 0.0560, 0.0069, -0.1843,
  58888. -0.0146, 0.1402, 0.0762,
  58889. 0.0100, -0.1924, -0.0344,
  58890. -0.3577, -0.5301, -0.4358,
  58891. -0.3169, 0.1063, 0.0158,
  58892. 0.0103, -0.5869, 0.0046,
  58893. -0.0897, -0.4940, 0.3287,
  58894. 0.7119, -0.0154, -0.0918,
  58895. -0.0533, 0.0596, -0.5411,
  58896. 0.0352, -0.0631, 0.5460,
  58897. -0.4776, 0.2847, -0.0271
  58898. ];
  58899. var samplesFactor = 1.0 / numSamples;
  58900. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  58901. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  58902. "area", "fallOff", "base", "range", "viewport"
  58903. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  58904. this._ssaoPostProcess.onApply = function (effect) {
  58905. if (_this._firstUpdate) {
  58906. effect.setArray3("sampleSphere", sampleSphere);
  58907. effect.setFloat("samplesFactor", samplesFactor);
  58908. effect.setFloat("randTextureTiles", 4.0);
  58909. }
  58910. effect.setFloat("totalStrength", _this.totalStrength);
  58911. effect.setFloat("radius", _this.radius);
  58912. effect.setFloat("area", _this.area);
  58913. effect.setFloat("fallOff", _this.fallOff);
  58914. effect.setFloat("base", _this.base);
  58915. effect.setTexture("textureSampler", _this._depthTexture);
  58916. effect.setTexture("randomSampler", _this._randomTexture);
  58917. };
  58918. };
  58919. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  58920. var _this = this;
  58921. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  58922. this._ssaoCombinePostProcess.onApply = function (effect) {
  58923. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  58924. };
  58925. };
  58926. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  58927. var size = 512;
  58928. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  58929. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58930. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58931. var context = this._randomTexture.getContext();
  58932. var rand = function (min, max) {
  58933. return Math.random() * (max - min) + min;
  58934. };
  58935. var randVector = BABYLON.Vector3.Zero();
  58936. for (var x = 0; x < size; x++) {
  58937. for (var y = 0; y < size; y++) {
  58938. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  58939. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  58940. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  58941. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  58942. context.fillRect(x, y, 1, 1);
  58943. }
  58944. }
  58945. this._randomTexture.update(false);
  58946. };
  58947. __decorate([
  58948. BABYLON.serialize()
  58949. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  58950. __decorate([
  58951. BABYLON.serialize()
  58952. ], SSAORenderingPipeline.prototype, "radius", void 0);
  58953. __decorate([
  58954. BABYLON.serialize()
  58955. ], SSAORenderingPipeline.prototype, "area", void 0);
  58956. __decorate([
  58957. BABYLON.serialize()
  58958. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  58959. __decorate([
  58960. BABYLON.serialize()
  58961. ], SSAORenderingPipeline.prototype, "base", void 0);
  58962. return SSAORenderingPipeline;
  58963. }(BABYLON.PostProcessRenderPipeline));
  58964. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  58965. })(BABYLON || (BABYLON = {}));
  58966. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  58967. var BABYLON;
  58968. (function (BABYLON) {
  58969. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  58970. __extends(SSAO2RenderingPipeline, _super);
  58971. /**
  58972. * @constructor
  58973. * @param {string} name - The rendering pipeline name
  58974. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58975. * @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 }
  58976. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58977. */
  58978. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  58979. var _this = _super.call(this, scene.getEngine(), name) || this;
  58980. // Members
  58981. /**
  58982. * The PassPostProcess id in the pipeline that contains the original scene color
  58983. * @type {string}
  58984. */
  58985. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  58986. /**
  58987. * The SSAO PostProcess id in the pipeline
  58988. * @type {string}
  58989. */
  58990. _this.SSAORenderEffect = "SSAORenderEffect";
  58991. /**
  58992. * The horizontal blur PostProcess id in the pipeline
  58993. * @type {string}
  58994. */
  58995. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  58996. /**
  58997. * The vertical blur PostProcess id in the pipeline
  58998. * @type {string}
  58999. */
  59000. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  59001. /**
  59002. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  59003. * @type {string}
  59004. */
  59005. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  59006. /**
  59007. * The output strength of the SSAO post-process. Default value is 1.0.
  59008. * @type {number}
  59009. */
  59010. _this.totalStrength = 1.0;
  59011. /**
  59012. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  59013. * @type {number}
  59014. */
  59015. _this.maxZ = 100.0;
  59016. /**
  59017. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  59018. * @type {number}
  59019. */
  59020. _this.minZAspect = 0.2;
  59021. /**
  59022. * Number of samples used for the SSAO calculations. Default value is 8
  59023. * @type {number}
  59024. */
  59025. _this._samples = 8;
  59026. /**
  59027. * Are we using bilateral blur ?
  59028. * @type {boolean}
  59029. */
  59030. _this._expensiveBlur = true;
  59031. /**
  59032. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  59033. * @type {number}
  59034. */
  59035. _this.radius = 2.0;
  59036. /**
  59037. * The base color of the SSAO post-process
  59038. * The final result is "base + ssao" between [0, 1]
  59039. * @type {number}
  59040. */
  59041. _this.base = 0.1;
  59042. _this._firstUpdate = true;
  59043. _this._scene = scene;
  59044. if (!_this.isSupported) {
  59045. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  59046. return _this;
  59047. }
  59048. var ssaoRatio = ratio.ssaoRatio || ratio;
  59049. var blurRatio = ratio.blurRatio || ratio;
  59050. // Set up assets
  59051. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  59052. _this._createRandomTexture();
  59053. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  59054. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  59055. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  59056. _this._createSSAOPostProcess(1.0);
  59057. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  59058. _this._createSSAOCombinePostProcess(blurRatio);
  59059. // Set up pipeline
  59060. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  59061. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  59062. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  59063. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  59064. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  59065. // Finish
  59066. scene.postProcessRenderPipelineManager.addPipeline(_this);
  59067. if (cameras)
  59068. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  59069. return _this;
  59070. }
  59071. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  59072. get: function () {
  59073. return this._samples;
  59074. },
  59075. set: function (n) {
  59076. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  59077. this._samples = n;
  59078. this._sampleSphere = this._generateHemisphere();
  59079. this._firstUpdate = true;
  59080. },
  59081. enumerable: true,
  59082. configurable: true
  59083. });
  59084. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  59085. get: function () {
  59086. return this._expensiveBlur;
  59087. },
  59088. set: function (b) {
  59089. 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"]);
  59090. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  59091. this._expensiveBlur = b;
  59092. this._firstUpdate = true;
  59093. },
  59094. enumerable: true,
  59095. configurable: true
  59096. });
  59097. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  59098. /**
  59099. * Support test.
  59100. * @type {boolean}
  59101. */
  59102. get: function () {
  59103. var engine = BABYLON.Engine.LastCreatedEngine;
  59104. if (!engine) {
  59105. return false;
  59106. }
  59107. return engine.getCaps().drawBuffersExtension;
  59108. },
  59109. enumerable: true,
  59110. configurable: true
  59111. });
  59112. // Public Methods
  59113. /**
  59114. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  59115. */
  59116. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  59117. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  59118. for (var i = 0; i < this._scene.cameras.length; i++) {
  59119. var camera = this._scene.cameras[i];
  59120. this._originalColorPostProcess.dispose(camera);
  59121. this._ssaoPostProcess.dispose(camera);
  59122. this._blurHPostProcess.dispose(camera);
  59123. this._blurVPostProcess.dispose(camera);
  59124. this._ssaoCombinePostProcess.dispose(camera);
  59125. }
  59126. this._randomTexture.dispose();
  59127. if (disableGeometryBufferRenderer)
  59128. this._scene.disableGeometryBufferRenderer();
  59129. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  59130. _super.prototype.dispose.call(this);
  59131. };
  59132. // Private Methods
  59133. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  59134. var _this = this;
  59135. this._samplerOffsets = [];
  59136. var expensive = this.expensiveBlur;
  59137. for (var i = -8; i < 8; i++) {
  59138. this._samplerOffsets.push(i * 2 + 0.5);
  59139. }
  59140. 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");
  59141. this._blurHPostProcess.onApply = function (effect) {
  59142. if (!_this._scene.activeCamera) {
  59143. return;
  59144. }
  59145. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  59146. effect.setFloat("near", _this._scene.activeCamera.minZ);
  59147. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  59148. effect.setFloat("radius", _this.radius);
  59149. effect.setTexture("depthSampler", _this._depthTexture);
  59150. if (_this._firstUpdate) {
  59151. effect.setArray("samplerOffsets", _this._samplerOffsets);
  59152. }
  59153. };
  59154. 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");
  59155. this._blurVPostProcess.onApply = function (effect) {
  59156. if (!_this._scene.activeCamera) {
  59157. return;
  59158. }
  59159. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  59160. effect.setFloat("near", _this._scene.activeCamera.minZ);
  59161. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  59162. effect.setFloat("radius", _this.radius);
  59163. effect.setTexture("depthSampler", _this._depthTexture);
  59164. if (_this._firstUpdate) {
  59165. effect.setArray("samplerOffsets", _this._samplerOffsets);
  59166. _this._firstUpdate = false;
  59167. }
  59168. };
  59169. };
  59170. SSAO2RenderingPipeline.prototype._rebuild = function () {
  59171. this._firstUpdate = true;
  59172. _super.prototype._rebuild.call(this);
  59173. };
  59174. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  59175. var numSamples = this.samples;
  59176. var result = [];
  59177. var vector, scale;
  59178. var rand = function (min, max) {
  59179. return Math.random() * (max - min) + min;
  59180. };
  59181. var i = 0;
  59182. while (i < numSamples) {
  59183. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  59184. vector.normalize();
  59185. scale = i / numSamples;
  59186. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  59187. vector.scaleInPlace(scale);
  59188. result.push(vector.x, vector.y, vector.z);
  59189. i++;
  59190. }
  59191. return result;
  59192. };
  59193. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  59194. var _this = this;
  59195. var numSamples = this.samples;
  59196. this._sampleSphere = this._generateHemisphere();
  59197. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  59198. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  59199. "base", "range", "projection", "near", "far", "texelSize",
  59200. "xViewport", "yViewport", "maxZ", "minZAspect"
  59201. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  59202. this._ssaoPostProcess.onApply = function (effect) {
  59203. if (_this._firstUpdate) {
  59204. effect.setArray3("sampleSphere", _this._sampleSphere);
  59205. effect.setFloat("randTextureTiles", 4.0);
  59206. }
  59207. if (!_this._scene.activeCamera) {
  59208. return;
  59209. }
  59210. effect.setFloat("samplesFactor", 1 / _this.samples);
  59211. effect.setFloat("totalStrength", _this.totalStrength);
  59212. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  59213. effect.setFloat("radius", _this.radius);
  59214. effect.setFloat("maxZ", _this.maxZ);
  59215. effect.setFloat("minZAspect", _this.minZAspect);
  59216. effect.setFloat("base", _this.base);
  59217. effect.setFloat("near", _this._scene.activeCamera.minZ);
  59218. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  59219. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  59220. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  59221. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  59222. effect.setTexture("textureSampler", _this._depthTexture);
  59223. effect.setTexture("normalSampler", _this._normalTexture);
  59224. effect.setTexture("randomSampler", _this._randomTexture);
  59225. };
  59226. };
  59227. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  59228. var _this = this;
  59229. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  59230. this._ssaoCombinePostProcess.onApply = function (effect) {
  59231. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  59232. };
  59233. };
  59234. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  59235. var size = 512;
  59236. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  59237. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59238. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59239. var context = this._randomTexture.getContext();
  59240. var rand = function (min, max) {
  59241. return Math.random() * (max - min) + min;
  59242. };
  59243. var randVector = BABYLON.Vector3.Zero();
  59244. for (var x = 0; x < size; x++) {
  59245. for (var y = 0; y < size; y++) {
  59246. randVector.x = rand(0.0, 1.0);
  59247. randVector.y = rand(0.0, 1.0);
  59248. randVector.z = 0.0;
  59249. randVector.normalize();
  59250. randVector.scaleInPlace(255);
  59251. randVector.x = Math.floor(randVector.x);
  59252. randVector.y = Math.floor(randVector.y);
  59253. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  59254. context.fillRect(x, y, 1, 1);
  59255. }
  59256. }
  59257. this._randomTexture.update(false);
  59258. };
  59259. __decorate([
  59260. BABYLON.serialize()
  59261. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  59262. __decorate([
  59263. BABYLON.serialize()
  59264. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  59265. __decorate([
  59266. BABYLON.serialize()
  59267. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  59268. __decorate([
  59269. BABYLON.serialize("samples")
  59270. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  59271. __decorate([
  59272. BABYLON.serialize("expensiveBlur")
  59273. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  59274. __decorate([
  59275. BABYLON.serialize()
  59276. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  59277. __decorate([
  59278. BABYLON.serialize()
  59279. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  59280. return SSAO2RenderingPipeline;
  59281. }(BABYLON.PostProcessRenderPipeline));
  59282. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  59283. })(BABYLON || (BABYLON = {}));
  59284. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  59285. // BABYLON.JS Chromatic Aberration GLSL Shader
  59286. // Author: Olivier Guyot
  59287. // Separates very slightly R, G and B colors on the edges of the screen
  59288. // Inspired by Francois Tarlier & Martins Upitis
  59289. var BABYLON;
  59290. (function (BABYLON) {
  59291. var LensRenderingPipeline = /** @class */ (function (_super) {
  59292. __extends(LensRenderingPipeline, _super);
  59293. /**
  59294. * @constructor
  59295. *
  59296. * Effect parameters are as follow:
  59297. * {
  59298. * chromatic_aberration: number; // from 0 to x (1 for realism)
  59299. * edge_blur: number; // from 0 to x (1 for realism)
  59300. * distortion: number; // from 0 to x (1 for realism)
  59301. * grain_amount: number; // from 0 to 1
  59302. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  59303. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  59304. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  59305. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  59306. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  59307. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  59308. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  59309. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  59310. * }
  59311. * Note: if an effect parameter is unset, effect is disabled
  59312. *
  59313. * @param {string} name - The rendering pipeline name
  59314. * @param {object} parameters - An object containing all parameters (see above)
  59315. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  59316. * @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)
  59317. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  59318. */
  59319. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  59320. if (ratio === void 0) { ratio = 1.0; }
  59321. var _this = _super.call(this, scene.getEngine(), name) || this;
  59322. // Lens effects can be of the following:
  59323. // - chromatic aberration (slight shift of RGB colors)
  59324. // - blur on the edge of the lens
  59325. // - lens distortion
  59326. // - depth-of-field blur & highlights enhancing
  59327. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  59328. // - grain effect (noise or custom texture)
  59329. // Two additional texture samplers are needed:
  59330. // - depth map (for depth-of-field)
  59331. // - grain texture
  59332. /**
  59333. * The chromatic aberration PostProcess id in the pipeline
  59334. * @type {string}
  59335. */
  59336. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  59337. /**
  59338. * The highlights enhancing PostProcess id in the pipeline
  59339. * @type {string}
  59340. */
  59341. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  59342. /**
  59343. * The depth-of-field PostProcess id in the pipeline
  59344. * @type {string}
  59345. */
  59346. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  59347. _this._scene = scene;
  59348. // Fetch texture samplers
  59349. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  59350. if (parameters.grain_texture) {
  59351. _this._grainTexture = parameters.grain_texture;
  59352. }
  59353. else {
  59354. _this._createGrainTexture();
  59355. }
  59356. // save parameters
  59357. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  59358. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  59359. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  59360. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  59361. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  59362. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  59363. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  59364. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  59365. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  59366. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  59367. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  59368. // Create effects
  59369. _this._createChromaticAberrationPostProcess(ratio);
  59370. _this._createHighlightsPostProcess(ratio);
  59371. _this._createDepthOfFieldPostProcess(ratio / 4);
  59372. // Set up pipeline
  59373. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  59374. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  59375. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  59376. if (_this._highlightsGain === -1) {
  59377. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  59378. }
  59379. // Finish
  59380. scene.postProcessRenderPipelineManager.addPipeline(_this);
  59381. if (cameras) {
  59382. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  59383. }
  59384. return _this;
  59385. }
  59386. // public methods (self explanatory)
  59387. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  59388. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  59389. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  59390. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  59391. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  59392. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  59393. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  59394. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  59395. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  59396. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  59397. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  59398. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  59399. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  59400. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  59401. };
  59402. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  59403. this._highlightsPostProcess.updateEffect();
  59404. };
  59405. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  59406. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  59407. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  59408. this._highlightsGain = amount;
  59409. };
  59410. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  59411. if (this._highlightsGain === -1) {
  59412. this._highlightsGain = 1.0;
  59413. }
  59414. this._highlightsThreshold = amount;
  59415. };
  59416. LensRenderingPipeline.prototype.disableHighlights = function () {
  59417. this._highlightsGain = -1;
  59418. };
  59419. /**
  59420. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  59421. */
  59422. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  59423. if (disableDepthRender === void 0) { disableDepthRender = false; }
  59424. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  59425. this._chromaticAberrationPostProcess = null;
  59426. this._highlightsPostProcess = null;
  59427. this._depthOfFieldPostProcess = null;
  59428. this._grainTexture.dispose();
  59429. if (disableDepthRender)
  59430. this._scene.disableDepthRenderer();
  59431. };
  59432. // colors shifting and distortion
  59433. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  59434. var _this = this;
  59435. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  59436. [], // samplers
  59437. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  59438. this._chromaticAberrationPostProcess.onApply = function (effect) {
  59439. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  59440. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  59441. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  59442. };
  59443. };
  59444. // highlights enhancing
  59445. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  59446. var _this = this;
  59447. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  59448. [], // samplers
  59449. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  59450. this._highlightsPostProcess.onApply = function (effect) {
  59451. effect.setFloat('gain', _this._highlightsGain);
  59452. effect.setFloat('threshold', _this._highlightsThreshold);
  59453. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  59454. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  59455. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  59456. };
  59457. };
  59458. // colors shifting and distortion
  59459. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  59460. var _this = this;
  59461. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  59462. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  59463. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  59464. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  59465. this._depthOfFieldPostProcess.onApply = function (effect) {
  59466. effect.setTexture("depthSampler", _this._depthTexture);
  59467. effect.setTexture("grainSampler", _this._grainTexture);
  59468. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  59469. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  59470. effect.setFloat('grain_amount', _this._grainAmount);
  59471. effect.setBool('blur_noise', _this._blurNoise);
  59472. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  59473. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  59474. effect.setFloat('distortion', _this._distortion);
  59475. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  59476. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  59477. effect.setFloat('aperture', _this._dofAperture);
  59478. effect.setFloat('darken', _this._dofDarken);
  59479. effect.setFloat('edge_blur', _this._edgeBlur);
  59480. effect.setBool('highlights', (_this._highlightsGain !== -1));
  59481. if (_this._scene.activeCamera) {
  59482. effect.setFloat('near', _this._scene.activeCamera.minZ);
  59483. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  59484. }
  59485. };
  59486. };
  59487. // creates a black and white random noise texture, 512x512
  59488. LensRenderingPipeline.prototype._createGrainTexture = function () {
  59489. var size = 512;
  59490. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59491. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59492. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59493. var context = this._grainTexture.getContext();
  59494. var rand = function (min, max) {
  59495. return Math.random() * (max - min) + min;
  59496. };
  59497. var value;
  59498. for (var x = 0; x < size; x++) {
  59499. for (var y = 0; y < size; y++) {
  59500. value = Math.floor(rand(0.42, 0.58) * 255);
  59501. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  59502. context.fillRect(x, y, 1, 1);
  59503. }
  59504. }
  59505. this._grainTexture.update(false);
  59506. };
  59507. return LensRenderingPipeline;
  59508. }(BABYLON.PostProcessRenderPipeline));
  59509. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  59510. })(BABYLON || (BABYLON = {}));
  59511. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  59512. var BABYLON;
  59513. (function (BABYLON) {
  59514. var StandardRenderingPipeline = /** @class */ (function (_super) {
  59515. __extends(StandardRenderingPipeline, _super);
  59516. /**
  59517. * @constructor
  59518. * @param {string} name - The rendering pipeline name
  59519. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  59520. * @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)
  59521. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  59522. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  59523. */
  59524. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  59525. if (originalPostProcess === void 0) { originalPostProcess = null; }
  59526. var _this = _super.call(this, scene.getEngine(), name) || this;
  59527. _this.downSampleX4PostProcess = null;
  59528. _this.brightPassPostProcess = null;
  59529. _this.blurHPostProcesses = [];
  59530. _this.blurVPostProcesses = [];
  59531. _this.textureAdderPostProcess = null;
  59532. _this.volumetricLightPostProcess = null;
  59533. _this.volumetricLightSmoothXPostProcess = null;
  59534. _this.volumetricLightSmoothYPostProcess = null;
  59535. _this.volumetricLightMergePostProces = null;
  59536. _this.volumetricLightFinalPostProcess = null;
  59537. _this.luminancePostProcess = null;
  59538. _this.luminanceDownSamplePostProcesses = [];
  59539. _this.hdrPostProcess = null;
  59540. _this.textureAdderFinalPostProcess = null;
  59541. _this.lensFlareFinalPostProcess = null;
  59542. _this.hdrFinalPostProcess = null;
  59543. _this.lensFlarePostProcess = null;
  59544. _this.lensFlareComposePostProcess = null;
  59545. _this.motionBlurPostProcess = null;
  59546. _this.depthOfFieldPostProcess = null;
  59547. // Values
  59548. _this.brightThreshold = 1.0;
  59549. _this.blurWidth = 512.0;
  59550. _this.horizontalBlur = false;
  59551. _this.exposure = 1.0;
  59552. _this.lensTexture = null;
  59553. _this.volumetricLightCoefficient = 0.2;
  59554. _this.volumetricLightPower = 4.0;
  59555. _this.volumetricLightBlurScale = 64.0;
  59556. _this.sourceLight = null;
  59557. _this.hdrMinimumLuminance = 1.0;
  59558. _this.hdrDecreaseRate = 0.5;
  59559. _this.hdrIncreaseRate = 0.5;
  59560. _this.lensColorTexture = null;
  59561. _this.lensFlareStrength = 20.0;
  59562. _this.lensFlareGhostDispersal = 1.4;
  59563. _this.lensFlareHaloWidth = 0.7;
  59564. _this.lensFlareDistortionStrength = 16.0;
  59565. _this.lensStarTexture = null;
  59566. _this.lensFlareDirtTexture = null;
  59567. _this.depthOfFieldDistance = 10.0;
  59568. _this.depthOfFieldBlurWidth = 64.0;
  59569. _this.motionStrength = 1.0;
  59570. // IAnimatable
  59571. _this.animations = [];
  59572. _this._currentDepthOfFieldSource = null;
  59573. _this._hdrCurrentLuminance = 1.0;
  59574. // Getters and setters
  59575. _this._bloomEnabled = true;
  59576. _this._depthOfFieldEnabled = false;
  59577. _this._vlsEnabled = false;
  59578. _this._lensFlareEnabled = false;
  59579. _this._hdrEnabled = false;
  59580. _this._motionBlurEnabled = false;
  59581. _this._motionBlurSamples = 64.0;
  59582. _this._volumetricLightStepsCount = 50.0;
  59583. _this._cameras = cameras || [];
  59584. // Initialize
  59585. _this._scene = scene;
  59586. _this._basePostProcess = originalPostProcess;
  59587. _this._ratio = ratio;
  59588. // Misc
  59589. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59590. // Finish
  59591. scene.postProcessRenderPipelineManager.addPipeline(_this);
  59592. _this._buildPipeline();
  59593. return _this;
  59594. }
  59595. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  59596. get: function () {
  59597. return this._bloomEnabled;
  59598. },
  59599. set: function (enabled) {
  59600. if (this._bloomEnabled === enabled) {
  59601. return;
  59602. }
  59603. this._bloomEnabled = enabled;
  59604. this._buildPipeline();
  59605. },
  59606. enumerable: true,
  59607. configurable: true
  59608. });
  59609. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  59610. get: function () {
  59611. return this._depthOfFieldEnabled;
  59612. },
  59613. set: function (enabled) {
  59614. if (this._depthOfFieldEnabled === enabled) {
  59615. return;
  59616. }
  59617. this._depthOfFieldEnabled = enabled;
  59618. this._buildPipeline();
  59619. },
  59620. enumerable: true,
  59621. configurable: true
  59622. });
  59623. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  59624. get: function () {
  59625. return this._lensFlareEnabled;
  59626. },
  59627. set: function (enabled) {
  59628. if (this._lensFlareEnabled === enabled) {
  59629. return;
  59630. }
  59631. this._lensFlareEnabled = enabled;
  59632. this._buildPipeline();
  59633. },
  59634. enumerable: true,
  59635. configurable: true
  59636. });
  59637. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  59638. get: function () {
  59639. return this._hdrEnabled;
  59640. },
  59641. set: function (enabled) {
  59642. if (this._hdrEnabled === enabled) {
  59643. return;
  59644. }
  59645. this._hdrEnabled = enabled;
  59646. this._buildPipeline();
  59647. },
  59648. enumerable: true,
  59649. configurable: true
  59650. });
  59651. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  59652. get: function () {
  59653. return this._vlsEnabled;
  59654. },
  59655. set: function (enabled) {
  59656. if (this._vlsEnabled === enabled) {
  59657. return;
  59658. }
  59659. if (enabled) {
  59660. var geometry = this._scene.enableGeometryBufferRenderer();
  59661. if (!geometry) {
  59662. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  59663. return;
  59664. }
  59665. }
  59666. this._vlsEnabled = enabled;
  59667. this._buildPipeline();
  59668. },
  59669. enumerable: true,
  59670. configurable: true
  59671. });
  59672. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  59673. get: function () {
  59674. return this._motionBlurEnabled;
  59675. },
  59676. set: function (enabled) {
  59677. if (this._motionBlurEnabled === enabled) {
  59678. return;
  59679. }
  59680. this._motionBlurEnabled = enabled;
  59681. this._buildPipeline();
  59682. },
  59683. enumerable: true,
  59684. configurable: true
  59685. });
  59686. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  59687. get: function () {
  59688. return this._volumetricLightStepsCount;
  59689. },
  59690. set: function (count) {
  59691. if (this.volumetricLightPostProcess) {
  59692. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  59693. }
  59694. this._volumetricLightStepsCount = count;
  59695. },
  59696. enumerable: true,
  59697. configurable: true
  59698. });
  59699. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  59700. get: function () {
  59701. return this._motionBlurSamples;
  59702. },
  59703. set: function (samples) {
  59704. if (this.motionBlurPostProcess) {
  59705. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  59706. }
  59707. this._motionBlurSamples = samples;
  59708. },
  59709. enumerable: true,
  59710. configurable: true
  59711. });
  59712. StandardRenderingPipeline.prototype._buildPipeline = function () {
  59713. var _this = this;
  59714. var ratio = this._ratio;
  59715. var scene = this._scene;
  59716. this._disposePostProcesses();
  59717. this._reset();
  59718. // Create pass post-process
  59719. if (!this._basePostProcess) {
  59720. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  59721. this.originalPostProcess.onApply = function (effect) {
  59722. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  59723. };
  59724. }
  59725. else {
  59726. this.originalPostProcess = this._basePostProcess;
  59727. }
  59728. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  59729. this._currentDepthOfFieldSource = this.originalPostProcess;
  59730. if (this._vlsEnabled) {
  59731. // Create volumetric light
  59732. this._createVolumetricLightPostProcess(scene, ratio);
  59733. // Create volumetric light final post-process
  59734. 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);
  59735. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  59736. }
  59737. if (this._bloomEnabled) {
  59738. // Create down sample X4 post-process
  59739. this._createDownSampleX4PostProcess(scene, ratio / 2);
  59740. // Create bright pass post-process
  59741. this._createBrightPassPostProcess(scene, ratio / 2);
  59742. // Create gaussian blur post-processes (down sampling blurs)
  59743. this._createBlurPostProcesses(scene, ratio / 4, 1);
  59744. // Create texture adder post-process
  59745. this._createTextureAdderPostProcess(scene, ratio);
  59746. // Create depth-of-field source post-process
  59747. 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);
  59748. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  59749. }
  59750. if (this._lensFlareEnabled) {
  59751. // Create lens flare post-process
  59752. this._createLensFlarePostProcess(scene, ratio);
  59753. // Create depth-of-field source post-process post lens-flare and disable it now
  59754. 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);
  59755. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  59756. }
  59757. if (this._hdrEnabled) {
  59758. // Create luminance
  59759. this._createLuminancePostProcesses(scene, this._floatTextureType);
  59760. // Create HDR
  59761. this._createHdrPostProcess(scene, ratio);
  59762. // Create depth-of-field source post-process post hdr and disable it now
  59763. 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);
  59764. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  59765. }
  59766. if (this._depthOfFieldEnabled) {
  59767. // Create gaussian blur used by depth-of-field
  59768. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  59769. // Create depth-of-field post-process
  59770. this._createDepthOfFieldPostProcess(scene, ratio);
  59771. }
  59772. if (this._motionBlurEnabled) {
  59773. // Create motion blur post-process
  59774. this._createMotionBlurPostProcess(scene, ratio);
  59775. }
  59776. if (this._cameras !== null) {
  59777. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  59778. }
  59779. };
  59780. // Down Sample X4 Post-Processs
  59781. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  59782. var _this = this;
  59783. var downSampleX4Offsets = new Array(32);
  59784. 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);
  59785. this.downSampleX4PostProcess.onApply = function (effect) {
  59786. var id = 0;
  59787. var width = _this.downSampleX4PostProcess.width;
  59788. var height = _this.downSampleX4PostProcess.height;
  59789. for (var i = -2; i < 2; i++) {
  59790. for (var j = -2; j < 2; j++) {
  59791. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  59792. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  59793. id += 2;
  59794. }
  59795. }
  59796. effect.setArray2("dsOffsets", downSampleX4Offsets);
  59797. };
  59798. // Add to pipeline
  59799. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  59800. };
  59801. // Brightpass Post-Process
  59802. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  59803. var _this = this;
  59804. var brightOffsets = new Array(8);
  59805. 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);
  59806. this.brightPassPostProcess.onApply = function (effect) {
  59807. var sU = (1.0 / _this.brightPassPostProcess.width);
  59808. var sV = (1.0 / _this.brightPassPostProcess.height);
  59809. brightOffsets[0] = -0.5 * sU;
  59810. brightOffsets[1] = 0.5 * sV;
  59811. brightOffsets[2] = 0.5 * sU;
  59812. brightOffsets[3] = 0.5 * sV;
  59813. brightOffsets[4] = -0.5 * sU;
  59814. brightOffsets[5] = -0.5 * sV;
  59815. brightOffsets[6] = 0.5 * sU;
  59816. brightOffsets[7] = -0.5 * sV;
  59817. effect.setArray2("dsOffsets", brightOffsets);
  59818. effect.setFloat("brightThreshold", _this.brightThreshold);
  59819. };
  59820. // Add to pipeline
  59821. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  59822. };
  59823. // Create blur H&V post-processes
  59824. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  59825. var _this = this;
  59826. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  59827. var engine = scene.getEngine();
  59828. 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);
  59829. 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);
  59830. blurX.onActivateObservable.add(function () {
  59831. var dw = blurX.width / engine.getRenderWidth();
  59832. blurX.kernel = _this[blurWidthKey] * dw;
  59833. });
  59834. blurY.onActivateObservable.add(function () {
  59835. var dw = blurY.height / engine.getRenderHeight();
  59836. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  59837. });
  59838. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  59839. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  59840. this.blurHPostProcesses.push(blurX);
  59841. this.blurVPostProcesses.push(blurY);
  59842. };
  59843. // Create texture adder post-process
  59844. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  59845. var _this = this;
  59846. 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);
  59847. this.textureAdderPostProcess.onApply = function (effect) {
  59848. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  59849. effect.setTexture("lensSampler", _this.lensTexture);
  59850. effect.setFloat("exposure", _this.exposure);
  59851. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  59852. };
  59853. // Add to pipeline
  59854. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  59855. };
  59856. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  59857. var _this = this;
  59858. var geometryRenderer = scene.enableGeometryBufferRenderer();
  59859. geometryRenderer.enablePosition = true;
  59860. var geometry = geometryRenderer.getGBuffer();
  59861. // Base post-process
  59862. 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));
  59863. var depthValues = BABYLON.Vector2.Zero();
  59864. this.volumetricLightPostProcess.onApply = function (effect) {
  59865. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  59866. var generator = _this.sourceLight.getShadowGenerator();
  59867. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  59868. effect.setTexture("positionSampler", geometry.textures[2]);
  59869. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  59870. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  59871. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  59872. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  59873. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  59874. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  59875. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  59876. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  59877. effect.setVector2("depthValues", depthValues);
  59878. }
  59879. };
  59880. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  59881. // Smooth
  59882. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  59883. // Merge
  59884. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  59885. this.volumetricLightMergePostProces.onApply = function (effect) {
  59886. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  59887. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  59888. };
  59889. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  59890. };
  59891. // Create luminance
  59892. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  59893. var _this = this;
  59894. // Create luminance
  59895. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  59896. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  59897. var offsets = [];
  59898. this.luminancePostProcess.onApply = function (effect) {
  59899. var sU = (1.0 / _this.luminancePostProcess.width);
  59900. var sV = (1.0 / _this.luminancePostProcess.height);
  59901. offsets[0] = -0.5 * sU;
  59902. offsets[1] = 0.5 * sV;
  59903. offsets[2] = 0.5 * sU;
  59904. offsets[3] = 0.5 * sV;
  59905. offsets[4] = -0.5 * sU;
  59906. offsets[5] = -0.5 * sV;
  59907. offsets[6] = 0.5 * sU;
  59908. offsets[7] = -0.5 * sV;
  59909. effect.setArray2("lumOffsets", offsets);
  59910. };
  59911. // Add to pipeline
  59912. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  59913. // Create down sample luminance
  59914. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  59915. var size = Math.pow(3, i);
  59916. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  59917. if (i === 0) {
  59918. defines += "#define FINAL_DOWN_SAMPLER";
  59919. }
  59920. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  59921. this.luminanceDownSamplePostProcesses.push(postProcess);
  59922. }
  59923. // Create callbacks and add effects
  59924. var lastLuminance = this.luminancePostProcess;
  59925. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  59926. var downSampleOffsets = new Array(18);
  59927. pp.onApply = function (effect) {
  59928. if (!lastLuminance) {
  59929. return;
  59930. }
  59931. var id = 0;
  59932. for (var x = -1; x < 2; x++) {
  59933. for (var y = -1; y < 2; y++) {
  59934. downSampleOffsets[id] = x / lastLuminance.width;
  59935. downSampleOffsets[id + 1] = y / lastLuminance.height;
  59936. id += 2;
  59937. }
  59938. }
  59939. effect.setArray2("dsOffsets", downSampleOffsets);
  59940. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  59941. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  59942. lastLuminance = _this.luminancePostProcess;
  59943. }
  59944. else {
  59945. lastLuminance = pp;
  59946. }
  59947. };
  59948. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  59949. pp.onAfterRender = function (effect) {
  59950. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  59951. 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);
  59952. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  59953. };
  59954. }
  59955. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  59956. });
  59957. };
  59958. // Create HDR post-process
  59959. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  59960. var _this = this;
  59961. 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);
  59962. var outputLiminance = 1;
  59963. var time = 0;
  59964. var lastTime = 0;
  59965. this.hdrPostProcess.onApply = function (effect) {
  59966. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  59967. time += scene.getEngine().getDeltaTime();
  59968. if (outputLiminance < 0) {
  59969. outputLiminance = _this._hdrCurrentLuminance;
  59970. }
  59971. else {
  59972. var dt = (lastTime - time) / 1000.0;
  59973. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  59974. outputLiminance += _this.hdrDecreaseRate * dt;
  59975. }
  59976. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  59977. outputLiminance -= _this.hdrIncreaseRate * dt;
  59978. }
  59979. else {
  59980. outputLiminance = _this._hdrCurrentLuminance;
  59981. }
  59982. }
  59983. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  59984. effect.setFloat("averageLuminance", outputLiminance);
  59985. lastTime = time;
  59986. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  59987. };
  59988. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  59989. };
  59990. // Create lens flare post-process
  59991. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  59992. var _this = this;
  59993. 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);
  59994. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  59995. this._createBlurPostProcesses(scene, ratio / 4, 2);
  59996. 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);
  59997. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  59998. var resolution = new BABYLON.Vector2(0, 0);
  59999. // Lens flare
  60000. this.lensFlarePostProcess.onApply = function (effect) {
  60001. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  60002. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  60003. effect.setFloat("strength", _this.lensFlareStrength);
  60004. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  60005. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  60006. // Shift
  60007. resolution.x = _this.lensFlarePostProcess.width;
  60008. resolution.y = _this.lensFlarePostProcess.height;
  60009. effect.setVector2("resolution", resolution);
  60010. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  60011. };
  60012. // Compose
  60013. 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);
  60014. 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);
  60015. this.lensFlareComposePostProcess.onApply = function (effect) {
  60016. if (!_this._scene.activeCamera) {
  60017. return;
  60018. }
  60019. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  60020. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  60021. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  60022. // Lens start rotation matrix
  60023. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  60024. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  60025. 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));
  60026. camRot *= 4.0;
  60027. 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);
  60028. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  60029. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  60030. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  60031. };
  60032. };
  60033. // Create depth-of-field post-process
  60034. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  60035. var _this = this;
  60036. 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);
  60037. this.depthOfFieldPostProcess.onApply = function (effect) {
  60038. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  60039. effect.setTexture("depthSampler", _this._getDepthTexture());
  60040. effect.setFloat("distance", _this.depthOfFieldDistance);
  60041. };
  60042. // Add to pipeline
  60043. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  60044. };
  60045. // Create motion blur post-process
  60046. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  60047. var _this = this;
  60048. 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);
  60049. var motionScale = 0;
  60050. var prevViewProjection = BABYLON.Matrix.Identity();
  60051. var invViewProjection = BABYLON.Matrix.Identity();
  60052. var viewProjection = BABYLON.Matrix.Identity();
  60053. var screenSize = BABYLON.Vector2.Zero();
  60054. this.motionBlurPostProcess.onApply = function (effect) {
  60055. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  60056. viewProjection.invertToRef(invViewProjection);
  60057. effect.setMatrix("inverseViewProjection", invViewProjection);
  60058. effect.setMatrix("prevViewProjection", prevViewProjection);
  60059. prevViewProjection = viewProjection;
  60060. screenSize.x = _this.motionBlurPostProcess.width;
  60061. screenSize.y = _this.motionBlurPostProcess.height;
  60062. effect.setVector2("screenSize", screenSize);
  60063. motionScale = scene.getEngine().getFps() / 60.0;
  60064. effect.setFloat("motionScale", motionScale);
  60065. effect.setFloat("motionStrength", _this.motionStrength);
  60066. effect.setTexture("depthSampler", _this._getDepthTexture());
  60067. };
  60068. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  60069. };
  60070. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  60071. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  60072. var renderer = this._scene.enableGeometryBufferRenderer();
  60073. return renderer.getGBuffer().textures[0];
  60074. }
  60075. return this._scene.enableDepthRenderer().getDepthMap();
  60076. };
  60077. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  60078. for (var i = 0; i < this._cameras.length; i++) {
  60079. var camera = this._cameras[i];
  60080. if (this.originalPostProcess) {
  60081. this.originalPostProcess.dispose(camera);
  60082. }
  60083. if (this.downSampleX4PostProcess) {
  60084. this.downSampleX4PostProcess.dispose(camera);
  60085. }
  60086. if (this.brightPassPostProcess) {
  60087. this.brightPassPostProcess.dispose(camera);
  60088. }
  60089. if (this.textureAdderPostProcess) {
  60090. this.textureAdderPostProcess.dispose(camera);
  60091. }
  60092. if (this.textureAdderFinalPostProcess) {
  60093. this.textureAdderFinalPostProcess.dispose(camera);
  60094. }
  60095. if (this.volumetricLightPostProcess) {
  60096. this.volumetricLightPostProcess.dispose(camera);
  60097. }
  60098. if (this.volumetricLightSmoothXPostProcess) {
  60099. this.volumetricLightSmoothXPostProcess.dispose(camera);
  60100. }
  60101. if (this.volumetricLightSmoothYPostProcess) {
  60102. this.volumetricLightSmoothYPostProcess.dispose(camera);
  60103. }
  60104. if (this.volumetricLightMergePostProces) {
  60105. this.volumetricLightMergePostProces.dispose(camera);
  60106. }
  60107. if (this.volumetricLightFinalPostProcess) {
  60108. this.volumetricLightFinalPostProcess.dispose(camera);
  60109. }
  60110. if (this.lensFlarePostProcess) {
  60111. this.lensFlarePostProcess.dispose(camera);
  60112. }
  60113. if (this.lensFlareComposePostProcess) {
  60114. this.lensFlareComposePostProcess.dispose(camera);
  60115. }
  60116. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  60117. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  60118. }
  60119. if (this.luminancePostProcess) {
  60120. this.luminancePostProcess.dispose(camera);
  60121. }
  60122. if (this.hdrPostProcess) {
  60123. this.hdrPostProcess.dispose(camera);
  60124. }
  60125. if (this.hdrFinalPostProcess) {
  60126. this.hdrFinalPostProcess.dispose(camera);
  60127. }
  60128. if (this.depthOfFieldPostProcess) {
  60129. this.depthOfFieldPostProcess.dispose(camera);
  60130. }
  60131. if (this.motionBlurPostProcess) {
  60132. this.motionBlurPostProcess.dispose(camera);
  60133. }
  60134. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  60135. this.blurHPostProcesses[j].dispose(camera);
  60136. }
  60137. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  60138. this.blurVPostProcesses[j].dispose(camera);
  60139. }
  60140. }
  60141. this.originalPostProcess = null;
  60142. this.downSampleX4PostProcess = null;
  60143. this.brightPassPostProcess = null;
  60144. this.textureAdderPostProcess = null;
  60145. this.textureAdderFinalPostProcess = null;
  60146. this.volumetricLightPostProcess = null;
  60147. this.volumetricLightSmoothXPostProcess = null;
  60148. this.volumetricLightSmoothYPostProcess = null;
  60149. this.volumetricLightMergePostProces = null;
  60150. this.volumetricLightFinalPostProcess = null;
  60151. this.lensFlarePostProcess = null;
  60152. this.lensFlareComposePostProcess = null;
  60153. this.luminancePostProcess = null;
  60154. this.hdrPostProcess = null;
  60155. this.hdrFinalPostProcess = null;
  60156. this.depthOfFieldPostProcess = null;
  60157. this.motionBlurPostProcess = null;
  60158. this.luminanceDownSamplePostProcesses = [];
  60159. this.blurHPostProcesses = [];
  60160. this.blurVPostProcesses = [];
  60161. };
  60162. // Dispose
  60163. StandardRenderingPipeline.prototype.dispose = function () {
  60164. this._disposePostProcesses();
  60165. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  60166. _super.prototype.dispose.call(this);
  60167. };
  60168. // Serialize rendering pipeline
  60169. StandardRenderingPipeline.prototype.serialize = function () {
  60170. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60171. serializationObject.customType = "StandardRenderingPipeline";
  60172. return serializationObject;
  60173. };
  60174. /**
  60175. * Static members
  60176. */
  60177. // Parse serialized pipeline
  60178. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  60179. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  60180. };
  60181. // Luminance steps
  60182. StandardRenderingPipeline.LuminanceSteps = 6;
  60183. __decorate([
  60184. BABYLON.serialize()
  60185. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  60186. __decorate([
  60187. BABYLON.serialize()
  60188. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  60189. __decorate([
  60190. BABYLON.serialize()
  60191. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  60192. __decorate([
  60193. BABYLON.serialize()
  60194. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  60195. __decorate([
  60196. BABYLON.serializeAsTexture("lensTexture")
  60197. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  60198. __decorate([
  60199. BABYLON.serialize()
  60200. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  60201. __decorate([
  60202. BABYLON.serialize()
  60203. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  60204. __decorate([
  60205. BABYLON.serialize()
  60206. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  60207. __decorate([
  60208. BABYLON.serialize()
  60209. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  60210. __decorate([
  60211. BABYLON.serialize()
  60212. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  60213. __decorate([
  60214. BABYLON.serialize()
  60215. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  60216. __decorate([
  60217. BABYLON.serializeAsTexture("lensColorTexture")
  60218. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  60219. __decorate([
  60220. BABYLON.serialize()
  60221. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  60222. __decorate([
  60223. BABYLON.serialize()
  60224. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  60225. __decorate([
  60226. BABYLON.serialize()
  60227. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  60228. __decorate([
  60229. BABYLON.serialize()
  60230. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  60231. __decorate([
  60232. BABYLON.serializeAsTexture("lensStarTexture")
  60233. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  60234. __decorate([
  60235. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  60236. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  60237. __decorate([
  60238. BABYLON.serialize()
  60239. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  60240. __decorate([
  60241. BABYLON.serialize()
  60242. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  60243. __decorate([
  60244. BABYLON.serialize()
  60245. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  60246. __decorate([
  60247. BABYLON.serialize()
  60248. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  60249. __decorate([
  60250. BABYLON.serialize()
  60251. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  60252. __decorate([
  60253. BABYLON.serialize()
  60254. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  60255. __decorate([
  60256. BABYLON.serialize()
  60257. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  60258. __decorate([
  60259. BABYLON.serialize()
  60260. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  60261. __decorate([
  60262. BABYLON.serialize()
  60263. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  60264. __decorate([
  60265. BABYLON.serialize()
  60266. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  60267. __decorate([
  60268. BABYLON.serialize()
  60269. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  60270. __decorate([
  60271. BABYLON.serialize()
  60272. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  60273. return StandardRenderingPipeline;
  60274. }(BABYLON.PostProcessRenderPipeline));
  60275. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  60276. })(BABYLON || (BABYLON = {}));
  60277. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  60278. var BABYLON;
  60279. (function (BABYLON) {
  60280. var FxaaPostProcess = /** @class */ (function (_super) {
  60281. __extends(FxaaPostProcess, _super);
  60282. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  60283. if (camera === void 0) { camera = null; }
  60284. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60285. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  60286. _this.onApplyObservable.add(function (effect) {
  60287. var texelSize = _this.texelSize;
  60288. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  60289. });
  60290. return _this;
  60291. }
  60292. return FxaaPostProcess;
  60293. }(BABYLON.PostProcess));
  60294. BABYLON.FxaaPostProcess = FxaaPostProcess;
  60295. })(BABYLON || (BABYLON = {}));
  60296. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  60297. var BABYLON;
  60298. (function (BABYLON) {
  60299. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  60300. __extends(DefaultRenderingPipeline, _super);
  60301. /**
  60302. * @constructor
  60303. * @param {string} name - The rendering pipeline name
  60304. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  60305. * @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)
  60306. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  60307. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  60308. */
  60309. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  60310. if (automaticBuild === void 0) { automaticBuild = true; }
  60311. var _this = _super.call(this, scene.getEngine(), name) || this;
  60312. _this.PassPostProcessId = "PassPostProcessEffect";
  60313. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  60314. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  60315. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  60316. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  60317. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  60318. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  60319. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  60320. // IAnimatable
  60321. _this.animations = [];
  60322. // Values
  60323. _this._bloomEnabled = false;
  60324. _this._fxaaEnabled = false;
  60325. _this._imageProcessingEnabled = true;
  60326. _this._bloomScale = 0.6;
  60327. _this._buildAllowed = true;
  60328. /**
  60329. * Specifies the size of the bloom blur kernel, relative to the final output size
  60330. */
  60331. _this.bloomKernel = 64;
  60332. /**
  60333. * Specifies the weight of the bloom in the final rendering
  60334. */
  60335. _this._bloomWeight = 0.15;
  60336. _this._cameras = cameras || [];
  60337. _this._buildAllowed = automaticBuild;
  60338. // Initialize
  60339. _this._scene = scene;
  60340. var caps = _this._scene.getEngine().getCaps();
  60341. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  60342. // Misc
  60343. if (_this._hdr) {
  60344. if (caps.textureHalfFloatRender) {
  60345. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60346. }
  60347. else if (caps.textureFloatRender) {
  60348. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60349. }
  60350. }
  60351. else {
  60352. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60353. }
  60354. // Attach
  60355. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60356. _this._buildPipeline();
  60357. return _this;
  60358. }
  60359. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  60360. get: function () {
  60361. return this._bloomWeight;
  60362. },
  60363. set: function (value) {
  60364. if (this._bloomWeight === value) {
  60365. return;
  60366. }
  60367. this._bloomWeight = value;
  60368. if (this._hdr && this.copyBack) {
  60369. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  60370. }
  60371. },
  60372. enumerable: true,
  60373. configurable: true
  60374. });
  60375. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  60376. get: function () {
  60377. return this._bloomScale;
  60378. },
  60379. set: function (value) {
  60380. if (this._bloomScale === value) {
  60381. return;
  60382. }
  60383. this._bloomScale = value;
  60384. this._buildPipeline();
  60385. },
  60386. enumerable: true,
  60387. configurable: true
  60388. });
  60389. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  60390. get: function () {
  60391. return this._bloomEnabled;
  60392. },
  60393. set: function (enabled) {
  60394. if (this._bloomEnabled === enabled) {
  60395. return;
  60396. }
  60397. this._bloomEnabled = enabled;
  60398. this._buildPipeline();
  60399. },
  60400. enumerable: true,
  60401. configurable: true
  60402. });
  60403. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  60404. get: function () {
  60405. return this._fxaaEnabled;
  60406. },
  60407. set: function (enabled) {
  60408. if (this._fxaaEnabled === enabled) {
  60409. return;
  60410. }
  60411. this._fxaaEnabled = enabled;
  60412. this._buildPipeline();
  60413. },
  60414. enumerable: true,
  60415. configurable: true
  60416. });
  60417. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  60418. get: function () {
  60419. return this._imageProcessingEnabled;
  60420. },
  60421. set: function (enabled) {
  60422. if (this._imageProcessingEnabled === enabled) {
  60423. return;
  60424. }
  60425. this._imageProcessingEnabled = enabled;
  60426. this._buildPipeline();
  60427. },
  60428. enumerable: true,
  60429. configurable: true
  60430. });
  60431. /**
  60432. * Force the compilation of the entire pipeline.
  60433. */
  60434. DefaultRenderingPipeline.prototype.prepare = function () {
  60435. var previousState = this._buildAllowed;
  60436. this._buildAllowed = true;
  60437. this._buildPipeline();
  60438. this._buildAllowed = previousState;
  60439. };
  60440. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  60441. var _this = this;
  60442. if (!this._buildAllowed) {
  60443. return;
  60444. }
  60445. var engine = this._scene.getEngine();
  60446. this._disposePostProcesses();
  60447. this._reset();
  60448. if (this.bloomEnabled) {
  60449. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  60450. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  60451. if (!this._hdr) {
  60452. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  60453. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  60454. this.highlights.autoClear = false;
  60455. this.highlights.alwaysForcePOT = true;
  60456. }
  60457. 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);
  60458. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  60459. this.blurX.alwaysForcePOT = true;
  60460. this.blurX.autoClear = false;
  60461. this.blurX.onActivateObservable.add(function () {
  60462. var dw = _this.blurX.width / engine.getRenderWidth(true);
  60463. _this.blurX.kernel = _this.bloomKernel * dw;
  60464. });
  60465. 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);
  60466. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  60467. this.blurY.alwaysForcePOT = true;
  60468. this.blurY.autoClear = false;
  60469. this.blurY.onActivateObservable.add(function () {
  60470. var dh = _this.blurY.height / engine.getRenderHeight(true);
  60471. _this.blurY.kernel = _this.bloomKernel * dh;
  60472. });
  60473. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  60474. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  60475. this.copyBack.alwaysForcePOT = true;
  60476. if (this._hdr) {
  60477. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  60478. var w = this.bloomWeight;
  60479. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  60480. }
  60481. else {
  60482. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  60483. }
  60484. this.copyBack.autoClear = false;
  60485. }
  60486. if (this._imageProcessingEnabled) {
  60487. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  60488. if (this._hdr) {
  60489. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  60490. }
  60491. else {
  60492. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  60493. }
  60494. }
  60495. if (this.fxaaEnabled) {
  60496. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  60497. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  60498. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  60499. }
  60500. else if (this._hdr && this.imageProcessing) {
  60501. this.finalMerge = this.imageProcessing;
  60502. }
  60503. else {
  60504. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  60505. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  60506. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  60507. }
  60508. if (this.bloomEnabled) {
  60509. if (this._hdr) {
  60510. this.copyBack.shareOutputWith(this.blurX);
  60511. if (this.imageProcessing) {
  60512. this.imageProcessing.shareOutputWith(this.pass);
  60513. this.imageProcessing.autoClear = false;
  60514. }
  60515. else if (this.fxaa) {
  60516. this.fxaa.shareOutputWith(this.pass);
  60517. }
  60518. else {
  60519. this.finalMerge.shareOutputWith(this.pass);
  60520. }
  60521. }
  60522. else {
  60523. if (this.fxaa) {
  60524. this.fxaa.shareOutputWith(this.pass);
  60525. }
  60526. else {
  60527. this.finalMerge.shareOutputWith(this.pass);
  60528. }
  60529. }
  60530. }
  60531. if (this._cameras !== null) {
  60532. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  60533. }
  60534. };
  60535. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  60536. for (var i = 0; i < this._cameras.length; i++) {
  60537. var camera = this._cameras[i];
  60538. if (this.pass) {
  60539. this.pass.dispose(camera);
  60540. }
  60541. if (this.highlights) {
  60542. this.highlights.dispose(camera);
  60543. }
  60544. if (this.blurX) {
  60545. this.blurX.dispose(camera);
  60546. }
  60547. if (this.blurY) {
  60548. this.blurY.dispose(camera);
  60549. }
  60550. if (this.copyBack) {
  60551. this.copyBack.dispose(camera);
  60552. }
  60553. if (this.imageProcessing) {
  60554. this.imageProcessing.dispose(camera);
  60555. }
  60556. if (this.fxaa) {
  60557. this.fxaa.dispose(camera);
  60558. }
  60559. if (this.finalMerge) {
  60560. this.finalMerge.dispose(camera);
  60561. }
  60562. }
  60563. this.pass = null;
  60564. this.highlights = null;
  60565. this.blurX = null;
  60566. this.blurY = null;
  60567. this.copyBack = null;
  60568. this.imageProcessing = null;
  60569. this.fxaa = null;
  60570. this.finalMerge = null;
  60571. };
  60572. // Dispose
  60573. DefaultRenderingPipeline.prototype.dispose = function () {
  60574. this._disposePostProcesses();
  60575. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  60576. _super.prototype.dispose.call(this);
  60577. };
  60578. // Serialize rendering pipeline
  60579. DefaultRenderingPipeline.prototype.serialize = function () {
  60580. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60581. serializationObject.customType = "DefaultRenderingPipeline";
  60582. return serializationObject;
  60583. };
  60584. // Parse serialized pipeline
  60585. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  60586. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  60587. };
  60588. __decorate([
  60589. BABYLON.serialize()
  60590. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  60591. __decorate([
  60592. BABYLON.serialize()
  60593. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  60594. __decorate([
  60595. BABYLON.serialize()
  60596. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  60597. __decorate([
  60598. BABYLON.serialize()
  60599. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  60600. __decorate([
  60601. BABYLON.serialize()
  60602. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  60603. __decorate([
  60604. BABYLON.serialize()
  60605. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  60606. __decorate([
  60607. BABYLON.serialize()
  60608. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  60609. __decorate([
  60610. BABYLON.serialize()
  60611. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  60612. return DefaultRenderingPipeline;
  60613. }(BABYLON.PostProcessRenderPipeline));
  60614. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  60615. })(BABYLON || (BABYLON = {}));
  60616. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  60617. var BABYLON;
  60618. (function (BABYLON) {
  60619. var GeometryBufferRenderer = /** @class */ (function () {
  60620. function GeometryBufferRenderer(scene, ratio) {
  60621. if (ratio === void 0) { ratio = 1; }
  60622. this._enablePosition = false;
  60623. this._scene = scene;
  60624. this._ratio = ratio;
  60625. // Render target
  60626. this._createRenderTargets();
  60627. }
  60628. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  60629. set: function (meshes) {
  60630. this._multiRenderTarget.renderList = meshes;
  60631. },
  60632. enumerable: true,
  60633. configurable: true
  60634. });
  60635. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  60636. get: function () {
  60637. return this._multiRenderTarget.isSupported;
  60638. },
  60639. enumerable: true,
  60640. configurable: true
  60641. });
  60642. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  60643. get: function () {
  60644. return this._enablePosition;
  60645. },
  60646. set: function (enable) {
  60647. this._enablePosition = enable;
  60648. this.dispose();
  60649. this._createRenderTargets();
  60650. },
  60651. enumerable: true,
  60652. configurable: true
  60653. });
  60654. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  60655. var material = subMesh.getMaterial();
  60656. if (material && material.disableDepthWrite) {
  60657. return false;
  60658. }
  60659. var defines = [];
  60660. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  60661. var mesh = subMesh.getMesh();
  60662. // Alpha test
  60663. if (material && material.needAlphaTesting()) {
  60664. defines.push("#define ALPHATEST");
  60665. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60666. attribs.push(BABYLON.VertexBuffer.UVKind);
  60667. defines.push("#define UV1");
  60668. }
  60669. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60670. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60671. defines.push("#define UV2");
  60672. }
  60673. }
  60674. // Buffers
  60675. if (this._enablePosition) {
  60676. defines.push("#define POSITION");
  60677. }
  60678. // Bones
  60679. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60680. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60681. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60682. if (mesh.numBoneInfluencers > 4) {
  60683. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60684. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60685. }
  60686. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60687. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  60688. }
  60689. else {
  60690. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60691. }
  60692. // Instances
  60693. if (useInstances) {
  60694. defines.push("#define INSTANCES");
  60695. attribs.push("world0");
  60696. attribs.push("world1");
  60697. attribs.push("world2");
  60698. attribs.push("world3");
  60699. }
  60700. // Get correct effect
  60701. var join = defines.join("\n");
  60702. if (this._cachedDefines !== join) {
  60703. this._cachedDefines = join;
  60704. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  60705. }
  60706. return this._effect.isReady();
  60707. };
  60708. GeometryBufferRenderer.prototype.getGBuffer = function () {
  60709. return this._multiRenderTarget;
  60710. };
  60711. // Methods
  60712. GeometryBufferRenderer.prototype.dispose = function () {
  60713. this.getGBuffer().dispose();
  60714. };
  60715. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  60716. var _this = this;
  60717. var engine = this._scene.getEngine();
  60718. var count = this._enablePosition ? 3 : 2;
  60719. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  60720. if (!this.isSupported) {
  60721. return;
  60722. }
  60723. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60724. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60725. this._multiRenderTarget.refreshRate = 1;
  60726. this._multiRenderTarget.renderParticles = false;
  60727. this._multiRenderTarget.renderList = null;
  60728. // set default depth value to 1.0 (far away)
  60729. this._multiRenderTarget.onClearObservable.add(function (engine) {
  60730. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  60731. });
  60732. // Custom render function
  60733. var renderSubMesh = function (subMesh) {
  60734. var mesh = subMesh.getRenderingMesh();
  60735. var scene = _this._scene;
  60736. var engine = scene.getEngine();
  60737. var material = subMesh.getMaterial();
  60738. if (!material) {
  60739. return;
  60740. }
  60741. // Culling
  60742. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  60743. // Managing instances
  60744. var batch = mesh._getInstancesRenderList(subMesh._id);
  60745. if (batch.mustReturn) {
  60746. return;
  60747. }
  60748. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  60749. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  60750. engine.enableEffect(_this._effect);
  60751. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  60752. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  60753. _this._effect.setMatrix("view", scene.getViewMatrix());
  60754. // Alpha test
  60755. if (material && material.needAlphaTesting()) {
  60756. var alphaTexture = material.getAlphaTestTexture();
  60757. if (alphaTexture) {
  60758. _this._effect.setTexture("diffuseSampler", alphaTexture);
  60759. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  60760. }
  60761. }
  60762. // Bones
  60763. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  60764. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  60765. }
  60766. // Draw
  60767. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  60768. }
  60769. };
  60770. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  60771. var index;
  60772. if (depthOnlySubMeshes.length) {
  60773. engine.setColorWrite(false);
  60774. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  60775. renderSubMesh(depthOnlySubMeshes.data[index]);
  60776. }
  60777. engine.setColorWrite(true);
  60778. }
  60779. for (index = 0; index < opaqueSubMeshes.length; index++) {
  60780. renderSubMesh(opaqueSubMeshes.data[index]);
  60781. }
  60782. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  60783. renderSubMesh(alphaTestSubMeshes.data[index]);
  60784. }
  60785. };
  60786. };
  60787. return GeometryBufferRenderer;
  60788. }());
  60789. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  60790. })(BABYLON || (BABYLON = {}));
  60791. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  60792. var BABYLON;
  60793. (function (BABYLON) {
  60794. var RefractionPostProcess = /** @class */ (function (_super) {
  60795. __extends(RefractionPostProcess, _super);
  60796. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  60797. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  60798. _this.color = color;
  60799. _this.depth = depth;
  60800. _this.colorLevel = colorLevel;
  60801. _this.onActivateObservable.add(function (cam) {
  60802. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  60803. });
  60804. _this.onApplyObservable.add(function (effect) {
  60805. effect.setColor3("baseColor", _this.color);
  60806. effect.setFloat("depth", _this.depth);
  60807. effect.setFloat("colorLevel", _this.colorLevel);
  60808. effect.setTexture("refractionSampler", _this._refRexture);
  60809. });
  60810. return _this;
  60811. }
  60812. // Methods
  60813. RefractionPostProcess.prototype.dispose = function (camera) {
  60814. if (this._refRexture) {
  60815. this._refRexture.dispose();
  60816. }
  60817. _super.prototype.dispose.call(this, camera);
  60818. };
  60819. return RefractionPostProcess;
  60820. }(BABYLON.PostProcess));
  60821. BABYLON.RefractionPostProcess = RefractionPostProcess;
  60822. })(BABYLON || (BABYLON = {}));
  60823. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  60824. var BABYLON;
  60825. (function (BABYLON) {
  60826. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  60827. __extends(BlackAndWhitePostProcess, _super);
  60828. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  60829. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  60830. _this.degree = 1;
  60831. _this.onApplyObservable.add(function (effect) {
  60832. effect.setFloat("degree", _this.degree);
  60833. });
  60834. return _this;
  60835. }
  60836. return BlackAndWhitePostProcess;
  60837. }(BABYLON.PostProcess));
  60838. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  60839. })(BABYLON || (BABYLON = {}));
  60840. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  60841. var BABYLON;
  60842. (function (BABYLON) {
  60843. var ConvolutionPostProcess = /** @class */ (function (_super) {
  60844. __extends(ConvolutionPostProcess, _super);
  60845. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  60846. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  60847. _this.kernel = kernel;
  60848. _this.onApply = function (effect) {
  60849. effect.setFloat2("screenSize", _this.width, _this.height);
  60850. effect.setArray("kernel", _this.kernel);
  60851. };
  60852. return _this;
  60853. }
  60854. // Statics
  60855. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  60856. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  60857. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  60858. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  60859. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  60860. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  60861. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  60862. return ConvolutionPostProcess;
  60863. }(BABYLON.PostProcess));
  60864. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  60865. })(BABYLON || (BABYLON = {}));
  60866. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  60867. var BABYLON;
  60868. (function (BABYLON) {
  60869. var FilterPostProcess = /** @class */ (function (_super) {
  60870. __extends(FilterPostProcess, _super);
  60871. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  60872. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  60873. _this.kernelMatrix = kernelMatrix;
  60874. _this.onApply = function (effect) {
  60875. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  60876. };
  60877. return _this;
  60878. }
  60879. return FilterPostProcess;
  60880. }(BABYLON.PostProcess));
  60881. BABYLON.FilterPostProcess = FilterPostProcess;
  60882. })(BABYLON || (BABYLON = {}));
  60883. //# sourceMappingURL=babylon.filterPostProcess.js.map
  60884. var BABYLON;
  60885. (function (BABYLON) {
  60886. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  60887. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  60888. __extends(VolumetricLightScatteringPostProcess, _super);
  60889. /**
  60890. * @constructor
  60891. * @param {string} name - The post-process name
  60892. * @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)
  60893. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  60894. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  60895. * @param {number} samples - The post-process quality, default 100
  60896. * @param {number} samplingMode - The post-process filtering mode
  60897. * @param {BABYLON.Engine} engine - The babylon engine
  60898. * @param {boolean} reusable - If the post-process is reusable
  60899. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  60900. */
  60901. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  60902. if (samples === void 0) { samples = 100; }
  60903. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  60904. 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;
  60905. _this._screenCoordinates = BABYLON.Vector2.Zero();
  60906. /**
  60907. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  60908. * @type {Vector3}
  60909. */
  60910. _this.customMeshPosition = BABYLON.Vector3.Zero();
  60911. /**
  60912. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  60913. * @type {boolean}
  60914. */
  60915. _this.useCustomMeshPosition = false;
  60916. /**
  60917. * If the post-process should inverse the light scattering direction
  60918. * @type {boolean}
  60919. */
  60920. _this.invert = true;
  60921. /**
  60922. * Array containing the excluded meshes not rendered in the internal pass
  60923. */
  60924. _this.excludedMeshes = new Array();
  60925. /**
  60926. * Controls the overall intensity of the post-process
  60927. * @type {number}
  60928. */
  60929. _this.exposure = 0.3;
  60930. /**
  60931. * Dissipates each sample's contribution in range [0, 1]
  60932. * @type {number}
  60933. */
  60934. _this.decay = 0.96815;
  60935. /**
  60936. * Controls the overall intensity of each sample
  60937. * @type {number}
  60938. */
  60939. _this.weight = 0.58767;
  60940. /**
  60941. * Controls the density of each sample
  60942. * @type {number}
  60943. */
  60944. _this.density = 0.926;
  60945. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  60946. engine = scene.getEngine();
  60947. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  60948. // Configure mesh
  60949. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  60950. // Configure
  60951. _this._createPass(scene, ratio.passRatio || ratio);
  60952. _this.onActivate = function (camera) {
  60953. if (!_this.isSupported) {
  60954. _this.dispose(camera);
  60955. }
  60956. _this.onActivate = null;
  60957. };
  60958. _this.onApplyObservable.add(function (effect) {
  60959. _this._updateMeshScreenCoordinates(scene);
  60960. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  60961. effect.setFloat("exposure", _this.exposure);
  60962. effect.setFloat("decay", _this.decay);
  60963. effect.setFloat("weight", _this.weight);
  60964. effect.setFloat("density", _this.density);
  60965. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  60966. });
  60967. return _this;
  60968. }
  60969. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  60970. get: function () {
  60971. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  60972. return false;
  60973. },
  60974. set: function (useDiffuseColor) {
  60975. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  60976. },
  60977. enumerable: true,
  60978. configurable: true
  60979. });
  60980. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  60981. return "VolumetricLightScatteringPostProcess";
  60982. };
  60983. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  60984. var mesh = subMesh.getMesh();
  60985. // Render this.mesh as default
  60986. if (mesh === this.mesh && mesh.material) {
  60987. return mesh.material.isReady(mesh);
  60988. }
  60989. var defines = [];
  60990. var attribs = [BABYLON.VertexBuffer.PositionKind];
  60991. var material = subMesh.getMaterial();
  60992. // Alpha test
  60993. if (material) {
  60994. if (material.needAlphaTesting()) {
  60995. defines.push("#define ALPHATEST");
  60996. }
  60997. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60998. attribs.push(BABYLON.VertexBuffer.UVKind);
  60999. defines.push("#define UV1");
  61000. }
  61001. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61002. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61003. defines.push("#define UV2");
  61004. }
  61005. }
  61006. // Bones
  61007. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61008. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61009. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61010. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61011. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  61012. }
  61013. else {
  61014. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61015. }
  61016. // Instances
  61017. if (useInstances) {
  61018. defines.push("#define INSTANCES");
  61019. attribs.push("world0");
  61020. attribs.push("world1");
  61021. attribs.push("world2");
  61022. attribs.push("world3");
  61023. }
  61024. // Get correct effect
  61025. var join = defines.join("\n");
  61026. if (this._cachedDefines !== join) {
  61027. this._cachedDefines = join;
  61028. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  61029. }
  61030. return this._volumetricLightScatteringPass.isReady();
  61031. };
  61032. /**
  61033. * Sets the new light position for light scattering effect
  61034. * @param {BABYLON.Vector3} The new custom light position
  61035. */
  61036. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  61037. this.customMeshPosition = position;
  61038. };
  61039. /**
  61040. * Returns the light position for light scattering effect
  61041. * @return {BABYLON.Vector3} The custom light position
  61042. */
  61043. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  61044. return this.customMeshPosition;
  61045. };
  61046. /**
  61047. * Disposes the internal assets and detaches the post-process from the camera
  61048. */
  61049. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  61050. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  61051. if (rttIndex !== -1) {
  61052. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  61053. }
  61054. this._volumetricLightScatteringRTT.dispose();
  61055. _super.prototype.dispose.call(this, camera);
  61056. };
  61057. /**
  61058. * Returns the render target texture used by the post-process
  61059. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  61060. */
  61061. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  61062. return this._volumetricLightScatteringRTT;
  61063. };
  61064. // Private methods
  61065. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  61066. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  61067. return true;
  61068. }
  61069. return false;
  61070. };
  61071. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  61072. var _this = this;
  61073. var engine = scene.getEngine();
  61074. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  61075. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61076. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61077. this._volumetricLightScatteringRTT.renderList = null;
  61078. this._volumetricLightScatteringRTT.renderParticles = false;
  61079. var camera = this.getCamera();
  61080. if (camera) {
  61081. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  61082. }
  61083. else {
  61084. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  61085. }
  61086. // Custom render function for submeshes
  61087. var renderSubMesh = function (subMesh) {
  61088. var mesh = subMesh.getRenderingMesh();
  61089. if (_this._meshExcluded(mesh)) {
  61090. return;
  61091. }
  61092. var material = subMesh.getMaterial();
  61093. if (!material) {
  61094. return;
  61095. }
  61096. var scene = mesh.getScene();
  61097. var engine = scene.getEngine();
  61098. // Culling
  61099. engine.setState(material.backFaceCulling);
  61100. // Managing instances
  61101. var batch = mesh._getInstancesRenderList(subMesh._id);
  61102. if (batch.mustReturn) {
  61103. return;
  61104. }
  61105. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  61106. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  61107. var effect = _this._volumetricLightScatteringPass;
  61108. if (mesh === _this.mesh) {
  61109. if (subMesh.effect) {
  61110. effect = subMesh.effect;
  61111. }
  61112. else {
  61113. effect = material.getEffect();
  61114. }
  61115. }
  61116. engine.enableEffect(effect);
  61117. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  61118. if (mesh === _this.mesh) {
  61119. material.bind(mesh.getWorldMatrix(), mesh);
  61120. }
  61121. else {
  61122. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  61123. // Alpha test
  61124. if (material && material.needAlphaTesting()) {
  61125. var alphaTexture = material.getAlphaTestTexture();
  61126. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  61127. if (alphaTexture) {
  61128. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  61129. }
  61130. }
  61131. // Bones
  61132. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  61133. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  61134. }
  61135. }
  61136. // Draw
  61137. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  61138. }
  61139. };
  61140. // Render target texture callbacks
  61141. var savedSceneClearColor;
  61142. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  61143. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  61144. savedSceneClearColor = scene.clearColor;
  61145. scene.clearColor = sceneClearColor;
  61146. });
  61147. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  61148. scene.clearColor = savedSceneClearColor;
  61149. });
  61150. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  61151. var engine = scene.getEngine();
  61152. var index;
  61153. if (depthOnlySubMeshes.length) {
  61154. engine.setColorWrite(false);
  61155. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  61156. renderSubMesh(depthOnlySubMeshes.data[index]);
  61157. }
  61158. engine.setColorWrite(true);
  61159. }
  61160. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61161. renderSubMesh(opaqueSubMeshes.data[index]);
  61162. }
  61163. engine.setAlphaTesting(true);
  61164. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61165. renderSubMesh(alphaTestSubMeshes.data[index]);
  61166. }
  61167. engine.setAlphaTesting(false);
  61168. if (transparentSubMeshes.length) {
  61169. // Sort sub meshes
  61170. for (index = 0; index < transparentSubMeshes.length; index++) {
  61171. var submesh = transparentSubMeshes.data[index];
  61172. var boundingInfo = submesh.getBoundingInfo();
  61173. if (boundingInfo && scene.activeCamera) {
  61174. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  61175. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  61176. }
  61177. }
  61178. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  61179. sortedArray.sort(function (a, b) {
  61180. // Alpha index first
  61181. if (a._alphaIndex > b._alphaIndex) {
  61182. return 1;
  61183. }
  61184. if (a._alphaIndex < b._alphaIndex) {
  61185. return -1;
  61186. }
  61187. // Then distance to camera
  61188. if (a._distanceToCamera < b._distanceToCamera) {
  61189. return 1;
  61190. }
  61191. if (a._distanceToCamera > b._distanceToCamera) {
  61192. return -1;
  61193. }
  61194. return 0;
  61195. });
  61196. // Render sub meshes
  61197. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  61198. for (index = 0; index < sortedArray.length; index++) {
  61199. renderSubMesh(sortedArray[index]);
  61200. }
  61201. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  61202. }
  61203. };
  61204. };
  61205. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  61206. var transform = scene.getTransformMatrix();
  61207. var meshPosition;
  61208. if (this.useCustomMeshPosition) {
  61209. meshPosition = this.customMeshPosition;
  61210. }
  61211. else if (this.attachedNode) {
  61212. meshPosition = this.attachedNode.position;
  61213. }
  61214. else {
  61215. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  61216. }
  61217. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  61218. this._screenCoordinates.x = pos.x / this._viewPort.width;
  61219. this._screenCoordinates.y = pos.y / this._viewPort.height;
  61220. if (this.invert)
  61221. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  61222. };
  61223. // Static methods
  61224. /**
  61225. * Creates a default mesh for the Volumeric Light Scattering post-process
  61226. * @param {string} The mesh name
  61227. * @param {BABYLON.Scene} The scene where to create the mesh
  61228. * @return {BABYLON.Mesh} the default mesh
  61229. */
  61230. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  61231. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  61232. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  61233. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  61234. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  61235. mesh.material = material;
  61236. return mesh;
  61237. };
  61238. __decorate([
  61239. BABYLON.serializeAsVector3()
  61240. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  61241. __decorate([
  61242. BABYLON.serialize()
  61243. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  61244. __decorate([
  61245. BABYLON.serialize()
  61246. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  61247. __decorate([
  61248. BABYLON.serializeAsMeshReference()
  61249. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  61250. __decorate([
  61251. BABYLON.serialize()
  61252. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  61253. __decorate([
  61254. BABYLON.serialize()
  61255. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  61256. __decorate([
  61257. BABYLON.serialize()
  61258. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  61259. __decorate([
  61260. BABYLON.serialize()
  61261. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  61262. __decorate([
  61263. BABYLON.serialize()
  61264. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  61265. return VolumetricLightScatteringPostProcess;
  61266. }(BABYLON.PostProcess));
  61267. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  61268. })(BABYLON || (BABYLON = {}));
  61269. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  61270. //
  61271. // This post-process allows the modification of rendered colors by using
  61272. // a 'look-up table' (LUT). This effect is also called Color Grading.
  61273. //
  61274. // The object needs to be provided an url to a texture containing the color
  61275. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  61276. // Use an image editing software to tweak the LUT to match your needs.
  61277. //
  61278. // For an example of a color LUT, see here:
  61279. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  61280. // For explanations on color grading, see here:
  61281. // http://udn.epicgames.com/Three/ColorGrading.html
  61282. //
  61283. var BABYLON;
  61284. (function (BABYLON) {
  61285. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  61286. __extends(ColorCorrectionPostProcess, _super);
  61287. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  61288. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  61289. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  61290. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  61291. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61292. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61293. _this.onApply = function (effect) {
  61294. effect.setTexture("colorTable", _this._colorTableTexture);
  61295. };
  61296. return _this;
  61297. }
  61298. return ColorCorrectionPostProcess;
  61299. }(BABYLON.PostProcess));
  61300. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  61301. })(BABYLON || (BABYLON = {}));
  61302. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  61303. var BABYLON;
  61304. (function (BABYLON) {
  61305. var TonemappingOperator;
  61306. (function (TonemappingOperator) {
  61307. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  61308. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  61309. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  61310. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  61311. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  61312. ;
  61313. var TonemapPostProcess = /** @class */ (function (_super) {
  61314. __extends(TonemapPostProcess, _super);
  61315. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  61316. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  61317. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61318. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  61319. _this._operator = _operator;
  61320. _this.exposureAdjustment = exposureAdjustment;
  61321. var defines = "#define ";
  61322. if (_this._operator === TonemappingOperator.Hable)
  61323. defines += "HABLE_TONEMAPPING";
  61324. else if (_this._operator === TonemappingOperator.Reinhard)
  61325. defines += "REINHARD_TONEMAPPING";
  61326. else if (_this._operator === TonemappingOperator.HejiDawson)
  61327. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  61328. else if (_this._operator === TonemappingOperator.Photographic)
  61329. defines += "PHOTOGRAPHIC_TONEMAPPING";
  61330. //sadly a second call to create the effect.
  61331. _this.updateEffect(defines);
  61332. _this.onApply = function (effect) {
  61333. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  61334. };
  61335. return _this;
  61336. }
  61337. return TonemapPostProcess;
  61338. }(BABYLON.PostProcess));
  61339. BABYLON.TonemapPostProcess = TonemapPostProcess;
  61340. })(BABYLON || (BABYLON = {}));
  61341. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  61342. var BABYLON;
  61343. (function (BABYLON) {
  61344. var DisplayPassPostProcess = /** @class */ (function (_super) {
  61345. __extends(DisplayPassPostProcess, _super);
  61346. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  61347. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  61348. }
  61349. return DisplayPassPostProcess;
  61350. }(BABYLON.PostProcess));
  61351. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  61352. })(BABYLON || (BABYLON = {}));
  61353. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  61354. var BABYLON;
  61355. (function (BABYLON) {
  61356. var HighlightsPostProcess = /** @class */ (function (_super) {
  61357. __extends(HighlightsPostProcess, _super);
  61358. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  61359. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61360. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  61361. }
  61362. return HighlightsPostProcess;
  61363. }(BABYLON.PostProcess));
  61364. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  61365. })(BABYLON || (BABYLON = {}));
  61366. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  61367. var BABYLON;
  61368. (function (BABYLON) {
  61369. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  61370. __extends(ImageProcessingPostProcess, _super);
  61371. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  61372. if (camera === void 0) { camera = null; }
  61373. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61374. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  61375. _this._fromLinearSpace = true;
  61376. /**
  61377. * Defines cache preventing GC.
  61378. */
  61379. _this._defines = {
  61380. IMAGEPROCESSING: false,
  61381. VIGNETTE: false,
  61382. VIGNETTEBLENDMODEMULTIPLY: false,
  61383. VIGNETTEBLENDMODEOPAQUE: false,
  61384. TONEMAPPING: false,
  61385. CONTRAST: false,
  61386. COLORCURVES: false,
  61387. COLORGRADING: false,
  61388. COLORGRADING3D: false,
  61389. FROMLINEARSPACE: false,
  61390. SAMPLER3DGREENDEPTH: false,
  61391. SAMPLER3DBGRMAP: false,
  61392. IMAGEPROCESSINGPOSTPROCESS: false,
  61393. EXPOSURE: false,
  61394. };
  61395. // Setup the configuration as forced by the constructor. This would then not force the
  61396. // scene materials output in linear space and let untouched the default forward pass.
  61397. if (imageProcessingConfiguration) {
  61398. imageProcessingConfiguration.applyByPostProcess = true;
  61399. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  61400. // This will cause the shader to be compiled
  61401. _this.fromLinearSpace = false;
  61402. }
  61403. else {
  61404. _this._attachImageProcessingConfiguration(null, true);
  61405. _this.imageProcessingConfiguration.applyByPostProcess = true;
  61406. }
  61407. _this.onApply = function (effect) {
  61408. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  61409. };
  61410. return _this;
  61411. }
  61412. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  61413. /**
  61414. * Gets the image processing configuration used either in this material.
  61415. */
  61416. get: function () {
  61417. return this._imageProcessingConfiguration;
  61418. },
  61419. /**
  61420. * Sets the Default image processing configuration used either in the this material.
  61421. *
  61422. * If sets to null, the scene one is in use.
  61423. */
  61424. set: function (value) {
  61425. this._attachImageProcessingConfiguration(value);
  61426. },
  61427. enumerable: true,
  61428. configurable: true
  61429. });
  61430. /**
  61431. * Attaches a new image processing configuration to the PBR Material.
  61432. * @param configuration
  61433. */
  61434. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  61435. var _this = this;
  61436. if (doNotBuild === void 0) { doNotBuild = false; }
  61437. if (configuration === this._imageProcessingConfiguration) {
  61438. return;
  61439. }
  61440. // Detaches observer.
  61441. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  61442. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  61443. }
  61444. // Pick the scene configuration if needed.
  61445. if (!configuration) {
  61446. var scene = null;
  61447. var engine = this.getEngine();
  61448. var camera = this.getCamera();
  61449. if (camera) {
  61450. scene = camera.getScene();
  61451. }
  61452. else if (engine && engine.scenes) {
  61453. var scenes = engine.scenes;
  61454. scene = scenes[scenes.length - 1];
  61455. }
  61456. else {
  61457. scene = BABYLON.Engine.LastCreatedScene;
  61458. }
  61459. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  61460. }
  61461. else {
  61462. this._imageProcessingConfiguration = configuration;
  61463. }
  61464. // Attaches observer.
  61465. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  61466. _this._updateParameters();
  61467. });
  61468. // Ensure the effect will be rebuilt.
  61469. if (!doNotBuild) {
  61470. this._updateParameters();
  61471. }
  61472. };
  61473. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  61474. /**
  61475. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  61476. */
  61477. get: function () {
  61478. return this.imageProcessingConfiguration.colorCurves;
  61479. },
  61480. /**
  61481. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  61482. */
  61483. set: function (value) {
  61484. this.imageProcessingConfiguration.colorCurves = value;
  61485. },
  61486. enumerable: true,
  61487. configurable: true
  61488. });
  61489. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  61490. /**
  61491. * Gets wether the color curves effect is enabled.
  61492. */
  61493. get: function () {
  61494. return this.imageProcessingConfiguration.colorCurvesEnabled;
  61495. },
  61496. /**
  61497. * Sets wether the color curves effect is enabled.
  61498. */
  61499. set: function (value) {
  61500. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  61501. },
  61502. enumerable: true,
  61503. configurable: true
  61504. });
  61505. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  61506. /**
  61507. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  61508. */
  61509. get: function () {
  61510. return this.imageProcessingConfiguration.colorGradingTexture;
  61511. },
  61512. /**
  61513. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  61514. */
  61515. set: function (value) {
  61516. this.imageProcessingConfiguration.colorGradingTexture = value;
  61517. },
  61518. enumerable: true,
  61519. configurable: true
  61520. });
  61521. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  61522. /**
  61523. * Gets wether the color grading effect is enabled.
  61524. */
  61525. get: function () {
  61526. return this.imageProcessingConfiguration.colorGradingEnabled;
  61527. },
  61528. /**
  61529. * Gets wether the color grading effect is enabled.
  61530. */
  61531. set: function (value) {
  61532. this.imageProcessingConfiguration.colorGradingEnabled = value;
  61533. },
  61534. enumerable: true,
  61535. configurable: true
  61536. });
  61537. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  61538. /**
  61539. * Gets exposure used in the effect.
  61540. */
  61541. get: function () {
  61542. return this.imageProcessingConfiguration.exposure;
  61543. },
  61544. /**
  61545. * Sets exposure used in the effect.
  61546. */
  61547. set: function (value) {
  61548. this.imageProcessingConfiguration.exposure = value;
  61549. },
  61550. enumerable: true,
  61551. configurable: true
  61552. });
  61553. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  61554. /**
  61555. * Gets wether tonemapping is enabled or not.
  61556. */
  61557. get: function () {
  61558. return this._imageProcessingConfiguration.toneMappingEnabled;
  61559. },
  61560. /**
  61561. * Sets wether tonemapping is enabled or not
  61562. */
  61563. set: function (value) {
  61564. this._imageProcessingConfiguration.toneMappingEnabled = value;
  61565. },
  61566. enumerable: true,
  61567. configurable: true
  61568. });
  61569. ;
  61570. ;
  61571. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  61572. /**
  61573. * Gets contrast used in the effect.
  61574. */
  61575. get: function () {
  61576. return this.imageProcessingConfiguration.contrast;
  61577. },
  61578. /**
  61579. * Sets contrast used in the effect.
  61580. */
  61581. set: function (value) {
  61582. this.imageProcessingConfiguration.contrast = value;
  61583. },
  61584. enumerable: true,
  61585. configurable: true
  61586. });
  61587. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  61588. /**
  61589. * Gets Vignette stretch size.
  61590. */
  61591. get: function () {
  61592. return this.imageProcessingConfiguration.vignetteStretch;
  61593. },
  61594. /**
  61595. * Sets Vignette stretch size.
  61596. */
  61597. set: function (value) {
  61598. this.imageProcessingConfiguration.vignetteStretch = value;
  61599. },
  61600. enumerable: true,
  61601. configurable: true
  61602. });
  61603. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  61604. /**
  61605. * Gets Vignette centre X Offset.
  61606. */
  61607. get: function () {
  61608. return this.imageProcessingConfiguration.vignetteCentreX;
  61609. },
  61610. /**
  61611. * Sets Vignette centre X Offset.
  61612. */
  61613. set: function (value) {
  61614. this.imageProcessingConfiguration.vignetteCentreX = value;
  61615. },
  61616. enumerable: true,
  61617. configurable: true
  61618. });
  61619. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  61620. /**
  61621. * Gets Vignette centre Y Offset.
  61622. */
  61623. get: function () {
  61624. return this.imageProcessingConfiguration.vignetteCentreY;
  61625. },
  61626. /**
  61627. * Sets Vignette centre Y Offset.
  61628. */
  61629. set: function (value) {
  61630. this.imageProcessingConfiguration.vignetteCentreY = value;
  61631. },
  61632. enumerable: true,
  61633. configurable: true
  61634. });
  61635. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  61636. /**
  61637. * Gets Vignette weight or intensity of the vignette effect.
  61638. */
  61639. get: function () {
  61640. return this.imageProcessingConfiguration.vignetteWeight;
  61641. },
  61642. /**
  61643. * Sets Vignette weight or intensity of the vignette effect.
  61644. */
  61645. set: function (value) {
  61646. this.imageProcessingConfiguration.vignetteWeight = value;
  61647. },
  61648. enumerable: true,
  61649. configurable: true
  61650. });
  61651. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  61652. /**
  61653. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  61654. * if vignetteEnabled is set to true.
  61655. */
  61656. get: function () {
  61657. return this.imageProcessingConfiguration.vignetteColor;
  61658. },
  61659. /**
  61660. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  61661. * if vignetteEnabled is set to true.
  61662. */
  61663. set: function (value) {
  61664. this.imageProcessingConfiguration.vignetteColor = value;
  61665. },
  61666. enumerable: true,
  61667. configurable: true
  61668. });
  61669. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  61670. /**
  61671. * Gets Camera field of view used by the Vignette effect.
  61672. */
  61673. get: function () {
  61674. return this.imageProcessingConfiguration.vignetteCameraFov;
  61675. },
  61676. /**
  61677. * Sets Camera field of view used by the Vignette effect.
  61678. */
  61679. set: function (value) {
  61680. this.imageProcessingConfiguration.vignetteCameraFov = value;
  61681. },
  61682. enumerable: true,
  61683. configurable: true
  61684. });
  61685. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  61686. /**
  61687. * Gets the vignette blend mode allowing different kind of effect.
  61688. */
  61689. get: function () {
  61690. return this.imageProcessingConfiguration.vignetteBlendMode;
  61691. },
  61692. /**
  61693. * Sets the vignette blend mode allowing different kind of effect.
  61694. */
  61695. set: function (value) {
  61696. this.imageProcessingConfiguration.vignetteBlendMode = value;
  61697. },
  61698. enumerable: true,
  61699. configurable: true
  61700. });
  61701. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  61702. /**
  61703. * Gets wether the vignette effect is enabled.
  61704. */
  61705. get: function () {
  61706. return this.imageProcessingConfiguration.vignetteEnabled;
  61707. },
  61708. /**
  61709. * Sets wether the vignette effect is enabled.
  61710. */
  61711. set: function (value) {
  61712. this.imageProcessingConfiguration.vignetteEnabled = value;
  61713. },
  61714. enumerable: true,
  61715. configurable: true
  61716. });
  61717. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  61718. /**
  61719. * Gets wether the input of the processing is in Gamma or Linear Space.
  61720. */
  61721. get: function () {
  61722. return this._fromLinearSpace;
  61723. },
  61724. /**
  61725. * Sets wether the input of the processing is in Gamma or Linear Space.
  61726. */
  61727. set: function (value) {
  61728. if (this._fromLinearSpace === value) {
  61729. return;
  61730. }
  61731. this._fromLinearSpace = value;
  61732. this._updateParameters();
  61733. },
  61734. enumerable: true,
  61735. configurable: true
  61736. });
  61737. ImageProcessingPostProcess.prototype.getClassName = function () {
  61738. return "ImageProcessingPostProcess";
  61739. };
  61740. ImageProcessingPostProcess.prototype._updateParameters = function () {
  61741. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  61742. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  61743. var defines = "";
  61744. for (var define in this._defines) {
  61745. if (this._defines[define]) {
  61746. defines += "#define " + define + ";\r\n";
  61747. }
  61748. }
  61749. var samplers = ["textureSampler"];
  61750. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  61751. var uniforms = ["scale"];
  61752. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  61753. this.updateEffect(defines, uniforms, samplers);
  61754. };
  61755. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  61756. _super.prototype.dispose.call(this, camera);
  61757. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  61758. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  61759. }
  61760. this.imageProcessingConfiguration.applyByPostProcess = false;
  61761. };
  61762. __decorate([
  61763. BABYLON.serialize()
  61764. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  61765. return ImageProcessingPostProcess;
  61766. }(BABYLON.PostProcess));
  61767. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  61768. })(BABYLON || (BABYLON = {}));
  61769. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  61770. var BABYLON;
  61771. (function (BABYLON) {
  61772. var BlurPostProcess = /** @class */ (function (_super) {
  61773. __extends(BlurPostProcess, _super);
  61774. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  61775. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  61776. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61777. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  61778. _this.direction = direction;
  61779. _this._packedFloat = false;
  61780. _this.onApplyObservable.add(function (effect) {
  61781. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  61782. });
  61783. _this.kernel = kernel;
  61784. return _this;
  61785. }
  61786. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  61787. /**
  61788. * Gets the length in pixels of the blur sample region
  61789. */
  61790. get: function () {
  61791. return this._idealKernel;
  61792. },
  61793. /**
  61794. * Sets the length in pixels of the blur sample region
  61795. */
  61796. set: function (v) {
  61797. if (this._idealKernel === v) {
  61798. return;
  61799. }
  61800. v = Math.max(v, 1);
  61801. this._idealKernel = v;
  61802. this._kernel = this._nearestBestKernel(v);
  61803. this._updateParameters();
  61804. },
  61805. enumerable: true,
  61806. configurable: true
  61807. });
  61808. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  61809. /**
  61810. * Gets wether or not the blur is unpacking/repacking floats
  61811. */
  61812. get: function () {
  61813. return this._packedFloat;
  61814. },
  61815. /**
  61816. * Sets wether or not the blur needs to unpack/repack floats
  61817. */
  61818. set: function (v) {
  61819. if (this._packedFloat === v) {
  61820. return;
  61821. }
  61822. this._packedFloat = v;
  61823. this._updateParameters();
  61824. },
  61825. enumerable: true,
  61826. configurable: true
  61827. });
  61828. BlurPostProcess.prototype._updateParameters = function () {
  61829. // Generate sampling offsets and weights
  61830. var N = this._kernel;
  61831. var centerIndex = (N - 1) / 2;
  61832. // Generate Gaussian sampling weights over kernel
  61833. var offsets = [];
  61834. var weights = [];
  61835. var totalWeight = 0;
  61836. for (var i = 0; i < N; i++) {
  61837. var u = i / (N - 1);
  61838. var w = this._gaussianWeight(u * 2.0 - 1);
  61839. offsets[i] = (i - centerIndex);
  61840. weights[i] = w;
  61841. totalWeight += w;
  61842. }
  61843. // Normalize weights
  61844. for (var i = 0; i < weights.length; i++) {
  61845. weights[i] /= totalWeight;
  61846. }
  61847. // Optimize: combine samples to take advantage of hardware linear sampling
  61848. // Walk from left to center, combining pairs (symmetrically)
  61849. var linearSamplingWeights = [];
  61850. var linearSamplingOffsets = [];
  61851. var linearSamplingMap = [];
  61852. for (var i = 0; i <= centerIndex; i += 2) {
  61853. var j = Math.min(i + 1, Math.floor(centerIndex));
  61854. var singleCenterSample = i === j;
  61855. if (singleCenterSample) {
  61856. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  61857. }
  61858. else {
  61859. var sharedCell = j === centerIndex;
  61860. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  61861. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  61862. if (offsetLinear === 0) {
  61863. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  61864. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  61865. }
  61866. else {
  61867. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  61868. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  61869. }
  61870. }
  61871. }
  61872. for (var i = 0; i < linearSamplingMap.length; i++) {
  61873. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  61874. linearSamplingWeights[i] = linearSamplingMap[i].w;
  61875. }
  61876. // Replace with optimized
  61877. offsets = linearSamplingOffsets;
  61878. weights = linearSamplingWeights;
  61879. // Generate shaders
  61880. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  61881. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  61882. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  61883. var defines = "";
  61884. for (var i = 0; i < varyingCount; i++) {
  61885. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  61886. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  61887. }
  61888. var depCount = 0;
  61889. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  61890. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  61891. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  61892. depCount++;
  61893. }
  61894. if (this.packedFloat) {
  61895. defines += "#define PACKEDFLOAT 1";
  61896. }
  61897. this.updateEffect(defines, null, null, {
  61898. varyingCount: varyingCount,
  61899. depCount: depCount
  61900. });
  61901. };
  61902. /**
  61903. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  61904. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  61905. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  61906. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  61907. * The gaps between physical kernels are compensated for in the weighting of the samples
  61908. * @param idealKernel Ideal blur kernel.
  61909. * @return Nearest best kernel.
  61910. */
  61911. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  61912. var v = Math.round(idealKernel);
  61913. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  61914. var k = _a[_i];
  61915. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  61916. return Math.max(k, 3);
  61917. }
  61918. }
  61919. return Math.max(v, 3);
  61920. };
  61921. /**
  61922. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  61923. * @param x The point on the Gaussian distribution to sample.
  61924. * @return the value of the Gaussian function at x.
  61925. */
  61926. BlurPostProcess.prototype._gaussianWeight = function (x) {
  61927. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  61928. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  61929. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  61930. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  61931. // truncated at around 1.3% of peak strength.
  61932. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  61933. var sigma = (1 / 3);
  61934. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  61935. var exponent = -((x * x) / (2.0 * sigma * sigma));
  61936. var weight = (1.0 / denominator) * Math.exp(exponent);
  61937. return weight;
  61938. };
  61939. /**
  61940. * Generates a string that can be used as a floating point number in GLSL.
  61941. * @param x Value to print.
  61942. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  61943. * @return GLSL float string.
  61944. */
  61945. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  61946. if (decimalFigures === void 0) { decimalFigures = 8; }
  61947. return x.toFixed(decimalFigures).replace(/0+$/, '');
  61948. };
  61949. return BlurPostProcess;
  61950. }(BABYLON.PostProcess));
  61951. BABYLON.BlurPostProcess = BlurPostProcess;
  61952. })(BABYLON || (BABYLON = {}));
  61953. //# sourceMappingURL=babylon.blurPostProcess.js.map
  61954. var BABYLON;
  61955. (function (BABYLON) {
  61956. var Bone = /** @class */ (function (_super) {
  61957. __extends(Bone, _super);
  61958. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  61959. if (parentBone === void 0) { parentBone = null; }
  61960. if (localMatrix === void 0) { localMatrix = null; }
  61961. if (restPose === void 0) { restPose = null; }
  61962. if (baseMatrix === void 0) { baseMatrix = null; }
  61963. if (index === void 0) { index = null; }
  61964. var _this = _super.call(this, name, skeleton.getScene()) || this;
  61965. _this.name = name;
  61966. _this.children = new Array();
  61967. _this.animations = new Array();
  61968. // Set this value to map this bone to a different index in the transform matrices.
  61969. // Set this value to -1 to exclude the bone from the transform matrices.
  61970. _this._index = null;
  61971. _this._worldTransform = new BABYLON.Matrix();
  61972. _this._absoluteTransform = new BABYLON.Matrix();
  61973. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  61974. _this._scaleMatrix = BABYLON.Matrix.Identity();
  61975. _this._scaleVector = BABYLON.Vector3.One();
  61976. _this._negateScaleChildren = BABYLON.Vector3.One();
  61977. _this._scalingDeterminant = 1;
  61978. _this._skeleton = skeleton;
  61979. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  61980. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  61981. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  61982. _this._index = index;
  61983. skeleton.bones.push(_this);
  61984. _this.setParent(parentBone, false);
  61985. _this._updateDifferenceMatrix();
  61986. return _this;
  61987. }
  61988. Object.defineProperty(Bone.prototype, "_matrix", {
  61989. get: function () {
  61990. return this._localMatrix;
  61991. },
  61992. set: function (val) {
  61993. if (this._localMatrix) {
  61994. this._localMatrix.copyFrom(val);
  61995. }
  61996. else {
  61997. this._localMatrix = val;
  61998. }
  61999. },
  62000. enumerable: true,
  62001. configurable: true
  62002. });
  62003. // Members
  62004. Bone.prototype.getSkeleton = function () {
  62005. return this._skeleton;
  62006. };
  62007. Bone.prototype.getParent = function () {
  62008. return this._parent;
  62009. };
  62010. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  62011. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  62012. if (this._parent === parent) {
  62013. return;
  62014. }
  62015. if (this._parent) {
  62016. var index = this._parent.children.indexOf(this);
  62017. if (index !== -1) {
  62018. this._parent.children.splice(index, 1);
  62019. }
  62020. }
  62021. this._parent = parent;
  62022. if (this._parent) {
  62023. this._parent.children.push(this);
  62024. }
  62025. if (updateDifferenceMatrix) {
  62026. this._updateDifferenceMatrix();
  62027. }
  62028. };
  62029. Bone.prototype.getLocalMatrix = function () {
  62030. return this._localMatrix;
  62031. };
  62032. Bone.prototype.getBaseMatrix = function () {
  62033. return this._baseMatrix;
  62034. };
  62035. Bone.prototype.getRestPose = function () {
  62036. return this._restPose;
  62037. };
  62038. Bone.prototype.returnToRest = function () {
  62039. this.updateMatrix(this._restPose.clone());
  62040. };
  62041. Bone.prototype.getWorldMatrix = function () {
  62042. return this._worldTransform;
  62043. };
  62044. Bone.prototype.getInvertedAbsoluteTransform = function () {
  62045. return this._invertedAbsoluteTransform;
  62046. };
  62047. Bone.prototype.getAbsoluteTransform = function () {
  62048. return this._absoluteTransform;
  62049. };
  62050. Object.defineProperty(Bone.prototype, "position", {
  62051. // Properties (matches AbstractMesh properties)
  62052. get: function () {
  62053. return this.getPosition();
  62054. },
  62055. set: function (newPosition) {
  62056. this.setPosition(newPosition);
  62057. },
  62058. enumerable: true,
  62059. configurable: true
  62060. });
  62061. Object.defineProperty(Bone.prototype, "rotation", {
  62062. get: function () {
  62063. return this.getRotation();
  62064. },
  62065. set: function (newRotation) {
  62066. this.setRotation(newRotation);
  62067. },
  62068. enumerable: true,
  62069. configurable: true
  62070. });
  62071. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  62072. get: function () {
  62073. return this.getRotationQuaternion();
  62074. },
  62075. set: function (newRotation) {
  62076. this.setRotationQuaternion(newRotation);
  62077. },
  62078. enumerable: true,
  62079. configurable: true
  62080. });
  62081. Object.defineProperty(Bone.prototype, "scaling", {
  62082. get: function () {
  62083. return this.getScale();
  62084. },
  62085. set: function (newScaling) {
  62086. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  62087. },
  62088. enumerable: true,
  62089. configurable: true
  62090. });
  62091. // Methods
  62092. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  62093. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  62094. this._baseMatrix = matrix.clone();
  62095. this._localMatrix = matrix.clone();
  62096. this._skeleton._markAsDirty();
  62097. if (updateDifferenceMatrix) {
  62098. this._updateDifferenceMatrix();
  62099. }
  62100. };
  62101. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  62102. if (!rootMatrix) {
  62103. rootMatrix = this._baseMatrix;
  62104. }
  62105. if (this._parent) {
  62106. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  62107. }
  62108. else {
  62109. this._absoluteTransform.copyFrom(rootMatrix);
  62110. }
  62111. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  62112. for (var index = 0; index < this.children.length; index++) {
  62113. this.children[index]._updateDifferenceMatrix();
  62114. }
  62115. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  62116. };
  62117. Bone.prototype.markAsDirty = function () {
  62118. this._currentRenderId++;
  62119. this._skeleton._markAsDirty();
  62120. };
  62121. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  62122. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  62123. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  62124. // all animation may be coming from a library skeleton, so may need to create animation
  62125. if (this.animations.length === 0) {
  62126. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  62127. this.animations[0].setKeys([]);
  62128. }
  62129. // get animation info / verify there is such a range from the source bone
  62130. var sourceRange = source.animations[0].getRange(rangeName);
  62131. if (!sourceRange) {
  62132. return false;
  62133. }
  62134. var from = sourceRange.from;
  62135. var to = sourceRange.to;
  62136. var sourceKeys = source.animations[0].getKeys();
  62137. // rescaling prep
  62138. var sourceBoneLength = source.length;
  62139. var sourceParent = source.getParent();
  62140. var parent = this.getParent();
  62141. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  62142. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  62143. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  62144. var destKeys = this.animations[0].getKeys();
  62145. // loop vars declaration
  62146. var orig;
  62147. var origTranslation;
  62148. var mat;
  62149. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  62150. orig = sourceKeys[key];
  62151. if (orig.frame >= from && orig.frame <= to) {
  62152. if (rescaleAsRequired) {
  62153. mat = orig.value.clone();
  62154. // scale based on parent ratio, when bone has parent
  62155. if (parentScalingReqd) {
  62156. origTranslation = mat.getTranslation();
  62157. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  62158. // scale based on skeleton dimension ratio when root bone, and value is passed
  62159. }
  62160. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  62161. origTranslation = mat.getTranslation();
  62162. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  62163. // use original when root bone, and no data for skelDimensionsRatio
  62164. }
  62165. else {
  62166. mat = orig.value;
  62167. }
  62168. }
  62169. else {
  62170. mat = orig.value;
  62171. }
  62172. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  62173. }
  62174. }
  62175. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  62176. return true;
  62177. };
  62178. /**
  62179. * Translate the bone in local or world space.
  62180. * @param vec The amount to translate the bone.
  62181. * @param space The space that the translation is in.
  62182. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62183. */
  62184. Bone.prototype.translate = function (vec, space, mesh) {
  62185. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62186. var lm = this.getLocalMatrix();
  62187. if (space == BABYLON.Space.LOCAL) {
  62188. lm.m[12] += vec.x;
  62189. lm.m[13] += vec.y;
  62190. lm.m[14] += vec.z;
  62191. }
  62192. else {
  62193. var wm = null;
  62194. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  62195. if (mesh) {
  62196. wm = mesh.getWorldMatrix();
  62197. }
  62198. this._skeleton.computeAbsoluteTransforms();
  62199. var tmat = Bone._tmpMats[0];
  62200. var tvec = Bone._tmpVecs[0];
  62201. if (this._parent) {
  62202. if (mesh && wm) {
  62203. tmat.copyFrom(this._parent.getAbsoluteTransform());
  62204. tmat.multiplyToRef(wm, tmat);
  62205. }
  62206. else {
  62207. tmat.copyFrom(this._parent.getAbsoluteTransform());
  62208. }
  62209. }
  62210. tmat.m[12] = 0;
  62211. tmat.m[13] = 0;
  62212. tmat.m[14] = 0;
  62213. tmat.invert();
  62214. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  62215. lm.m[12] += tvec.x;
  62216. lm.m[13] += tvec.y;
  62217. lm.m[14] += tvec.z;
  62218. }
  62219. this.markAsDirty();
  62220. };
  62221. /**
  62222. * Set the postion of the bone in local or world space.
  62223. * @param position The position to set the bone.
  62224. * @param space The space that the position is in.
  62225. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62226. */
  62227. Bone.prototype.setPosition = function (position, space, mesh) {
  62228. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62229. var lm = this.getLocalMatrix();
  62230. if (space == BABYLON.Space.LOCAL) {
  62231. lm.m[12] = position.x;
  62232. lm.m[13] = position.y;
  62233. lm.m[14] = position.z;
  62234. }
  62235. else {
  62236. var wm = null;
  62237. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  62238. if (mesh) {
  62239. wm = mesh.getWorldMatrix();
  62240. }
  62241. this._skeleton.computeAbsoluteTransforms();
  62242. var tmat = Bone._tmpMats[0];
  62243. var vec = Bone._tmpVecs[0];
  62244. if (this._parent) {
  62245. if (mesh && wm) {
  62246. tmat.copyFrom(this._parent.getAbsoluteTransform());
  62247. tmat.multiplyToRef(wm, tmat);
  62248. }
  62249. else {
  62250. tmat.copyFrom(this._parent.getAbsoluteTransform());
  62251. }
  62252. }
  62253. tmat.invert();
  62254. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  62255. lm.m[12] = vec.x;
  62256. lm.m[13] = vec.y;
  62257. lm.m[14] = vec.z;
  62258. }
  62259. this.markAsDirty();
  62260. };
  62261. /**
  62262. * Set the absolute postion of the bone (world space).
  62263. * @param position The position to set the bone.
  62264. * @param mesh The mesh that this bone is attached to.
  62265. */
  62266. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  62267. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  62268. };
  62269. /**
  62270. * Set the scale of the bone on the x, y and z axes.
  62271. * @param x The scale of the bone on the x axis.
  62272. * @param x The scale of the bone on the y axis.
  62273. * @param z The scale of the bone on the z axis.
  62274. * @param scaleChildren Set this to true if children of the bone should be scaled.
  62275. */
  62276. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  62277. if (scaleChildren === void 0) { scaleChildren = false; }
  62278. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  62279. if (!scaleChildren) {
  62280. this._negateScaleChildren.x = 1 / x;
  62281. this._negateScaleChildren.y = 1 / y;
  62282. this._negateScaleChildren.z = 1 / z;
  62283. }
  62284. this._syncScaleVector();
  62285. }
  62286. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  62287. };
  62288. /**
  62289. * Scale the bone on the x, y and z axes.
  62290. * @param x The amount to scale the bone on the x axis.
  62291. * @param x The amount to scale the bone on the y axis.
  62292. * @param z The amount to scale the bone on the z axis.
  62293. * @param scaleChildren Set this to true if children of the bone should be scaled.
  62294. */
  62295. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  62296. if (scaleChildren === void 0) { scaleChildren = false; }
  62297. var locMat = this.getLocalMatrix();
  62298. var origLocMat = Bone._tmpMats[0];
  62299. origLocMat.copyFrom(locMat);
  62300. var origLocMatInv = Bone._tmpMats[1];
  62301. origLocMatInv.copyFrom(origLocMat);
  62302. origLocMatInv.invert();
  62303. var scaleMat = Bone._tmpMats[2];
  62304. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  62305. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  62306. this._scaleVector.x *= x;
  62307. this._scaleVector.y *= y;
  62308. this._scaleVector.z *= z;
  62309. locMat.multiplyToRef(origLocMatInv, locMat);
  62310. locMat.multiplyToRef(scaleMat, locMat);
  62311. locMat.multiplyToRef(origLocMat, locMat);
  62312. var parent = this.getParent();
  62313. if (parent) {
  62314. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  62315. }
  62316. else {
  62317. this.getAbsoluteTransform().copyFrom(locMat);
  62318. }
  62319. var len = this.children.length;
  62320. scaleMat.invert();
  62321. for (var i = 0; i < len; i++) {
  62322. var child = this.children[i];
  62323. var cm = child.getLocalMatrix();
  62324. cm.multiplyToRef(scaleMat, cm);
  62325. var lm = child.getLocalMatrix();
  62326. lm.m[12] *= x;
  62327. lm.m[13] *= y;
  62328. lm.m[14] *= z;
  62329. }
  62330. this.computeAbsoluteTransforms();
  62331. if (scaleChildren) {
  62332. for (var i = 0; i < len; i++) {
  62333. this.children[i].scale(x, y, z, scaleChildren);
  62334. }
  62335. }
  62336. this.markAsDirty();
  62337. };
  62338. /**
  62339. * Set the yaw, pitch, and roll of the bone in local or world space.
  62340. * @param yaw The rotation of the bone on the y axis.
  62341. * @param pitch The rotation of the bone on the x axis.
  62342. * @param roll The rotation of the bone on the z axis.
  62343. * @param space The space that the axes of rotation are in.
  62344. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62345. */
  62346. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  62347. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62348. var rotMat = Bone._tmpMats[0];
  62349. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  62350. var rotMatInv = Bone._tmpMats[1];
  62351. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  62352. rotMatInv.multiplyToRef(rotMat, rotMat);
  62353. this._rotateWithMatrix(rotMat, space, mesh);
  62354. };
  62355. /**
  62356. * Rotate the bone on an axis in local or world space.
  62357. * @param axis The axis to rotate the bone on.
  62358. * @param amount The amount to rotate the bone.
  62359. * @param space The space that the axis is in.
  62360. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62361. */
  62362. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  62363. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62364. var rmat = Bone._tmpMats[0];
  62365. rmat.m[12] = 0;
  62366. rmat.m[13] = 0;
  62367. rmat.m[14] = 0;
  62368. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  62369. this._rotateWithMatrix(rmat, space, mesh);
  62370. };
  62371. /**
  62372. * Set the rotation of the bone to a particular axis angle in local or world space.
  62373. * @param axis The axis to rotate the bone on.
  62374. * @param angle The angle that the bone should be rotated to.
  62375. * @param space The space that the axis is in.
  62376. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62377. */
  62378. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  62379. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62380. var rotMat = Bone._tmpMats[0];
  62381. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  62382. var rotMatInv = Bone._tmpMats[1];
  62383. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  62384. rotMatInv.multiplyToRef(rotMat, rotMat);
  62385. this._rotateWithMatrix(rotMat, space, mesh);
  62386. };
  62387. /**
  62388. * Set the euler rotation of the bone in local of world space.
  62389. * @param rotation The euler rotation that the bone should be set to.
  62390. * @param space The space that the rotation is in.
  62391. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62392. */
  62393. Bone.prototype.setRotation = function (rotation, space, mesh) {
  62394. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62395. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  62396. };
  62397. /**
  62398. * Set the quaternion rotation of the bone in local of world space.
  62399. * @param quat The quaternion rotation that the bone should be set to.
  62400. * @param space The space that the rotation is in.
  62401. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62402. */
  62403. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  62404. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62405. var rotMatInv = Bone._tmpMats[0];
  62406. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  62407. var rotMat = Bone._tmpMats[1];
  62408. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  62409. rotMatInv.multiplyToRef(rotMat, rotMat);
  62410. this._rotateWithMatrix(rotMat, space, mesh);
  62411. };
  62412. /**
  62413. * Set the rotation matrix of the bone in local of world space.
  62414. * @param rotMat The rotation matrix that the bone should be set to.
  62415. * @param space The space that the rotation is in.
  62416. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62417. */
  62418. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  62419. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62420. var rotMatInv = Bone._tmpMats[0];
  62421. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  62422. var rotMat2 = Bone._tmpMats[1];
  62423. rotMat2.copyFrom(rotMat);
  62424. rotMatInv.multiplyToRef(rotMat, rotMat2);
  62425. this._rotateWithMatrix(rotMat2, space, mesh);
  62426. };
  62427. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  62428. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62429. var lmat = this.getLocalMatrix();
  62430. var lx = lmat.m[12];
  62431. var ly = lmat.m[13];
  62432. var lz = lmat.m[14];
  62433. var parent = this.getParent();
  62434. var parentScale = Bone._tmpMats[3];
  62435. var parentScaleInv = Bone._tmpMats[4];
  62436. if (parent) {
  62437. if (space == BABYLON.Space.WORLD) {
  62438. if (mesh) {
  62439. parentScale.copyFrom(mesh.getWorldMatrix());
  62440. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  62441. }
  62442. else {
  62443. parentScale.copyFrom(parent.getAbsoluteTransform());
  62444. }
  62445. }
  62446. else {
  62447. parentScale = parent._scaleMatrix;
  62448. }
  62449. parentScaleInv.copyFrom(parentScale);
  62450. parentScaleInv.invert();
  62451. lmat.multiplyToRef(parentScale, lmat);
  62452. lmat.multiplyToRef(rmat, lmat);
  62453. lmat.multiplyToRef(parentScaleInv, lmat);
  62454. }
  62455. else {
  62456. if (space == BABYLON.Space.WORLD && mesh) {
  62457. parentScale.copyFrom(mesh.getWorldMatrix());
  62458. parentScaleInv.copyFrom(parentScale);
  62459. parentScaleInv.invert();
  62460. lmat.multiplyToRef(parentScale, lmat);
  62461. lmat.multiplyToRef(rmat, lmat);
  62462. lmat.multiplyToRef(parentScaleInv, lmat);
  62463. }
  62464. else {
  62465. lmat.multiplyToRef(rmat, lmat);
  62466. }
  62467. }
  62468. lmat.m[12] = lx;
  62469. lmat.m[13] = ly;
  62470. lmat.m[14] = lz;
  62471. this.computeAbsoluteTransforms();
  62472. this.markAsDirty();
  62473. };
  62474. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  62475. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62476. if (space == BABYLON.Space.WORLD) {
  62477. var scaleMatrix = Bone._tmpMats[2];
  62478. scaleMatrix.copyFrom(this._scaleMatrix);
  62479. rotMatInv.copyFrom(this.getAbsoluteTransform());
  62480. if (mesh) {
  62481. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  62482. var meshScale = Bone._tmpMats[3];
  62483. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  62484. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  62485. }
  62486. rotMatInv.invert();
  62487. scaleMatrix.m[0] *= this._scalingDeterminant;
  62488. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  62489. }
  62490. else {
  62491. rotMatInv.copyFrom(this.getLocalMatrix());
  62492. rotMatInv.invert();
  62493. var scaleMatrix = Bone._tmpMats[2];
  62494. scaleMatrix.copyFrom(this._scaleMatrix);
  62495. if (this._parent) {
  62496. var pscaleMatrix = Bone._tmpMats[3];
  62497. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  62498. pscaleMatrix.invert();
  62499. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  62500. }
  62501. else {
  62502. scaleMatrix.m[0] *= this._scalingDeterminant;
  62503. }
  62504. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  62505. }
  62506. };
  62507. /**
  62508. * Get the scale of the bone
  62509. * @returns the scale of the bone
  62510. */
  62511. Bone.prototype.getScale = function () {
  62512. return this._scaleVector.clone();
  62513. };
  62514. /**
  62515. * Copy the scale of the bone to a vector3.
  62516. * @param result The vector3 to copy the scale to
  62517. */
  62518. Bone.prototype.getScaleToRef = function (result) {
  62519. result.copyFrom(this._scaleVector);
  62520. };
  62521. /**
  62522. * Get the position of the bone in local or world space.
  62523. * @param space The space that the returned position is in.
  62524. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62525. * @returns The position of the bone
  62526. */
  62527. Bone.prototype.getPosition = function (space, mesh) {
  62528. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62529. if (mesh === void 0) { mesh = null; }
  62530. var pos = BABYLON.Vector3.Zero();
  62531. this.getPositionToRef(space, mesh, pos);
  62532. return pos;
  62533. };
  62534. /**
  62535. * Copy the position of the bone to a vector3 in local or world space.
  62536. * @param space The space that the returned position is in.
  62537. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62538. * @param result The vector3 to copy the position to.
  62539. */
  62540. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  62541. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62542. if (space == BABYLON.Space.LOCAL) {
  62543. var lm = this.getLocalMatrix();
  62544. result.x = lm.m[12];
  62545. result.y = lm.m[13];
  62546. result.z = lm.m[14];
  62547. }
  62548. else {
  62549. var wm = null;
  62550. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  62551. if (mesh) {
  62552. wm = mesh.getWorldMatrix();
  62553. }
  62554. this._skeleton.computeAbsoluteTransforms();
  62555. var tmat = Bone._tmpMats[0];
  62556. if (mesh && wm) {
  62557. tmat.copyFrom(this.getAbsoluteTransform());
  62558. tmat.multiplyToRef(wm, tmat);
  62559. }
  62560. else {
  62561. tmat = this.getAbsoluteTransform();
  62562. }
  62563. result.x = tmat.m[12];
  62564. result.y = tmat.m[13];
  62565. result.z = tmat.m[14];
  62566. }
  62567. };
  62568. /**
  62569. * Get the absolute position of the bone (world space).
  62570. * @param mesh The mesh that this bone is attached to.
  62571. * @returns The absolute position of the bone
  62572. */
  62573. Bone.prototype.getAbsolutePosition = function (mesh) {
  62574. if (mesh === void 0) { mesh = null; }
  62575. var pos = BABYLON.Vector3.Zero();
  62576. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  62577. return pos;
  62578. };
  62579. /**
  62580. * Copy the absolute position of the bone (world space) to the result param.
  62581. * @param mesh The mesh that this bone is attached to.
  62582. * @param result The vector3 to copy the absolute position to.
  62583. */
  62584. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  62585. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  62586. };
  62587. /**
  62588. * Compute the absolute transforms of this bone and its children.
  62589. */
  62590. Bone.prototype.computeAbsoluteTransforms = function () {
  62591. if (this._parent) {
  62592. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  62593. }
  62594. else {
  62595. this._absoluteTransform.copyFrom(this._localMatrix);
  62596. var poseMatrix = this._skeleton.getPoseMatrix();
  62597. if (poseMatrix) {
  62598. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  62599. }
  62600. }
  62601. var children = this.children;
  62602. var len = children.length;
  62603. for (var i = 0; i < len; i++) {
  62604. children[i].computeAbsoluteTransforms();
  62605. }
  62606. };
  62607. Bone.prototype._syncScaleVector = function () {
  62608. var lm = this.getLocalMatrix();
  62609. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  62610. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  62611. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  62612. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  62613. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  62614. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  62615. this._scaleVector.x = xs * Math.sqrt(xsq);
  62616. this._scaleVector.y = ys * Math.sqrt(ysq);
  62617. this._scaleVector.z = zs * Math.sqrt(zsq);
  62618. if (this._parent) {
  62619. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  62620. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  62621. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  62622. }
  62623. 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);
  62624. };
  62625. /**
  62626. * Get the world direction from an axis that is in the local space of the bone.
  62627. * @param localAxis The local direction that is used to compute the world direction.
  62628. * @param mesh The mesh that this bone is attached to.
  62629. * @returns The world direction
  62630. */
  62631. Bone.prototype.getDirection = function (localAxis, mesh) {
  62632. if (mesh === void 0) { mesh = null; }
  62633. var result = BABYLON.Vector3.Zero();
  62634. this.getDirectionToRef(localAxis, mesh, result);
  62635. return result;
  62636. };
  62637. /**
  62638. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  62639. * @param localAxis The local direction that is used to compute the world direction.
  62640. * @param mesh The mesh that this bone is attached to.
  62641. * @param result The vector3 that the world direction will be copied to.
  62642. */
  62643. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  62644. if (mesh === void 0) { mesh = null; }
  62645. var wm = null;
  62646. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  62647. if (mesh) {
  62648. wm = mesh.getWorldMatrix();
  62649. }
  62650. this._skeleton.computeAbsoluteTransforms();
  62651. var mat = Bone._tmpMats[0];
  62652. mat.copyFrom(this.getAbsoluteTransform());
  62653. if (mesh && wm) {
  62654. mat.multiplyToRef(wm, mat);
  62655. }
  62656. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  62657. result.normalize();
  62658. };
  62659. /**
  62660. * Get the euler rotation of the bone in local or world space.
  62661. * @param space The space that the rotation should be in.
  62662. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62663. * @returns The euler rotation
  62664. */
  62665. Bone.prototype.getRotation = function (space, mesh) {
  62666. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62667. if (mesh === void 0) { mesh = null; }
  62668. var result = BABYLON.Vector3.Zero();
  62669. this.getRotationToRef(space, mesh, result);
  62670. return result;
  62671. };
  62672. /**
  62673. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  62674. * @param space The space that the rotation should be in.
  62675. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62676. * @param result The vector3 that the rotation should be copied to.
  62677. */
  62678. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  62679. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62680. if (mesh === void 0) { mesh = null; }
  62681. var quat = Bone._tmpQuat;
  62682. this.getRotationQuaternionToRef(space, mesh, quat);
  62683. quat.toEulerAnglesToRef(result);
  62684. };
  62685. /**
  62686. * Get the quaternion rotation of the bone in either local or world space.
  62687. * @param space The space that the rotation should be in.
  62688. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62689. * @returns The quaternion rotation
  62690. */
  62691. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  62692. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62693. if (mesh === void 0) { mesh = null; }
  62694. var result = BABYLON.Quaternion.Identity();
  62695. this.getRotationQuaternionToRef(space, mesh, result);
  62696. return result;
  62697. };
  62698. /**
  62699. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  62700. * @param space The space that the rotation should be in.
  62701. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62702. * @param result The quaternion that the rotation should be copied to.
  62703. */
  62704. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  62705. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62706. if (mesh === void 0) { mesh = null; }
  62707. if (space == BABYLON.Space.LOCAL) {
  62708. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  62709. }
  62710. else {
  62711. var mat = Bone._tmpMats[0];
  62712. var amat = this.getAbsoluteTransform();
  62713. if (mesh) {
  62714. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  62715. }
  62716. else {
  62717. mat.copyFrom(amat);
  62718. }
  62719. mat.m[0] *= this._scalingDeterminant;
  62720. mat.m[1] *= this._scalingDeterminant;
  62721. mat.m[2] *= this._scalingDeterminant;
  62722. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  62723. }
  62724. };
  62725. /**
  62726. * Get the rotation matrix of the bone in local or world space.
  62727. * @param space The space that the rotation should be in.
  62728. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62729. * @returns The rotation matrix
  62730. */
  62731. Bone.prototype.getRotationMatrix = function (space, mesh) {
  62732. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62733. var result = BABYLON.Matrix.Identity();
  62734. this.getRotationMatrixToRef(space, mesh, result);
  62735. return result;
  62736. };
  62737. /**
  62738. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  62739. * @param space The space that the rotation should be in.
  62740. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62741. * @param result The quaternion that the rotation should be copied to.
  62742. */
  62743. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  62744. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62745. if (space == BABYLON.Space.LOCAL) {
  62746. this.getLocalMatrix().getRotationMatrixToRef(result);
  62747. }
  62748. else {
  62749. var mat = Bone._tmpMats[0];
  62750. var amat = this.getAbsoluteTransform();
  62751. if (mesh) {
  62752. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  62753. }
  62754. else {
  62755. mat.copyFrom(amat);
  62756. }
  62757. mat.m[0] *= this._scalingDeterminant;
  62758. mat.m[1] *= this._scalingDeterminant;
  62759. mat.m[2] *= this._scalingDeterminant;
  62760. mat.getRotationMatrixToRef(result);
  62761. }
  62762. };
  62763. /**
  62764. * Get the world position of a point that is in the local space of the bone.
  62765. * @param position The local position
  62766. * @param mesh The mesh that this bone is attached to.
  62767. * @returns The world position
  62768. */
  62769. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  62770. if (mesh === void 0) { mesh = null; }
  62771. var result = BABYLON.Vector3.Zero();
  62772. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  62773. return result;
  62774. };
  62775. /**
  62776. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  62777. * @param position The local position
  62778. * @param mesh The mesh that this bone is attached to.
  62779. * @param result The vector3 that the world position should be copied to.
  62780. */
  62781. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  62782. if (mesh === void 0) { mesh = null; }
  62783. var wm = null;
  62784. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  62785. if (mesh) {
  62786. wm = mesh.getWorldMatrix();
  62787. }
  62788. this._skeleton.computeAbsoluteTransforms();
  62789. var tmat = Bone._tmpMats[0];
  62790. if (mesh && wm) {
  62791. tmat.copyFrom(this.getAbsoluteTransform());
  62792. tmat.multiplyToRef(wm, tmat);
  62793. }
  62794. else {
  62795. tmat = this.getAbsoluteTransform();
  62796. }
  62797. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  62798. };
  62799. /**
  62800. * Get the local position of a point that is in world space.
  62801. * @param position The world position
  62802. * @param mesh The mesh that this bone is attached to.
  62803. * @returns The local position
  62804. */
  62805. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  62806. if (mesh === void 0) { mesh = null; }
  62807. var result = BABYLON.Vector3.Zero();
  62808. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  62809. return result;
  62810. };
  62811. /**
  62812. * Get the local position of a point that is in world space and copy it to the result param.
  62813. * @param position The world position
  62814. * @param mesh The mesh that this bone is attached to.
  62815. * @param result The vector3 that the local position should be copied to.
  62816. */
  62817. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  62818. if (mesh === void 0) { mesh = null; }
  62819. var wm = null;
  62820. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  62821. if (mesh) {
  62822. wm = mesh.getWorldMatrix();
  62823. }
  62824. this._skeleton.computeAbsoluteTransforms();
  62825. var tmat = Bone._tmpMats[0];
  62826. tmat.copyFrom(this.getAbsoluteTransform());
  62827. if (mesh && wm) {
  62828. tmat.multiplyToRef(wm, tmat);
  62829. }
  62830. tmat.invert();
  62831. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  62832. };
  62833. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62834. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  62835. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  62836. return Bone;
  62837. }(BABYLON.Node));
  62838. BABYLON.Bone = Bone;
  62839. })(BABYLON || (BABYLON = {}));
  62840. //# sourceMappingURL=babylon.bone.js.map
  62841. var BABYLON;
  62842. (function (BABYLON) {
  62843. var BoneIKController = /** @class */ (function () {
  62844. function BoneIKController(mesh, bone, options) {
  62845. this.targetPosition = BABYLON.Vector3.Zero();
  62846. this.poleTargetPosition = BABYLON.Vector3.Zero();
  62847. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  62848. this.poleAngle = 0;
  62849. this.slerpAmount = 1;
  62850. this._bone1Quat = BABYLON.Quaternion.Identity();
  62851. this._bone1Mat = BABYLON.Matrix.Identity();
  62852. this._bone2Ang = Math.PI;
  62853. this._maxAngle = Math.PI;
  62854. this._rightHandedSystem = false;
  62855. this._bendAxis = BABYLON.Vector3.Right();
  62856. this._slerping = false;
  62857. this._adjustRoll = 0;
  62858. this._bone2 = bone;
  62859. this._bone1 = bone.getParent();
  62860. if (!this._bone1) {
  62861. return;
  62862. }
  62863. this.mesh = mesh;
  62864. var bonePos = bone.getPosition();
  62865. if (bone.getAbsoluteTransform().determinant() > 0) {
  62866. this._rightHandedSystem = true;
  62867. this._bendAxis.x = 0;
  62868. this._bendAxis.y = 0;
  62869. this._bendAxis.z = -1;
  62870. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  62871. this._adjustRoll = Math.PI * .5;
  62872. this._bendAxis.z = 1;
  62873. }
  62874. }
  62875. if (this._bone1.length) {
  62876. var boneScale1 = this._bone1.getScale();
  62877. var boneScale2 = this._bone2.getScale();
  62878. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  62879. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  62880. }
  62881. else if (this._bone1.children[0]) {
  62882. mesh.computeWorldMatrix(true);
  62883. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  62884. var pos2 = this._bone2.getAbsolutePosition(mesh);
  62885. var pos3 = this._bone1.getAbsolutePosition(mesh);
  62886. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  62887. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  62888. }
  62889. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  62890. this.maxAngle = Math.PI;
  62891. if (options) {
  62892. if (options.targetMesh) {
  62893. this.targetMesh = options.targetMesh;
  62894. this.targetMesh.computeWorldMatrix(true);
  62895. }
  62896. if (options.poleTargetMesh) {
  62897. this.poleTargetMesh = options.poleTargetMesh;
  62898. this.poleTargetMesh.computeWorldMatrix(true);
  62899. }
  62900. else if (options.poleTargetBone) {
  62901. this.poleTargetBone = options.poleTargetBone;
  62902. }
  62903. else if (this._bone1.getParent()) {
  62904. this.poleTargetBone = this._bone1.getParent();
  62905. }
  62906. if (options.poleTargetLocalOffset) {
  62907. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  62908. }
  62909. if (options.poleAngle) {
  62910. this.poleAngle = options.poleAngle;
  62911. }
  62912. if (options.bendAxis) {
  62913. this._bendAxis.copyFrom(options.bendAxis);
  62914. }
  62915. if (options.maxAngle) {
  62916. this.maxAngle = options.maxAngle;
  62917. }
  62918. if (options.slerpAmount) {
  62919. this.slerpAmount = options.slerpAmount;
  62920. }
  62921. }
  62922. }
  62923. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  62924. get: function () {
  62925. return this._maxAngle;
  62926. },
  62927. set: function (value) {
  62928. this._setMaxAngle(value);
  62929. },
  62930. enumerable: true,
  62931. configurable: true
  62932. });
  62933. BoneIKController.prototype._setMaxAngle = function (ang) {
  62934. if (ang < 0) {
  62935. ang = 0;
  62936. }
  62937. if (ang > Math.PI || ang == undefined) {
  62938. ang = Math.PI;
  62939. }
  62940. this._maxAngle = ang;
  62941. var a = this._bone1Length;
  62942. var b = this._bone2Length;
  62943. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  62944. };
  62945. BoneIKController.prototype.update = function () {
  62946. var bone1 = this._bone1;
  62947. if (!bone1) {
  62948. return;
  62949. }
  62950. var target = this.targetPosition;
  62951. var poleTarget = this.poleTargetPosition;
  62952. var mat1 = BoneIKController._tmpMats[0];
  62953. var mat2 = BoneIKController._tmpMats[1];
  62954. if (this.targetMesh) {
  62955. target.copyFrom(this.targetMesh.getAbsolutePosition());
  62956. }
  62957. if (this.poleTargetBone) {
  62958. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  62959. }
  62960. else if (this.poleTargetMesh) {
  62961. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  62962. }
  62963. var bonePos = BoneIKController._tmpVecs[0];
  62964. var zaxis = BoneIKController._tmpVecs[1];
  62965. var xaxis = BoneIKController._tmpVecs[2];
  62966. var yaxis = BoneIKController._tmpVecs[3];
  62967. var upAxis = BoneIKController._tmpVecs[4];
  62968. var _tmpQuat = BoneIKController._tmpQuat;
  62969. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  62970. poleTarget.subtractToRef(bonePos, upAxis);
  62971. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  62972. upAxis.y = 1;
  62973. }
  62974. else {
  62975. upAxis.normalize();
  62976. }
  62977. target.subtractToRef(bonePos, yaxis);
  62978. yaxis.normalize();
  62979. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  62980. zaxis.normalize();
  62981. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  62982. xaxis.normalize();
  62983. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  62984. var a = this._bone1Length;
  62985. var b = this._bone2Length;
  62986. var c = BABYLON.Vector3.Distance(bonePos, target);
  62987. if (this._maxReach > 0) {
  62988. c = Math.min(this._maxReach, c);
  62989. }
  62990. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  62991. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  62992. if (acosa > 1) {
  62993. acosa = 1;
  62994. }
  62995. if (acosb > 1) {
  62996. acosb = 1;
  62997. }
  62998. if (acosa < -1) {
  62999. acosa = -1;
  63000. }
  63001. if (acosb < -1) {
  63002. acosb = -1;
  63003. }
  63004. var angA = Math.acos(acosa);
  63005. var angB = Math.acos(acosb);
  63006. var angC = -angA - angB;
  63007. if (this._rightHandedSystem) {
  63008. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  63009. mat2.multiplyToRef(mat1, mat1);
  63010. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  63011. mat2.multiplyToRef(mat1, mat1);
  63012. }
  63013. else {
  63014. var _tmpVec = BoneIKController._tmpVecs[5];
  63015. _tmpVec.copyFrom(this._bendAxis);
  63016. _tmpVec.x *= -1;
  63017. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  63018. mat2.multiplyToRef(mat1, mat1);
  63019. }
  63020. if (this.poleAngle) {
  63021. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  63022. mat1.multiplyToRef(mat2, mat1);
  63023. }
  63024. if (this._bone1) {
  63025. if (this.slerpAmount < 1) {
  63026. if (!this._slerping) {
  63027. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  63028. }
  63029. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  63030. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  63031. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  63032. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  63033. this._slerping = true;
  63034. }
  63035. else {
  63036. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  63037. this._bone1Mat.copyFrom(mat1);
  63038. this._slerping = false;
  63039. }
  63040. }
  63041. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  63042. this._bone2Ang = angC;
  63043. };
  63044. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63045. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  63046. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  63047. return BoneIKController;
  63048. }());
  63049. BABYLON.BoneIKController = BoneIKController;
  63050. })(BABYLON || (BABYLON = {}));
  63051. //# sourceMappingURL=babylon.boneIKController.js.map
  63052. var BABYLON;
  63053. (function (BABYLON) {
  63054. var BoneLookController = /** @class */ (function () {
  63055. /**
  63056. * Create a BoneLookController
  63057. * @param mesh the mesh that the bone belongs to
  63058. * @param bone the bone that will be looking to the target
  63059. * @param target the target Vector3 to look at
  63060. * @param settings optional settings:
  63061. * - maxYaw: the maximum angle the bone will yaw to
  63062. * - minYaw: the minimum angle the bone will yaw to
  63063. * - maxPitch: the maximum angle the bone will pitch to
  63064. * - minPitch: the minimum angle the bone will yaw to
  63065. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  63066. * - upAxis: the up axis of the coordinate system
  63067. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  63068. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  63069. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  63070. * - adjustYaw: used to make an adjustment to the yaw of the bone
  63071. * - adjustPitch: used to make an adjustment to the pitch of the bone
  63072. * - adjustRoll: used to make an adjustment to the roll of the bone
  63073. **/
  63074. function BoneLookController(mesh, bone, target, options) {
  63075. /**
  63076. * The up axis of the coordinate system that is used when the bone is rotated.
  63077. */
  63078. this.upAxis = BABYLON.Vector3.Up();
  63079. /**
  63080. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  63081. */
  63082. this.upAxisSpace = BABYLON.Space.LOCAL;
  63083. /**
  63084. * Used to make an adjustment to the yaw of the bone.
  63085. */
  63086. this.adjustYaw = 0;
  63087. /**
  63088. * Used to make an adjustment to the pitch of the bone.
  63089. */
  63090. this.adjustPitch = 0;
  63091. /**
  63092. * Used to make an adjustment to the roll of the bone.
  63093. */
  63094. this.adjustRoll = 0;
  63095. /**
  63096. * 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).
  63097. */
  63098. this.slerpAmount = 1;
  63099. this._boneQuat = BABYLON.Quaternion.Identity();
  63100. this._slerping = false;
  63101. this._firstFrameSkipped = false;
  63102. this._fowardAxis = BABYLON.Vector3.Forward();
  63103. this.mesh = mesh;
  63104. this.bone = bone;
  63105. this.target = target;
  63106. if (options) {
  63107. if (options.adjustYaw) {
  63108. this.adjustYaw = options.adjustYaw;
  63109. }
  63110. if (options.adjustPitch) {
  63111. this.adjustPitch = options.adjustPitch;
  63112. }
  63113. if (options.adjustRoll) {
  63114. this.adjustRoll = options.adjustRoll;
  63115. }
  63116. if (options.maxYaw != null) {
  63117. this.maxYaw = options.maxYaw;
  63118. }
  63119. else {
  63120. this.maxYaw = Math.PI;
  63121. }
  63122. if (options.minYaw != null) {
  63123. this.minYaw = options.minYaw;
  63124. }
  63125. else {
  63126. this.minYaw = -Math.PI;
  63127. }
  63128. if (options.maxPitch != null) {
  63129. this.maxPitch = options.maxPitch;
  63130. }
  63131. else {
  63132. this.maxPitch = Math.PI;
  63133. }
  63134. if (options.minPitch != null) {
  63135. this.minPitch = options.minPitch;
  63136. }
  63137. else {
  63138. this.minPitch = -Math.PI;
  63139. }
  63140. if (options.slerpAmount != null) {
  63141. this.slerpAmount = options.slerpAmount;
  63142. }
  63143. if (options.upAxis != null) {
  63144. this.upAxis = options.upAxis;
  63145. }
  63146. if (options.upAxisSpace != null) {
  63147. this.upAxisSpace = options.upAxisSpace;
  63148. }
  63149. if (options.yawAxis != null || options.pitchAxis != null) {
  63150. var newYawAxis = BABYLON.Axis.Y;
  63151. var newPitchAxis = BABYLON.Axis.X;
  63152. if (options.yawAxis != null) {
  63153. newYawAxis = options.yawAxis.clone();
  63154. newYawAxis.normalize();
  63155. }
  63156. if (options.pitchAxis != null) {
  63157. newPitchAxis = options.pitchAxis.clone();
  63158. newPitchAxis.normalize();
  63159. }
  63160. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  63161. this._transformYawPitch = BABYLON.Matrix.Identity();
  63162. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  63163. this._transformYawPitchInv = this._transformYawPitch.clone();
  63164. this._transformYawPitch.invert();
  63165. }
  63166. }
  63167. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  63168. this.upAxisSpace = BABYLON.Space.LOCAL;
  63169. }
  63170. }
  63171. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  63172. /**
  63173. * Get/set the minimum yaw angle that the bone can look to.
  63174. */
  63175. get: function () {
  63176. return this._minYaw;
  63177. },
  63178. set: function (value) {
  63179. this._minYaw = value;
  63180. this._minYawSin = Math.sin(value);
  63181. this._minYawCos = Math.cos(value);
  63182. if (this._maxYaw != null) {
  63183. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  63184. this._yawRange = this._maxYaw - this._minYaw;
  63185. }
  63186. },
  63187. enumerable: true,
  63188. configurable: true
  63189. });
  63190. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  63191. /**
  63192. * Get/set the maximum yaw angle that the bone can look to.
  63193. */
  63194. get: function () {
  63195. return this._maxYaw;
  63196. },
  63197. set: function (value) {
  63198. this._maxYaw = value;
  63199. this._maxYawSin = Math.sin(value);
  63200. this._maxYawCos = Math.cos(value);
  63201. if (this._minYaw != null) {
  63202. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  63203. this._yawRange = this._maxYaw - this._minYaw;
  63204. }
  63205. },
  63206. enumerable: true,
  63207. configurable: true
  63208. });
  63209. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  63210. /**
  63211. * Get/set the minimum pitch angle that the bone can look to.
  63212. */
  63213. get: function () {
  63214. return this._minPitch;
  63215. },
  63216. set: function (value) {
  63217. this._minPitch = value;
  63218. this._minPitchTan = Math.tan(value);
  63219. },
  63220. enumerable: true,
  63221. configurable: true
  63222. });
  63223. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  63224. /**
  63225. * Get/set the maximum pitch angle that the bone can look to.
  63226. */
  63227. get: function () {
  63228. return this._maxPitch;
  63229. },
  63230. set: function (value) {
  63231. this._maxPitch = value;
  63232. this._maxPitchTan = Math.tan(value);
  63233. },
  63234. enumerable: true,
  63235. configurable: true
  63236. });
  63237. /**
  63238. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  63239. */
  63240. BoneLookController.prototype.update = function () {
  63241. //skip the first frame when slerping so that the mesh rotation is correct
  63242. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  63243. this._firstFrameSkipped = true;
  63244. return;
  63245. }
  63246. var bone = this.bone;
  63247. var bonePos = BoneLookController._tmpVecs[0];
  63248. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  63249. var target = this.target;
  63250. var _tmpMat1 = BoneLookController._tmpMats[0];
  63251. var _tmpMat2 = BoneLookController._tmpMats[1];
  63252. var mesh = this.mesh;
  63253. var parentBone = bone.getParent();
  63254. var upAxis = BoneLookController._tmpVecs[1];
  63255. upAxis.copyFrom(this.upAxis);
  63256. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  63257. if (this._transformYawPitch) {
  63258. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  63259. }
  63260. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  63261. }
  63262. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  63263. mesh.getDirectionToRef(upAxis, upAxis);
  63264. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  63265. upAxis.normalize();
  63266. }
  63267. }
  63268. var checkYaw = false;
  63269. var checkPitch = false;
  63270. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  63271. checkYaw = true;
  63272. }
  63273. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  63274. checkPitch = true;
  63275. }
  63276. if (checkYaw || checkPitch) {
  63277. var spaceMat = BoneLookController._tmpMats[2];
  63278. var spaceMatInv = BoneLookController._tmpMats[3];
  63279. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  63280. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  63281. }
  63282. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  63283. spaceMat.copyFrom(mesh.getWorldMatrix());
  63284. }
  63285. else {
  63286. var forwardAxis = BoneLookController._tmpVecs[2];
  63287. forwardAxis.copyFrom(this._fowardAxis);
  63288. if (this._transformYawPitch) {
  63289. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  63290. }
  63291. if (parentBone) {
  63292. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  63293. }
  63294. else {
  63295. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  63296. }
  63297. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  63298. rightAxis.normalize();
  63299. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  63300. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  63301. }
  63302. spaceMat.invertToRef(spaceMatInv);
  63303. var xzlen = null;
  63304. if (checkPitch) {
  63305. var localTarget = BoneLookController._tmpVecs[3];
  63306. target.subtractToRef(bonePos, localTarget);
  63307. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  63308. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  63309. var pitch = Math.atan2(localTarget.y, xzlen);
  63310. var newPitch = pitch;
  63311. if (pitch > this._maxPitch) {
  63312. localTarget.y = this._maxPitchTan * xzlen;
  63313. newPitch = this._maxPitch;
  63314. }
  63315. else if (pitch < this._minPitch) {
  63316. localTarget.y = this._minPitchTan * xzlen;
  63317. newPitch = this._minPitch;
  63318. }
  63319. if (pitch != newPitch) {
  63320. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  63321. localTarget.addInPlace(bonePos);
  63322. target = localTarget;
  63323. }
  63324. }
  63325. if (checkYaw) {
  63326. var localTarget = BoneLookController._tmpVecs[4];
  63327. target.subtractToRef(bonePos, localTarget);
  63328. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  63329. var yaw = Math.atan2(localTarget.x, localTarget.z);
  63330. var newYaw = yaw;
  63331. if (yaw > this._maxYaw || yaw < this._minYaw) {
  63332. if (xzlen == null) {
  63333. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  63334. }
  63335. if (this._yawRange > Math.PI) {
  63336. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  63337. localTarget.z = this._maxYawCos * xzlen;
  63338. localTarget.x = this._maxYawSin * xzlen;
  63339. newYaw = this._maxYaw;
  63340. }
  63341. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  63342. localTarget.z = this._minYawCos * xzlen;
  63343. localTarget.x = this._minYawSin * xzlen;
  63344. newYaw = this._minYaw;
  63345. }
  63346. }
  63347. else {
  63348. if (yaw > this._maxYaw) {
  63349. localTarget.z = this._maxYawCos * xzlen;
  63350. localTarget.x = this._maxYawSin * xzlen;
  63351. newYaw = this._maxYaw;
  63352. }
  63353. else if (yaw < this._minYaw) {
  63354. localTarget.z = this._minYawCos * xzlen;
  63355. localTarget.x = this._minYawSin * xzlen;
  63356. newYaw = this._minYaw;
  63357. }
  63358. }
  63359. }
  63360. if (this._slerping && this._yawRange > Math.PI) {
  63361. //are we going to be crossing into the min/max region?
  63362. var boneFwd = BoneLookController._tmpVecs[8];
  63363. boneFwd.copyFrom(BABYLON.Axis.Z);
  63364. if (this._transformYawPitch) {
  63365. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  63366. }
  63367. var boneRotMat = BoneLookController._tmpMats[4];
  63368. this._boneQuat.toRotationMatrix(boneRotMat);
  63369. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  63370. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  63371. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  63372. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  63373. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  63374. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  63375. if (angBtwTar > angBtwMidYaw) {
  63376. if (xzlen == null) {
  63377. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  63378. }
  63379. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  63380. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  63381. if (angBtwMin < angBtwMax) {
  63382. newYaw = boneYaw + Math.PI * .75;
  63383. localTarget.z = Math.cos(newYaw) * xzlen;
  63384. localTarget.x = Math.sin(newYaw) * xzlen;
  63385. }
  63386. else {
  63387. newYaw = boneYaw - Math.PI * .75;
  63388. localTarget.z = Math.cos(newYaw) * xzlen;
  63389. localTarget.x = Math.sin(newYaw) * xzlen;
  63390. }
  63391. }
  63392. }
  63393. if (yaw != newYaw) {
  63394. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  63395. localTarget.addInPlace(bonePos);
  63396. target = localTarget;
  63397. }
  63398. }
  63399. }
  63400. var zaxis = BoneLookController._tmpVecs[5];
  63401. var xaxis = BoneLookController._tmpVecs[6];
  63402. var yaxis = BoneLookController._tmpVecs[7];
  63403. var _tmpQuat = BoneLookController._tmpQuat;
  63404. target.subtractToRef(bonePos, zaxis);
  63405. zaxis.normalize();
  63406. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  63407. xaxis.normalize();
  63408. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  63409. yaxis.normalize();
  63410. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  63411. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  63412. return;
  63413. }
  63414. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  63415. return;
  63416. }
  63417. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  63418. return;
  63419. }
  63420. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  63421. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  63422. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  63423. }
  63424. if (this.slerpAmount < 1) {
  63425. if (!this._slerping) {
  63426. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  63427. }
  63428. if (this._transformYawPitch) {
  63429. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  63430. }
  63431. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  63432. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  63433. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  63434. this._slerping = true;
  63435. }
  63436. else {
  63437. if (this._transformYawPitch) {
  63438. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  63439. }
  63440. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  63441. this._slerping = false;
  63442. }
  63443. };
  63444. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  63445. var angDiff = ang2 - ang1;
  63446. angDiff %= Math.PI * 2;
  63447. if (angDiff > Math.PI) {
  63448. angDiff -= Math.PI * 2;
  63449. }
  63450. else if (angDiff < -Math.PI) {
  63451. angDiff += Math.PI * 2;
  63452. }
  63453. return angDiff;
  63454. };
  63455. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  63456. ang1 %= (2 * Math.PI);
  63457. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  63458. ang2 %= (2 * Math.PI);
  63459. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  63460. var ab = 0;
  63461. if (ang1 < ang2) {
  63462. ab = ang2 - ang1;
  63463. }
  63464. else {
  63465. ab = ang1 - ang2;
  63466. }
  63467. if (ab > Math.PI) {
  63468. ab = Math.PI * 2 - ab;
  63469. }
  63470. return ab;
  63471. };
  63472. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  63473. ang %= (2 * Math.PI);
  63474. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  63475. ang1 %= (2 * Math.PI);
  63476. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  63477. ang2 %= (2 * Math.PI);
  63478. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  63479. if (ang1 < ang2) {
  63480. if (ang > ang1 && ang < ang2) {
  63481. return true;
  63482. }
  63483. }
  63484. else {
  63485. if (ang > ang2 && ang < ang1) {
  63486. return true;
  63487. }
  63488. }
  63489. return false;
  63490. };
  63491. 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()];
  63492. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  63493. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  63494. return BoneLookController;
  63495. }());
  63496. BABYLON.BoneLookController = BoneLookController;
  63497. })(BABYLON || (BABYLON = {}));
  63498. //# sourceMappingURL=babylon.boneLookController.js.map
  63499. var BABYLON;
  63500. (function (BABYLON) {
  63501. var Skeleton = /** @class */ (function () {
  63502. function Skeleton(name, id, scene) {
  63503. this.name = name;
  63504. this.id = id;
  63505. this.bones = new Array();
  63506. this.needInitialSkinMatrix = false;
  63507. this._isDirty = true;
  63508. this._meshesWithPoseMatrix = new Array();
  63509. this._identity = BABYLON.Matrix.Identity();
  63510. this._ranges = {};
  63511. this._lastAbsoluteTransformsUpdateId = -1;
  63512. // Events
  63513. /**
  63514. * An event triggered before computing the skeleton's matrices
  63515. * @type {BABYLON.Observable}
  63516. */
  63517. this.onBeforeComputeObservable = new BABYLON.Observable();
  63518. this.bones = [];
  63519. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  63520. scene.skeletons.push(this);
  63521. //make sure it will recalculate the matrix next time prepare is called.
  63522. this._isDirty = true;
  63523. }
  63524. // Members
  63525. Skeleton.prototype.getTransformMatrices = function (mesh) {
  63526. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  63527. return mesh._bonesTransformMatrices;
  63528. }
  63529. if (!this._transformMatrices) {
  63530. this.prepare();
  63531. }
  63532. return this._transformMatrices;
  63533. };
  63534. Skeleton.prototype.getScene = function () {
  63535. return this._scene;
  63536. };
  63537. // Methods
  63538. /**
  63539. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  63540. */
  63541. Skeleton.prototype.toString = function (fullDetails) {
  63542. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  63543. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  63544. if (fullDetails) {
  63545. ret += ", Ranges: {";
  63546. var first = true;
  63547. for (var name_1 in this._ranges) {
  63548. if (first) {
  63549. ret += ", ";
  63550. first = false;
  63551. }
  63552. ret += name_1;
  63553. }
  63554. ret += "}";
  63555. }
  63556. return ret;
  63557. };
  63558. /**
  63559. * Get bone's index searching by name
  63560. * @param {string} name is bone's name to search for
  63561. * @return {number} Indice of the bone. Returns -1 if not found
  63562. */
  63563. Skeleton.prototype.getBoneIndexByName = function (name) {
  63564. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  63565. if (this.bones[boneIndex].name === name) {
  63566. return boneIndex;
  63567. }
  63568. }
  63569. return -1;
  63570. };
  63571. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  63572. // check name not already in use
  63573. if (!this._ranges[name]) {
  63574. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  63575. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  63576. if (this.bones[i].animations[0]) {
  63577. this.bones[i].animations[0].createRange(name, from, to);
  63578. }
  63579. }
  63580. }
  63581. };
  63582. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  63583. if (deleteFrames === void 0) { deleteFrames = true; }
  63584. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  63585. if (this.bones[i].animations[0]) {
  63586. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  63587. }
  63588. }
  63589. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  63590. };
  63591. Skeleton.prototype.getAnimationRange = function (name) {
  63592. return this._ranges[name];
  63593. };
  63594. /**
  63595. * Returns as an Array, all AnimationRanges defined on this skeleton
  63596. */
  63597. Skeleton.prototype.getAnimationRanges = function () {
  63598. var animationRanges = [];
  63599. var name;
  63600. var i = 0;
  63601. for (name in this._ranges) {
  63602. animationRanges[i] = this._ranges[name];
  63603. i++;
  63604. }
  63605. return animationRanges;
  63606. };
  63607. /**
  63608. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  63609. */
  63610. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  63611. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  63612. if (this._ranges[name] || !source.getAnimationRange(name)) {
  63613. return false;
  63614. }
  63615. var ret = true;
  63616. var frameOffset = this._getHighestAnimationFrame() + 1;
  63617. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  63618. var boneDict = {};
  63619. var sourceBones = source.bones;
  63620. var nBones;
  63621. var i;
  63622. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  63623. boneDict[sourceBones[i].name] = sourceBones[i];
  63624. }
  63625. if (this.bones.length !== sourceBones.length) {
  63626. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  63627. ret = false;
  63628. }
  63629. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  63630. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  63631. var boneName = this.bones[i].name;
  63632. var sourceBone = boneDict[boneName];
  63633. if (sourceBone) {
  63634. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  63635. }
  63636. else {
  63637. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  63638. ret = false;
  63639. }
  63640. }
  63641. // do not call createAnimationRange(), since it also is done to bones, which was already done
  63642. var range = source.getAnimationRange(name);
  63643. if (range) {
  63644. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  63645. }
  63646. return ret;
  63647. };
  63648. Skeleton.prototype.returnToRest = function () {
  63649. for (var index = 0; index < this.bones.length; index++) {
  63650. this.bones[index].returnToRest();
  63651. }
  63652. };
  63653. Skeleton.prototype._getHighestAnimationFrame = function () {
  63654. var ret = 0;
  63655. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  63656. if (this.bones[i].animations[0]) {
  63657. var highest = this.bones[i].animations[0].getHighestFrame();
  63658. if (ret < highest) {
  63659. ret = highest;
  63660. }
  63661. }
  63662. }
  63663. return ret;
  63664. };
  63665. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  63666. var range = this.getAnimationRange(name);
  63667. if (!range) {
  63668. return null;
  63669. }
  63670. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  63671. };
  63672. Skeleton.prototype._markAsDirty = function () {
  63673. this._isDirty = true;
  63674. };
  63675. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  63676. this._meshesWithPoseMatrix.push(mesh);
  63677. };
  63678. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  63679. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  63680. if (index > -1) {
  63681. this._meshesWithPoseMatrix.splice(index, 1);
  63682. }
  63683. };
  63684. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  63685. this.onBeforeComputeObservable.notifyObservers(this);
  63686. for (var index = 0; index < this.bones.length; index++) {
  63687. var bone = this.bones[index];
  63688. var parentBone = bone.getParent();
  63689. if (parentBone) {
  63690. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  63691. }
  63692. else {
  63693. if (initialSkinMatrix) {
  63694. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  63695. }
  63696. else {
  63697. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  63698. }
  63699. }
  63700. if (bone._index !== -1) {
  63701. var mappedIndex = bone._index === null ? index : bone._index;
  63702. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  63703. }
  63704. }
  63705. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  63706. };
  63707. Skeleton.prototype.prepare = function () {
  63708. if (!this._isDirty) {
  63709. return;
  63710. }
  63711. if (this.needInitialSkinMatrix) {
  63712. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  63713. var mesh = this._meshesWithPoseMatrix[index];
  63714. var poseMatrix = mesh.getPoseMatrix();
  63715. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  63716. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  63717. }
  63718. if (this._synchronizedWithMesh !== mesh) {
  63719. this._synchronizedWithMesh = mesh;
  63720. // Prepare bones
  63721. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  63722. var bone = this.bones[boneIndex];
  63723. if (!bone.getParent()) {
  63724. var matrix = bone.getBaseMatrix();
  63725. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  63726. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  63727. }
  63728. }
  63729. }
  63730. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  63731. }
  63732. }
  63733. else {
  63734. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  63735. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  63736. }
  63737. this._computeTransformMatrices(this._transformMatrices, null);
  63738. }
  63739. this._isDirty = false;
  63740. this._scene._activeBones.addCount(this.bones.length, false);
  63741. };
  63742. Skeleton.prototype.getAnimatables = function () {
  63743. if (!this._animatables || this._animatables.length !== this.bones.length) {
  63744. this._animatables = [];
  63745. for (var index = 0; index < this.bones.length; index++) {
  63746. this._animatables.push(this.bones[index]);
  63747. }
  63748. }
  63749. return this._animatables;
  63750. };
  63751. Skeleton.prototype.clone = function (name, id) {
  63752. var result = new Skeleton(name, id || name, this._scene);
  63753. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  63754. for (var index = 0; index < this.bones.length; index++) {
  63755. var source = this.bones[index];
  63756. var parentBone = null;
  63757. var parent_1 = source.getParent();
  63758. if (parent_1) {
  63759. var parentIndex = this.bones.indexOf(parent_1);
  63760. parentBone = result.bones[parentIndex];
  63761. }
  63762. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  63763. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  63764. }
  63765. if (this._ranges) {
  63766. result._ranges = {};
  63767. for (var rangeName in this._ranges) {
  63768. var range = this._ranges[rangeName];
  63769. if (range) {
  63770. result._ranges[rangeName] = range.clone();
  63771. }
  63772. }
  63773. }
  63774. this._isDirty = true;
  63775. return result;
  63776. };
  63777. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  63778. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  63779. this.bones.forEach(function (bone) {
  63780. bone.animations.forEach(function (animation) {
  63781. animation.enableBlending = true;
  63782. animation.blendingSpeed = blendingSpeed;
  63783. });
  63784. });
  63785. };
  63786. Skeleton.prototype.dispose = function () {
  63787. this._meshesWithPoseMatrix = [];
  63788. // Animations
  63789. this.getScene().stopAnimation(this);
  63790. // Remove from scene
  63791. this.getScene().removeSkeleton(this);
  63792. };
  63793. Skeleton.prototype.serialize = function () {
  63794. var serializationObject = {};
  63795. serializationObject.name = this.name;
  63796. serializationObject.id = this.id;
  63797. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  63798. serializationObject.bones = [];
  63799. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  63800. for (var index = 0; index < this.bones.length; index++) {
  63801. var bone = this.bones[index];
  63802. var parent_2 = bone.getParent();
  63803. var serializedBone = {
  63804. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  63805. name: bone.name,
  63806. matrix: bone.getBaseMatrix().toArray(),
  63807. rest: bone.getRestPose().toArray()
  63808. };
  63809. serializationObject.bones.push(serializedBone);
  63810. if (bone.length) {
  63811. serializedBone.length = bone.length;
  63812. }
  63813. if (bone.animations && bone.animations.length > 0) {
  63814. serializedBone.animation = bone.animations[0].serialize();
  63815. }
  63816. serializationObject.ranges = [];
  63817. for (var name in this._ranges) {
  63818. var source = this._ranges[name];
  63819. if (!source) {
  63820. continue;
  63821. }
  63822. var range = {};
  63823. range.name = name;
  63824. range.from = source.from;
  63825. range.to = source.to;
  63826. serializationObject.ranges.push(range);
  63827. }
  63828. }
  63829. return serializationObject;
  63830. };
  63831. Skeleton.Parse = function (parsedSkeleton, scene) {
  63832. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  63833. if (parsedSkeleton.dimensionsAtRest) {
  63834. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  63835. }
  63836. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  63837. var index;
  63838. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  63839. var parsedBone = parsedSkeleton.bones[index];
  63840. var parentBone = null;
  63841. if (parsedBone.parentBoneIndex > -1) {
  63842. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  63843. }
  63844. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  63845. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  63846. if (parsedBone.length) {
  63847. bone.length = parsedBone.length;
  63848. }
  63849. if (parsedBone.animation) {
  63850. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  63851. }
  63852. }
  63853. // placed after bones, so createAnimationRange can cascade down
  63854. if (parsedSkeleton.ranges) {
  63855. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  63856. var data = parsedSkeleton.ranges[index];
  63857. skeleton.createAnimationRange(data.name, data.from, data.to);
  63858. }
  63859. }
  63860. return skeleton;
  63861. };
  63862. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  63863. if (forceUpdate === void 0) { forceUpdate = false; }
  63864. var renderId = this._scene.getRenderId();
  63865. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  63866. this.bones[0].computeAbsoluteTransforms();
  63867. this._lastAbsoluteTransformsUpdateId = renderId;
  63868. }
  63869. };
  63870. Skeleton.prototype.getPoseMatrix = function () {
  63871. var poseMatrix = null;
  63872. if (this._meshesWithPoseMatrix.length > 0) {
  63873. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  63874. }
  63875. return poseMatrix;
  63876. };
  63877. Skeleton.prototype.sortBones = function () {
  63878. var bones = new Array();
  63879. var visited = new Array(this.bones.length);
  63880. for (var index = 0; index < this.bones.length; index++) {
  63881. this._sortBones(index, bones, visited);
  63882. }
  63883. this.bones = bones;
  63884. };
  63885. Skeleton.prototype._sortBones = function (index, bones, visited) {
  63886. if (visited[index]) {
  63887. return;
  63888. }
  63889. visited[index] = true;
  63890. var bone = this.bones[index];
  63891. if (bone._index === undefined) {
  63892. bone._index = index;
  63893. }
  63894. var parentBone = bone.getParent();
  63895. if (parentBone) {
  63896. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  63897. }
  63898. bones.push(bone);
  63899. };
  63900. return Skeleton;
  63901. }());
  63902. BABYLON.Skeleton = Skeleton;
  63903. })(BABYLON || (BABYLON = {}));
  63904. //# sourceMappingURL=babylon.skeleton.js.map
  63905. var BABYLON;
  63906. (function (BABYLON) {
  63907. var SphericalPolynomial = /** @class */ (function () {
  63908. function SphericalPolynomial() {
  63909. this.x = BABYLON.Vector3.Zero();
  63910. this.y = BABYLON.Vector3.Zero();
  63911. this.z = BABYLON.Vector3.Zero();
  63912. this.xx = BABYLON.Vector3.Zero();
  63913. this.yy = BABYLON.Vector3.Zero();
  63914. this.zz = BABYLON.Vector3.Zero();
  63915. this.xy = BABYLON.Vector3.Zero();
  63916. this.yz = BABYLON.Vector3.Zero();
  63917. this.zx = BABYLON.Vector3.Zero();
  63918. }
  63919. SphericalPolynomial.prototype.addAmbient = function (color) {
  63920. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  63921. this.xx = this.xx.add(colorVector);
  63922. this.yy = this.yy.add(colorVector);
  63923. this.zz = this.zz.add(colorVector);
  63924. };
  63925. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  63926. var result = new SphericalPolynomial();
  63927. result.x = harmonics.L11.scale(1.02333);
  63928. result.y = harmonics.L1_1.scale(1.02333);
  63929. result.z = harmonics.L10.scale(1.02333);
  63930. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  63931. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  63932. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  63933. result.yz = harmonics.L2_1.scale(0.858086);
  63934. result.zx = harmonics.L21.scale(0.858086);
  63935. result.xy = harmonics.L2_2.scale(0.858086);
  63936. result.scale(1.0 / Math.PI);
  63937. return result;
  63938. };
  63939. SphericalPolynomial.prototype.scale = function (scale) {
  63940. this.x = this.x.scale(scale);
  63941. this.y = this.y.scale(scale);
  63942. this.z = this.z.scale(scale);
  63943. this.xx = this.xx.scale(scale);
  63944. this.yy = this.yy.scale(scale);
  63945. this.zz = this.zz.scale(scale);
  63946. this.yz = this.yz.scale(scale);
  63947. this.zx = this.zx.scale(scale);
  63948. this.xy = this.xy.scale(scale);
  63949. };
  63950. return SphericalPolynomial;
  63951. }());
  63952. BABYLON.SphericalPolynomial = SphericalPolynomial;
  63953. var SphericalHarmonics = /** @class */ (function () {
  63954. function SphericalHarmonics() {
  63955. this.L00 = BABYLON.Vector3.Zero();
  63956. this.L1_1 = BABYLON.Vector3.Zero();
  63957. this.L10 = BABYLON.Vector3.Zero();
  63958. this.L11 = BABYLON.Vector3.Zero();
  63959. this.L2_2 = BABYLON.Vector3.Zero();
  63960. this.L2_1 = BABYLON.Vector3.Zero();
  63961. this.L20 = BABYLON.Vector3.Zero();
  63962. this.L21 = BABYLON.Vector3.Zero();
  63963. this.L22 = BABYLON.Vector3.Zero();
  63964. }
  63965. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  63966. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  63967. var c = colorVector.scale(deltaSolidAngle);
  63968. this.L00 = this.L00.add(c.scale(0.282095));
  63969. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  63970. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  63971. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  63972. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  63973. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  63974. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  63975. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  63976. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  63977. };
  63978. SphericalHarmonics.prototype.scale = function (scale) {
  63979. this.L00 = this.L00.scale(scale);
  63980. this.L1_1 = this.L1_1.scale(scale);
  63981. this.L10 = this.L10.scale(scale);
  63982. this.L11 = this.L11.scale(scale);
  63983. this.L2_2 = this.L2_2.scale(scale);
  63984. this.L2_1 = this.L2_1.scale(scale);
  63985. this.L20 = this.L20.scale(scale);
  63986. this.L21 = this.L21.scale(scale);
  63987. this.L22 = this.L22.scale(scale);
  63988. };
  63989. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  63990. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  63991. //
  63992. // E_lm = A_l * L_lm
  63993. //
  63994. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  63995. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  63996. // the scaling factors are given in equation 9.
  63997. // Constant (Band 0)
  63998. this.L00 = this.L00.scale(3.141593);
  63999. // Linear (Band 1)
  64000. this.L1_1 = this.L1_1.scale(2.094395);
  64001. this.L10 = this.L10.scale(2.094395);
  64002. this.L11 = this.L11.scale(2.094395);
  64003. // Quadratic (Band 2)
  64004. this.L2_2 = this.L2_2.scale(0.785398);
  64005. this.L2_1 = this.L2_1.scale(0.785398);
  64006. this.L20 = this.L20.scale(0.785398);
  64007. this.L21 = this.L21.scale(0.785398);
  64008. this.L22 = this.L22.scale(0.785398);
  64009. };
  64010. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  64011. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  64012. // L = (1/pi) * E * rho
  64013. //
  64014. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  64015. this.scale(1.0 / Math.PI);
  64016. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  64017. // (The pixel shader must apply albedo after texture fetches, etc).
  64018. };
  64019. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  64020. var result = new SphericalHarmonics();
  64021. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  64022. result.L1_1 = polynomial.y.scale(0.977204);
  64023. result.L10 = polynomial.z.scale(0.977204);
  64024. result.L11 = polynomial.x.scale(0.977204);
  64025. result.L2_2 = polynomial.xy.scale(1.16538);
  64026. result.L2_1 = polynomial.yz.scale(1.16538);
  64027. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  64028. result.L21 = polynomial.zx.scale(1.16538);
  64029. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  64030. result.scale(Math.PI);
  64031. return result;
  64032. };
  64033. return SphericalHarmonics;
  64034. }());
  64035. BABYLON.SphericalHarmonics = SphericalHarmonics;
  64036. })(BABYLON || (BABYLON = {}));
  64037. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  64038. var BABYLON;
  64039. (function (BABYLON) {
  64040. var Internals;
  64041. (function (Internals) {
  64042. var FileFaceOrientation = /** @class */ (function () {
  64043. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  64044. this.name = name;
  64045. this.worldAxisForNormal = worldAxisForNormal;
  64046. this.worldAxisForFileX = worldAxisForFileX;
  64047. this.worldAxisForFileY = worldAxisForFileY;
  64048. }
  64049. return FileFaceOrientation;
  64050. }());
  64051. ;
  64052. /**
  64053. * Helper class dealing with the extraction of spherical polynomial dataArray
  64054. * from a cube map.
  64055. */
  64056. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  64057. function CubeMapToSphericalPolynomialTools() {
  64058. }
  64059. /**
  64060. * Converts a texture to the according Spherical Polynomial data.
  64061. * This extracts the first 3 orders only as they are the only one used in the lighting.
  64062. *
  64063. * @param texture The texture to extract the information from.
  64064. * @return The Spherical Polynomial data.
  64065. */
  64066. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  64067. if (!texture.isCube) {
  64068. // Only supports cube Textures currently.
  64069. return null;
  64070. }
  64071. var size = texture.getSize().width;
  64072. var right = texture.readPixels(0);
  64073. var left = texture.readPixels(1);
  64074. var up;
  64075. var down;
  64076. if (texture.isRenderTarget) {
  64077. up = texture.readPixels(3);
  64078. down = texture.readPixels(2);
  64079. }
  64080. else {
  64081. up = texture.readPixels(2);
  64082. down = texture.readPixels(3);
  64083. }
  64084. var front = texture.readPixels(4);
  64085. var back = texture.readPixels(5);
  64086. var gammaSpace = texture.gammaSpace;
  64087. // Always read as RGBA.
  64088. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  64089. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64090. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  64091. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64092. }
  64093. var cubeInfo = {
  64094. size: size,
  64095. right: right,
  64096. left: left,
  64097. up: up,
  64098. down: down,
  64099. front: front,
  64100. back: back,
  64101. format: format,
  64102. type: type,
  64103. gammaSpace: gammaSpace,
  64104. };
  64105. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  64106. };
  64107. /**
  64108. * Converts a cubemap to the according Spherical Polynomial data.
  64109. * This extracts the first 3 orders only as they are the only one used in the lighting.
  64110. *
  64111. * @param cubeInfo The Cube map to extract the information from.
  64112. * @return The Spherical Polynomial data.
  64113. */
  64114. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  64115. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  64116. var totalSolidAngle = 0.0;
  64117. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  64118. var du = 2.0 / cubeInfo.size;
  64119. var dv = du;
  64120. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  64121. var minUV = du * 0.5 - 1.0;
  64122. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  64123. var fileFace = this.FileFaces[faceIndex];
  64124. var dataArray = cubeInfo[fileFace.name];
  64125. var v = minUV;
  64126. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  64127. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  64128. // Because SP is still linear, so summation is fine in that basis.
  64129. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  64130. for (var y = 0; y < cubeInfo.size; y++) {
  64131. var u = minUV;
  64132. for (var x = 0; x < cubeInfo.size; x++) {
  64133. // World direction (not normalised)
  64134. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  64135. worldDirection.normalize();
  64136. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  64137. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  64138. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  64139. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  64140. // Handle Integer types.
  64141. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  64142. r /= 255;
  64143. g /= 255;
  64144. b /= 255;
  64145. }
  64146. // Handle Gamma space textures.
  64147. if (cubeInfo.gammaSpace) {
  64148. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  64149. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  64150. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  64151. }
  64152. var color = new BABYLON.Color3(r, g, b);
  64153. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  64154. totalSolidAngle += deltaSolidAngle;
  64155. u += du;
  64156. }
  64157. v += dv;
  64158. }
  64159. }
  64160. // Solid angle for entire sphere is 4*pi
  64161. var sphereSolidAngle = 4.0 * Math.PI;
  64162. // Adjust the solid angle to allow for how many faces we processed.
  64163. var facesProcessed = 6.0;
  64164. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  64165. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  64166. // This is needed because the numerical integration over the cube uses a
  64167. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  64168. // and also to compensate for accumulative error due to float precision in the summation.
  64169. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  64170. sphericalHarmonics.scale(correctionFactor);
  64171. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  64172. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  64173. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  64174. };
  64175. CubeMapToSphericalPolynomialTools.FileFaces = [
  64176. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  64177. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  64178. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  64179. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  64180. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  64181. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  64182. ];
  64183. return CubeMapToSphericalPolynomialTools;
  64184. }());
  64185. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  64186. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  64187. })(BABYLON || (BABYLON = {}));
  64188. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  64189. var BABYLON;
  64190. (function (BABYLON) {
  64191. var Internals;
  64192. (function (Internals) {
  64193. /**
  64194. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  64195. */
  64196. var PanoramaToCubeMapTools = /** @class */ (function () {
  64197. function PanoramaToCubeMapTools() {
  64198. }
  64199. /**
  64200. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  64201. *
  64202. * @param float32Array The source data.
  64203. * @param inputWidth The width of the input panorama.
  64204. * @param inputhHeight The height of the input panorama.
  64205. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  64206. * @return The cubemap data
  64207. */
  64208. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  64209. if (!float32Array) {
  64210. throw "ConvertPanoramaToCubemap: input cannot be null";
  64211. }
  64212. if (float32Array.length != inputWidth * inputHeight * 3) {
  64213. throw "ConvertPanoramaToCubemap: input size is wrong";
  64214. }
  64215. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  64216. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  64217. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  64218. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  64219. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  64220. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  64221. return {
  64222. front: textureFront,
  64223. back: textureBack,
  64224. left: textureLeft,
  64225. right: textureRight,
  64226. up: textureUp,
  64227. down: textureDown,
  64228. size: size,
  64229. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  64230. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  64231. gammaSpace: false,
  64232. };
  64233. };
  64234. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  64235. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  64236. var textureArray = new Float32Array(buffer);
  64237. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  64238. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  64239. var dy = 1 / texSize;
  64240. var fy = 0;
  64241. for (var y = 0; y < texSize; y++) {
  64242. var xv1 = faceData[0];
  64243. var xv2 = faceData[2];
  64244. for (var x = 0; x < texSize; x++) {
  64245. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  64246. v.normalize();
  64247. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  64248. // 3 channels per pixels
  64249. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  64250. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  64251. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  64252. xv1 = xv1.add(rotDX1);
  64253. xv2 = xv2.add(rotDX2);
  64254. }
  64255. fy += dy;
  64256. }
  64257. return textureArray;
  64258. };
  64259. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  64260. var theta = Math.atan2(vDir.z, vDir.x);
  64261. var phi = Math.acos(vDir.y);
  64262. while (theta < -Math.PI)
  64263. theta += 2 * Math.PI;
  64264. while (theta > Math.PI)
  64265. theta -= 2 * Math.PI;
  64266. var dx = theta / Math.PI;
  64267. var dy = phi / Math.PI;
  64268. // recenter.
  64269. dx = dx * 0.5 + 0.5;
  64270. var px = Math.round(dx * inputWidth);
  64271. if (px < 0)
  64272. px = 0;
  64273. else if (px >= inputWidth)
  64274. px = inputWidth - 1;
  64275. var py = Math.round(dy * inputHeight);
  64276. if (py < 0)
  64277. py = 0;
  64278. else if (py >= inputHeight)
  64279. py = inputHeight - 1;
  64280. var inputY = (inputHeight - py - 1);
  64281. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  64282. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  64283. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  64284. return {
  64285. r: r,
  64286. g: g,
  64287. b: b
  64288. };
  64289. };
  64290. PanoramaToCubeMapTools.FACE_FRONT = [
  64291. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  64292. new BABYLON.Vector3(1.0, -1.0, -1.0),
  64293. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  64294. new BABYLON.Vector3(1.0, 1.0, -1.0)
  64295. ];
  64296. PanoramaToCubeMapTools.FACE_BACK = [
  64297. new BABYLON.Vector3(1.0, -1.0, 1.0),
  64298. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  64299. new BABYLON.Vector3(1.0, 1.0, 1.0),
  64300. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  64301. ];
  64302. PanoramaToCubeMapTools.FACE_RIGHT = [
  64303. new BABYLON.Vector3(1.0, -1.0, -1.0),
  64304. new BABYLON.Vector3(1.0, -1.0, 1.0),
  64305. new BABYLON.Vector3(1.0, 1.0, -1.0),
  64306. new BABYLON.Vector3(1.0, 1.0, 1.0)
  64307. ];
  64308. PanoramaToCubeMapTools.FACE_LEFT = [
  64309. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  64310. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  64311. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  64312. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  64313. ];
  64314. PanoramaToCubeMapTools.FACE_DOWN = [
  64315. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  64316. new BABYLON.Vector3(1.0, 1.0, -1.0),
  64317. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  64318. new BABYLON.Vector3(1.0, 1.0, 1.0)
  64319. ];
  64320. PanoramaToCubeMapTools.FACE_UP = [
  64321. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  64322. new BABYLON.Vector3(1.0, -1.0, 1.0),
  64323. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  64324. new BABYLON.Vector3(1.0, -1.0, -1.0)
  64325. ];
  64326. return PanoramaToCubeMapTools;
  64327. }());
  64328. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  64329. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  64330. })(BABYLON || (BABYLON = {}));
  64331. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  64332. var BABYLON;
  64333. (function (BABYLON) {
  64334. var Internals;
  64335. (function (Internals) {
  64336. ;
  64337. /**
  64338. * This groups tools to convert HDR texture to native colors array.
  64339. */
  64340. var HDRTools = /** @class */ (function () {
  64341. function HDRTools() {
  64342. }
  64343. HDRTools.Ldexp = function (mantissa, exponent) {
  64344. if (exponent > 1023) {
  64345. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  64346. }
  64347. if (exponent < -1074) {
  64348. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  64349. }
  64350. return mantissa * Math.pow(2, exponent);
  64351. };
  64352. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  64353. if (exponent > 0) {
  64354. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  64355. float32array[index + 0] = red * exponent;
  64356. float32array[index + 1] = green * exponent;
  64357. float32array[index + 2] = blue * exponent;
  64358. }
  64359. else {
  64360. float32array[index + 0] = 0;
  64361. float32array[index + 1] = 0;
  64362. float32array[index + 2] = 0;
  64363. }
  64364. };
  64365. HDRTools.readStringLine = function (uint8array, startIndex) {
  64366. var line = "";
  64367. var character = "";
  64368. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  64369. character = String.fromCharCode(uint8array[i]);
  64370. if (character == "\n") {
  64371. break;
  64372. }
  64373. line += character;
  64374. }
  64375. return line;
  64376. };
  64377. /**
  64378. * Reads header information from an RGBE texture stored in a native array.
  64379. * More information on this format are available here:
  64380. * https://en.wikipedia.org/wiki/RGBE_image_format
  64381. *
  64382. * @param uint8array The binary file stored in native array.
  64383. * @return The header information.
  64384. */
  64385. HDRTools.RGBE_ReadHeader = function (uint8array) {
  64386. var height = 0;
  64387. var width = 0;
  64388. var line = this.readStringLine(uint8array, 0);
  64389. if (line[0] != '#' || line[1] != '?') {
  64390. throw "Bad HDR Format.";
  64391. }
  64392. var endOfHeader = false;
  64393. var findFormat = false;
  64394. var lineIndex = 0;
  64395. do {
  64396. lineIndex += (line.length + 1);
  64397. line = this.readStringLine(uint8array, lineIndex);
  64398. if (line == "FORMAT=32-bit_rle_rgbe") {
  64399. findFormat = true;
  64400. }
  64401. else if (line.length == 0) {
  64402. endOfHeader = true;
  64403. }
  64404. } while (!endOfHeader);
  64405. if (!findFormat) {
  64406. throw "HDR Bad header format, unsupported FORMAT";
  64407. }
  64408. lineIndex += (line.length + 1);
  64409. line = this.readStringLine(uint8array, lineIndex);
  64410. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  64411. var match = sizeRegexp.exec(line);
  64412. // TODO. Support +Y and -X if needed.
  64413. if (!match || match.length < 3) {
  64414. throw "HDR Bad header format, no size";
  64415. }
  64416. width = parseInt(match[2]);
  64417. height = parseInt(match[1]);
  64418. if (width < 8 || width > 0x7fff) {
  64419. throw "HDR Bad header format, unsupported size";
  64420. }
  64421. lineIndex += (line.length + 1);
  64422. return {
  64423. height: height,
  64424. width: width,
  64425. dataPosition: lineIndex
  64426. };
  64427. };
  64428. /**
  64429. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  64430. * This RGBE texture needs to store the information as a panorama.
  64431. *
  64432. * More information on this format are available here:
  64433. * https://en.wikipedia.org/wiki/RGBE_image_format
  64434. *
  64435. * @param buffer The binary file stored in an array buffer.
  64436. * @param size The expected size of the extracted cubemap.
  64437. * @return The Cube Map information.
  64438. */
  64439. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  64440. var uint8array = new Uint8Array(buffer);
  64441. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  64442. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  64443. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  64444. return cubeMapData;
  64445. };
  64446. /**
  64447. * Returns the pixels data extracted from an RGBE texture.
  64448. * This pixels will be stored left to right up to down in the R G B order in one array.
  64449. *
  64450. * More information on this format are available here:
  64451. * https://en.wikipedia.org/wiki/RGBE_image_format
  64452. *
  64453. * @param uint8array The binary file stored in an array buffer.
  64454. * @param hdrInfo The header information of the file.
  64455. * @return The pixels data in RGB right to left up to down order.
  64456. */
  64457. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  64458. // Keep for multi format supports.
  64459. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  64460. };
  64461. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  64462. var num_scanlines = hdrInfo.height;
  64463. var scanline_width = hdrInfo.width;
  64464. var a, b, c, d, count;
  64465. var dataIndex = hdrInfo.dataPosition;
  64466. var index = 0, endIndex = 0, i = 0;
  64467. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  64468. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  64469. // 3 channels of 4 bytes per pixel in float.
  64470. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  64471. var resultArray = new Float32Array(resultBuffer);
  64472. // read in each successive scanline
  64473. while (num_scanlines > 0) {
  64474. a = uint8array[dataIndex++];
  64475. b = uint8array[dataIndex++];
  64476. c = uint8array[dataIndex++];
  64477. d = uint8array[dataIndex++];
  64478. if (a != 2 || b != 2 || (c & 0x80)) {
  64479. // this file is not run length encoded
  64480. throw "HDR Bad header format, not RLE";
  64481. }
  64482. if (((c << 8) | d) != scanline_width) {
  64483. throw "HDR Bad header format, wrong scan line width";
  64484. }
  64485. index = 0;
  64486. // read each of the four channels for the scanline into the buffer
  64487. for (i = 0; i < 4; i++) {
  64488. endIndex = (i + 1) * scanline_width;
  64489. while (index < endIndex) {
  64490. a = uint8array[dataIndex++];
  64491. b = uint8array[dataIndex++];
  64492. if (a > 128) {
  64493. // a run of the same value
  64494. count = a - 128;
  64495. if ((count == 0) || (count > endIndex - index)) {
  64496. throw "HDR Bad Format, bad scanline data (run)";
  64497. }
  64498. while (count-- > 0) {
  64499. scanLineArray[index++] = b;
  64500. }
  64501. }
  64502. else {
  64503. // a non-run
  64504. count = a;
  64505. if ((count == 0) || (count > endIndex - index)) {
  64506. throw "HDR Bad Format, bad scanline data (non-run)";
  64507. }
  64508. scanLineArray[index++] = b;
  64509. if (--count > 0) {
  64510. for (var j = 0; j < count; j++) {
  64511. scanLineArray[index++] = uint8array[dataIndex++];
  64512. }
  64513. }
  64514. }
  64515. }
  64516. }
  64517. // now convert data from buffer into floats
  64518. for (i = 0; i < scanline_width; i++) {
  64519. a = scanLineArray[i];
  64520. b = scanLineArray[i + scanline_width];
  64521. c = scanLineArray[i + 2 * scanline_width];
  64522. d = scanLineArray[i + 3 * scanline_width];
  64523. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  64524. }
  64525. num_scanlines--;
  64526. }
  64527. return resultArray;
  64528. };
  64529. return HDRTools;
  64530. }());
  64531. Internals.HDRTools = HDRTools;
  64532. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  64533. })(BABYLON || (BABYLON = {}));
  64534. //# sourceMappingURL=babylon.hdr.js.map
  64535. var BABYLON;
  64536. (function (BABYLON) {
  64537. /**
  64538. * This represents a texture coming from an HDR input.
  64539. *
  64540. * The only supported format is currently panorama picture stored in RGBE format.
  64541. * Example of such files can be found on HDRLib: http://hdrlib.com/
  64542. */
  64543. var HDRCubeTexture = /** @class */ (function (_super) {
  64544. __extends(HDRCubeTexture, _super);
  64545. /**
  64546. * Instantiates an HDRTexture from the following parameters.
  64547. *
  64548. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  64549. * @param scene The scene the texture will be used in
  64550. * @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.
  64551. * @param noMipmap Forces to not generate the mipmap if true
  64552. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  64553. * @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)
  64554. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  64555. */
  64556. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  64557. if (noMipmap === void 0) { noMipmap = false; }
  64558. if (generateHarmonics === void 0) { generateHarmonics = true; }
  64559. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  64560. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  64561. if (onLoad === void 0) { onLoad = null; }
  64562. if (onError === void 0) { onError = null; }
  64563. var _this = _super.call(this, scene) || this;
  64564. _this._useInGammaSpace = false;
  64565. _this._generateHarmonics = true;
  64566. _this._isBABYLONPreprocessed = false;
  64567. _this._onLoad = null;
  64568. _this._onError = null;
  64569. /**
  64570. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  64571. */
  64572. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  64573. /**
  64574. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  64575. * This is usefull at run time to apply the good shader.
  64576. */
  64577. _this.isPMREM = false;
  64578. _this._isBlocking = true;
  64579. if (!url) {
  64580. return _this;
  64581. }
  64582. _this.name = url;
  64583. _this.url = url;
  64584. _this.hasAlpha = false;
  64585. _this.isCube = true;
  64586. _this._textureMatrix = BABYLON.Matrix.Identity();
  64587. _this._onLoad = onLoad;
  64588. _this._onError = onError;
  64589. _this.gammaSpace = false;
  64590. var caps = scene.getEngine().getCaps();
  64591. if (size) {
  64592. _this._isBABYLONPreprocessed = false;
  64593. _this._noMipmap = noMipmap;
  64594. _this._size = size;
  64595. _this._useInGammaSpace = useInGammaSpace;
  64596. _this._usePMREMGenerator = usePMREMGenerator &&
  64597. caps.textureLOD &&
  64598. caps.textureFloat &&
  64599. !_this._useInGammaSpace;
  64600. }
  64601. else {
  64602. _this._isBABYLONPreprocessed = true;
  64603. _this._noMipmap = false;
  64604. _this._useInGammaSpace = false;
  64605. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  64606. !_this._useInGammaSpace;
  64607. }
  64608. _this.isPMREM = _this._usePMREMGenerator;
  64609. _this._texture = _this._getFromCache(url, _this._noMipmap);
  64610. if (!_this._texture) {
  64611. if (!scene.useDelayedTextureLoading) {
  64612. _this.loadTexture();
  64613. }
  64614. else {
  64615. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  64616. }
  64617. }
  64618. return _this;
  64619. }
  64620. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  64621. /**
  64622. * Gets wether or not the texture is blocking during loading.
  64623. */
  64624. get: function () {
  64625. return this._isBlocking;
  64626. },
  64627. /**
  64628. * Sets wether or not the texture is blocking during loading.
  64629. */
  64630. set: function (value) {
  64631. this._isBlocking = value;
  64632. },
  64633. enumerable: true,
  64634. configurable: true
  64635. });
  64636. /**
  64637. * Occurs when the file is a preprocessed .babylon.hdr file.
  64638. */
  64639. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  64640. var _this = this;
  64641. var mipLevels = 0;
  64642. var floatArrayView = null;
  64643. var scene = this.getScene();
  64644. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  64645. var mips = new Array();
  64646. if (!floatArrayView) {
  64647. return mips;
  64648. }
  64649. var startIndex = 30;
  64650. for (var level = 0; level < mipLevels; level++) {
  64651. mips.push([]);
  64652. // Fill each pixel of the mip level.
  64653. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  64654. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  64655. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  64656. mips[level].push(faceData);
  64657. startIndex += faceSize;
  64658. }
  64659. }
  64660. return mips;
  64661. } : null;
  64662. var callback = function (buffer) {
  64663. var scene = _this.getScene();
  64664. if (!scene) {
  64665. return null;
  64666. }
  64667. // Create Native Array Views
  64668. var intArrayView = new Int32Array(buffer);
  64669. floatArrayView = new Float32Array(buffer);
  64670. // Fill header.
  64671. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  64672. _this._size = intArrayView[1]; // CubeMap max mip face size.
  64673. // Update Texture Information.
  64674. if (!_this._texture) {
  64675. return null;
  64676. }
  64677. _this._texture.updateSize(_this._size, _this._size);
  64678. // Fill polynomial information.
  64679. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  64680. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  64681. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  64682. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  64683. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  64684. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  64685. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  64686. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  64687. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  64688. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  64689. _this.sphericalPolynomial = sphericalPolynomial;
  64690. // Fill pixel data.
  64691. mipLevels = intArrayView[29]; // Number of mip levels.
  64692. var startIndex = 30;
  64693. var data = [];
  64694. var faceSize = Math.pow(_this._size, 2) * 3;
  64695. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  64696. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  64697. startIndex += faceSize;
  64698. }
  64699. var results = [];
  64700. var byteArray = null;
  64701. // Push each faces.
  64702. for (var k = 0; k < 6; k++) {
  64703. var dataFace = null;
  64704. // To be deprecated.
  64705. if (version === 1) {
  64706. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  64707. dataFace = data[j];
  64708. }
  64709. // If special cases.
  64710. if (!mipmapGenerator && dataFace) {
  64711. if (!scene.getEngine().getCaps().textureFloat) {
  64712. // 3 channels of 1 bytes per pixel in bytes.
  64713. var byteBuffer = new ArrayBuffer(faceSize);
  64714. byteArray = new Uint8Array(byteBuffer);
  64715. }
  64716. for (var i = 0; i < _this._size * _this._size; i++) {
  64717. // Put in gamma space if requested.
  64718. if (_this._useInGammaSpace) {
  64719. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  64720. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  64721. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  64722. }
  64723. // Convert to int texture for fallback.
  64724. if (byteArray) {
  64725. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  64726. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  64727. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  64728. // May use luminance instead if the result is not accurate.
  64729. var max = Math.max(Math.max(r, g), b);
  64730. if (max > 255) {
  64731. var scale = 255 / max;
  64732. r *= scale;
  64733. g *= scale;
  64734. b *= scale;
  64735. }
  64736. byteArray[(i * 3) + 0] = r;
  64737. byteArray[(i * 3) + 1] = g;
  64738. byteArray[(i * 3) + 2] = b;
  64739. }
  64740. }
  64741. }
  64742. // Fill the array accordingly.
  64743. if (byteArray) {
  64744. results.push(byteArray);
  64745. }
  64746. else {
  64747. results.push(dataFace);
  64748. }
  64749. }
  64750. return results;
  64751. };
  64752. if (scene) {
  64753. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  64754. }
  64755. };
  64756. /**
  64757. * Occurs when the file is raw .hdr file.
  64758. */
  64759. HDRCubeTexture.prototype.loadHDRTexture = function () {
  64760. var _this = this;
  64761. var callback = function (buffer) {
  64762. var scene = _this.getScene();
  64763. if (!scene) {
  64764. return null;
  64765. }
  64766. // Extract the raw linear data.
  64767. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  64768. // Generate harmonics if needed.
  64769. if (_this._generateHarmonics) {
  64770. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  64771. _this.sphericalPolynomial = sphericalPolynomial;
  64772. }
  64773. var results = [];
  64774. var byteArray = null;
  64775. // Push each faces.
  64776. for (var j = 0; j < 6; j++) {
  64777. // Create uintarray fallback.
  64778. if (!scene.getEngine().getCaps().textureFloat) {
  64779. // 3 channels of 1 bytes per pixel in bytes.
  64780. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  64781. byteArray = new Uint8Array(byteBuffer);
  64782. }
  64783. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  64784. // If special cases.
  64785. if (_this._useInGammaSpace || byteArray) {
  64786. for (var i = 0; i < _this._size * _this._size; i++) {
  64787. // Put in gamma space if requested.
  64788. if (_this._useInGammaSpace) {
  64789. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  64790. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  64791. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  64792. }
  64793. // Convert to int texture for fallback.
  64794. if (byteArray) {
  64795. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  64796. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  64797. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  64798. // May use luminance instead if the result is not accurate.
  64799. var max = Math.max(Math.max(r, g), b);
  64800. if (max > 255) {
  64801. var scale = 255 / max;
  64802. r *= scale;
  64803. g *= scale;
  64804. b *= scale;
  64805. }
  64806. byteArray[(i * 3) + 0] = r;
  64807. byteArray[(i * 3) + 1] = g;
  64808. byteArray[(i * 3) + 2] = b;
  64809. }
  64810. }
  64811. }
  64812. if (byteArray) {
  64813. results.push(byteArray);
  64814. }
  64815. else {
  64816. results.push(dataFace);
  64817. }
  64818. }
  64819. return results;
  64820. };
  64821. var mipmapGenerator = null;
  64822. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  64823. // if (!this._noMipmap &&
  64824. // this._usePMREMGenerator) {
  64825. // mipmapGenerator = (data: ArrayBufferView[]) => {
  64826. // // Custom setup of the generator matching with the PBR shader values.
  64827. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  64828. // this._size,
  64829. // this._size,
  64830. // 0,
  64831. // 3,
  64832. // this.getScene().getEngine().getCaps().textureFloat,
  64833. // 2048,
  64834. // 0.25,
  64835. // false,
  64836. // true);
  64837. // return generator.filterCubeMap();
  64838. // };
  64839. // }
  64840. var scene = this.getScene();
  64841. if (scene) {
  64842. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  64843. }
  64844. };
  64845. /**
  64846. * Starts the loading process of the texture.
  64847. */
  64848. HDRCubeTexture.prototype.loadTexture = function () {
  64849. if (this._isBABYLONPreprocessed) {
  64850. this.loadBabylonTexture();
  64851. }
  64852. else {
  64853. this.loadHDRTexture();
  64854. }
  64855. };
  64856. HDRCubeTexture.prototype.clone = function () {
  64857. var scene = this.getScene();
  64858. if (!scene) {
  64859. return this;
  64860. }
  64861. var size = (this._isBABYLONPreprocessed ? null : this._size);
  64862. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  64863. // Base texture
  64864. newTexture.level = this.level;
  64865. newTexture.wrapU = this.wrapU;
  64866. newTexture.wrapV = this.wrapV;
  64867. newTexture.coordinatesIndex = this.coordinatesIndex;
  64868. newTexture.coordinatesMode = this.coordinatesMode;
  64869. return newTexture;
  64870. };
  64871. // Methods
  64872. HDRCubeTexture.prototype.delayLoad = function () {
  64873. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  64874. return;
  64875. }
  64876. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  64877. this._texture = this._getFromCache(this.url, this._noMipmap);
  64878. if (!this._texture) {
  64879. this.loadTexture();
  64880. }
  64881. };
  64882. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  64883. return this._textureMatrix;
  64884. };
  64885. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  64886. this._textureMatrix = value;
  64887. };
  64888. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  64889. var texture = null;
  64890. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  64891. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  64892. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  64893. texture.name = parsedTexture.name;
  64894. texture.hasAlpha = parsedTexture.hasAlpha;
  64895. texture.level = parsedTexture.level;
  64896. texture.coordinatesMode = parsedTexture.coordinatesMode;
  64897. texture.isBlocking = parsedTexture.isBlocking;
  64898. }
  64899. return texture;
  64900. };
  64901. HDRCubeTexture.prototype.serialize = function () {
  64902. if (!this.name) {
  64903. return null;
  64904. }
  64905. var serializationObject = {};
  64906. serializationObject.name = this.name;
  64907. serializationObject.hasAlpha = this.hasAlpha;
  64908. serializationObject.isCube = true;
  64909. serializationObject.level = this.level;
  64910. serializationObject.size = this._size;
  64911. serializationObject.coordinatesMode = this.coordinatesMode;
  64912. serializationObject.useInGammaSpace = this._useInGammaSpace;
  64913. serializationObject.generateHarmonics = this._generateHarmonics;
  64914. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  64915. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  64916. serializationObject.customType = "BABYLON.HDRCubeTexture";
  64917. serializationObject.noMipmap = this._noMipmap;
  64918. serializationObject.isBlocking = this._isBlocking;
  64919. return serializationObject;
  64920. };
  64921. /**
  64922. * Saves as a file the data contained in the texture in a binary format.
  64923. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  64924. * as the spherical used in the lighting.
  64925. * @param url The HDR file url.
  64926. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  64927. * @param onError Method called if any error happens during download.
  64928. * @return The packed binary data.
  64929. */
  64930. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  64931. if (onError === void 0) { onError = null; }
  64932. var callback = function (buffer) {
  64933. var data = new Blob([buffer], { type: 'application/octet-stream' });
  64934. // Returns a URL you can use as a href.
  64935. var objUrl = window.URL.createObjectURL(data);
  64936. // Simulates a link to it and click to dowload.
  64937. var a = document.createElement("a");
  64938. document.body.appendChild(a);
  64939. a.style.display = "none";
  64940. a.href = objUrl;
  64941. a.download = "envmap.babylon.hdr";
  64942. a.click();
  64943. };
  64944. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  64945. };
  64946. /**
  64947. * Serializes the data contained in the texture in a binary format.
  64948. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  64949. * as the spherical used in the lighting.
  64950. * @param url The HDR file url.
  64951. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  64952. * @param onError Method called if any error happens during download.
  64953. * @return The packed binary data.
  64954. */
  64955. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  64956. if (onError === void 0) { onError = null; }
  64957. // Needs the url tho create the texture.
  64958. if (!url) {
  64959. return;
  64960. }
  64961. // Check Power of two size.
  64962. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  64963. return;
  64964. }
  64965. // Coming Back in 3.x.
  64966. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  64967. };
  64968. HDRCubeTexture._facesMapping = [
  64969. "right",
  64970. "left",
  64971. "up",
  64972. "down",
  64973. "front",
  64974. "back"
  64975. ];
  64976. return HDRCubeTexture;
  64977. }(BABYLON.BaseTexture));
  64978. BABYLON.HDRCubeTexture = HDRCubeTexture;
  64979. })(BABYLON || (BABYLON = {}));
  64980. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  64981. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  64982. // Huge respect for a such great lib.
  64983. // Earcut license:
  64984. // Copyright (c) 2016, Mapbox
  64985. //
  64986. // Permission to use, copy, modify, and/or distribute this software for any purpose
  64987. // with or without fee is hereby granted, provided that the above copyright notice
  64988. // and this permission notice appear in all copies.
  64989. //
  64990. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  64991. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  64992. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  64993. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  64994. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  64995. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  64996. // THIS SOFTWARE.
  64997. var Earcut;
  64998. (function (Earcut) {
  64999. /**
  65000. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  65001. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  65002. * @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).
  65003. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  65004. */
  65005. function earcut(data, holeIndices, dim) {
  65006. dim = dim || 2;
  65007. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  65008. if (!outerNode)
  65009. return triangles;
  65010. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  65011. if (hasHoles)
  65012. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  65013. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  65014. if (data.length > 80 * dim) {
  65015. minX = maxX = data[0];
  65016. minY = maxY = data[1];
  65017. for (var i = dim; i < outerLen; i += dim) {
  65018. x = data[i];
  65019. y = data[i + 1];
  65020. if (x < minX)
  65021. minX = x;
  65022. if (y < minY)
  65023. minY = y;
  65024. if (x > maxX)
  65025. maxX = x;
  65026. if (y > maxY)
  65027. maxY = y;
  65028. }
  65029. // minX, minY and size are later used to transform coords into integers for z-order calculation
  65030. size = Math.max(maxX - minX, maxY - minY);
  65031. }
  65032. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  65033. return triangles;
  65034. }
  65035. Earcut.earcut = earcut;
  65036. var Node = /** @class */ (function () {
  65037. function Node(i, x, y) {
  65038. this.i = i;
  65039. this.x = x;
  65040. this.y = y;
  65041. this.prev = null;
  65042. this.next = null;
  65043. this.z = null;
  65044. this.prevZ = null;
  65045. this.nextZ = null;
  65046. this.steiner = false;
  65047. }
  65048. return Node;
  65049. }());
  65050. // create a circular doubly linked list from polygon points in the specified winding order
  65051. function linkedList(data, start, end, dim, clockwise) {
  65052. var i, last = null;
  65053. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  65054. for (i = start; i < end; i += dim)
  65055. last = insertNode(i, data[i], data[i + 1], last);
  65056. }
  65057. else {
  65058. for (i = end - dim; i >= start; i -= dim)
  65059. last = insertNode(i, data[i], data[i + 1], last);
  65060. }
  65061. if (last && equals(last, last.next)) {
  65062. removeNode(last);
  65063. last = last.next;
  65064. }
  65065. return last;
  65066. }
  65067. // eliminate colinear or duplicate points
  65068. function filterPoints(start, end) {
  65069. if (!start)
  65070. return start;
  65071. if (!end)
  65072. end = start;
  65073. var p = start, again;
  65074. do {
  65075. again = false;
  65076. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  65077. removeNode(p);
  65078. p = end = p.prev;
  65079. if (p === p.next)
  65080. return undefined;
  65081. again = true;
  65082. }
  65083. else {
  65084. p = p.next;
  65085. }
  65086. } while (again || p !== end);
  65087. return end;
  65088. }
  65089. // main ear slicing loop which triangulates a polygon (given as a linked list)
  65090. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  65091. if (!ear)
  65092. return;
  65093. // interlink polygon nodes in z-order
  65094. if (!pass && size)
  65095. indexCurve(ear, minX, minY, size);
  65096. var stop = ear, prev, next;
  65097. // iterate through ears, slicing them one by one
  65098. while (ear.prev !== ear.next) {
  65099. prev = ear.prev;
  65100. next = ear.next;
  65101. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  65102. // cut off the triangle
  65103. triangles.push(prev.i / dim);
  65104. triangles.push(ear.i / dim);
  65105. triangles.push(next.i / dim);
  65106. removeNode(ear);
  65107. // skipping the next vertice leads to less sliver triangles
  65108. ear = next.next;
  65109. stop = next.next;
  65110. continue;
  65111. }
  65112. ear = next;
  65113. // if we looped through the whole remaining polygon and can't find any more ears
  65114. if (ear === stop) {
  65115. // try filtering points and slicing again
  65116. if (!pass) {
  65117. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  65118. // if this didn't work, try curing all small self-intersections locally
  65119. }
  65120. else if (pass === 1) {
  65121. ear = cureLocalIntersections(ear, triangles, dim);
  65122. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  65123. // as a last resort, try splitting the remaining polygon into two
  65124. }
  65125. else if (pass === 2) {
  65126. splitEarcut(ear, triangles, dim, minX, minY, size);
  65127. }
  65128. break;
  65129. }
  65130. }
  65131. }
  65132. // check whether a polygon node forms a valid ear with adjacent nodes
  65133. function isEar(ear) {
  65134. var a = ear.prev, b = ear, c = ear.next;
  65135. if (area(a, b, c) >= 0)
  65136. return false; // reflex, can't be an ear
  65137. // now make sure we don't have other points inside the potential ear
  65138. var p = ear.next.next;
  65139. while (p !== ear.prev) {
  65140. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  65141. area(p.prev, p, p.next) >= 0)
  65142. return false;
  65143. p = p.next;
  65144. }
  65145. return true;
  65146. }
  65147. function isEarHashed(ear, minX, minY, size) {
  65148. var a = ear.prev, b = ear, c = ear.next;
  65149. if (area(a, b, c) >= 0)
  65150. return false; // reflex, can't be an ear
  65151. // triangle bbox; min & max are calculated like this for speed
  65152. 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);
  65153. // z-order range for the current triangle bbox;
  65154. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  65155. // first look for points inside the triangle in increasing z-order
  65156. var p = ear.nextZ;
  65157. while (p && p.z <= maxZ) {
  65158. if (p !== ear.prev &&
  65159. p !== ear.next &&
  65160. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  65161. area(p.prev, p, p.next) >= 0)
  65162. return false;
  65163. p = p.nextZ;
  65164. }
  65165. // then look for points in decreasing z-order
  65166. p = ear.prevZ;
  65167. while (p && p.z >= minZ) {
  65168. if (p !== ear.prev &&
  65169. p !== ear.next &&
  65170. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  65171. area(p.prev, p, p.next) >= 0)
  65172. return false;
  65173. p = p.prevZ;
  65174. }
  65175. return true;
  65176. }
  65177. // go through all polygon nodes and cure small local self-intersections
  65178. function cureLocalIntersections(start, triangles, dim) {
  65179. var p = start;
  65180. do {
  65181. var a = p.prev, b = p.next.next;
  65182. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  65183. triangles.push(a.i / dim);
  65184. triangles.push(p.i / dim);
  65185. triangles.push(b.i / dim);
  65186. // remove two nodes involved
  65187. removeNode(p);
  65188. removeNode(p.next);
  65189. p = start = b;
  65190. }
  65191. p = p.next;
  65192. } while (p !== start);
  65193. return p;
  65194. }
  65195. // try splitting polygon into two and triangulate them independently
  65196. function splitEarcut(start, triangles, dim, minX, minY, size) {
  65197. // look for a valid diagonal that divides the polygon into two
  65198. var a = start;
  65199. do {
  65200. var b = a.next.next;
  65201. while (b !== a.prev) {
  65202. if (a.i !== b.i && isValidDiagonal(a, b)) {
  65203. // split the polygon in two by the diagonal
  65204. var c = splitPolygon(a, b);
  65205. // filter colinear points around the cuts
  65206. a = filterPoints(a, a.next);
  65207. c = filterPoints(c, c.next);
  65208. // run earcut on each half
  65209. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  65210. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  65211. return;
  65212. }
  65213. b = b.next;
  65214. }
  65215. a = a.next;
  65216. } while (a !== start);
  65217. }
  65218. // link every hole into the outer loop, producing a single-ring polygon without holes
  65219. function eliminateHoles(data, holeIndices, outerNode, dim) {
  65220. var queue = [], i, len, start, end, list;
  65221. for (i = 0, len = holeIndices.length; i < len; i++) {
  65222. start = holeIndices[i] * dim;
  65223. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  65224. list = linkedList(data, start, end, dim, false);
  65225. if (list === list.next)
  65226. list.steiner = true;
  65227. queue.push(getLeftmost(list));
  65228. }
  65229. queue.sort(compareX);
  65230. // process holes from left to right
  65231. for (i = 0; i < queue.length; i++) {
  65232. eliminateHole(queue[i], outerNode);
  65233. outerNode = filterPoints(outerNode, outerNode.next);
  65234. }
  65235. return outerNode;
  65236. }
  65237. function compareX(a, b) {
  65238. return a.x - b.x;
  65239. }
  65240. // find a bridge between vertices that connects hole with an outer ring and and link it
  65241. function eliminateHole(hole, outerNode) {
  65242. outerNode = findHoleBridge(hole, outerNode);
  65243. if (outerNode) {
  65244. var b = splitPolygon(outerNode, hole);
  65245. filterPoints(b, b.next);
  65246. }
  65247. }
  65248. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  65249. function findHoleBridge(hole, outerNode) {
  65250. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  65251. // find a segment intersected by a ray from the hole's leftmost point to the left;
  65252. // segment's endpoint with lesser x will be potential connection point
  65253. do {
  65254. if (hy <= p.y && hy >= p.next.y) {
  65255. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  65256. if (x <= hx && x > qx) {
  65257. qx = x;
  65258. if (x === hx) {
  65259. if (hy === p.y)
  65260. return p;
  65261. if (hy === p.next.y)
  65262. return p.next;
  65263. }
  65264. m = p.x < p.next.x ? p : p.next;
  65265. }
  65266. }
  65267. p = p.next;
  65268. } while (p !== outerNode);
  65269. if (!m)
  65270. return null;
  65271. if (hx === qx)
  65272. return m.prev; // hole touches outer segment; pick lower endpoint
  65273. // look for points inside the triangle of hole point, segment intersection and endpoint;
  65274. // if there are no points found, we have a valid connection;
  65275. // otherwise choose the point of the minimum angle with the ray as connection point
  65276. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  65277. p = m.next;
  65278. while (p !== stop) {
  65279. if (hx >= p.x &&
  65280. p.x >= mx &&
  65281. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  65282. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  65283. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  65284. m = p;
  65285. tanMin = tan;
  65286. }
  65287. }
  65288. p = p.next;
  65289. }
  65290. return m;
  65291. }
  65292. // interlink polygon nodes in z-order
  65293. function indexCurve(start, minX, minY, size) {
  65294. var p = start;
  65295. do {
  65296. if (p.z === null)
  65297. p.z = zOrder(p.x, p.y, minX, minY, size);
  65298. p.prevZ = p.prev;
  65299. p.nextZ = p.next;
  65300. p = p.next;
  65301. } while (p !== start);
  65302. p.prevZ.nextZ = null;
  65303. p.prevZ = null;
  65304. sortLinked(p);
  65305. }
  65306. // Simon Tatham's linked list merge sort algorithm
  65307. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  65308. function sortLinked(list) {
  65309. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  65310. do {
  65311. p = list;
  65312. list = null;
  65313. tail = null;
  65314. numMerges = 0;
  65315. while (p) {
  65316. numMerges++;
  65317. q = p;
  65318. pSize = 0;
  65319. for (i = 0; i < inSize; i++) {
  65320. pSize++;
  65321. q = q.nextZ;
  65322. if (!q)
  65323. break;
  65324. }
  65325. qSize = inSize;
  65326. while (pSize > 0 || (qSize > 0 && q)) {
  65327. if (pSize === 0) {
  65328. e = q;
  65329. q = q.nextZ;
  65330. qSize--;
  65331. }
  65332. else if (qSize === 0 || !q) {
  65333. e = p;
  65334. p = p.nextZ;
  65335. pSize--;
  65336. }
  65337. else if (p.z <= q.z) {
  65338. e = p;
  65339. p = p.nextZ;
  65340. pSize--;
  65341. }
  65342. else {
  65343. e = q;
  65344. q = q.nextZ;
  65345. qSize--;
  65346. }
  65347. if (tail)
  65348. tail.nextZ = e;
  65349. else
  65350. list = e;
  65351. e.prevZ = tail;
  65352. tail = e;
  65353. }
  65354. p = q;
  65355. }
  65356. tail.nextZ = null;
  65357. inSize *= 2;
  65358. } while (numMerges > 1);
  65359. return list;
  65360. }
  65361. // z-order of a point given coords and size of the data bounding box
  65362. function zOrder(x, y, minX, minY, size) {
  65363. // coords are transformed into non-negative 15-bit integer range
  65364. x = 32767 * (x - minX) / size;
  65365. y = 32767 * (y - minY) / size;
  65366. x = (x | (x << 8)) & 0x00FF00FF;
  65367. x = (x | (x << 4)) & 0x0F0F0F0F;
  65368. x = (x | (x << 2)) & 0x33333333;
  65369. x = (x | (x << 1)) & 0x55555555;
  65370. y = (y | (y << 8)) & 0x00FF00FF;
  65371. y = (y | (y << 4)) & 0x0F0F0F0F;
  65372. y = (y | (y << 2)) & 0x33333333;
  65373. y = (y | (y << 1)) & 0x55555555;
  65374. return x | (y << 1);
  65375. }
  65376. // find the leftmost node of a polygon ring
  65377. function getLeftmost(start) {
  65378. var p = start, leftmost = start;
  65379. do {
  65380. if (p.x < leftmost.x)
  65381. leftmost = p;
  65382. p = p.next;
  65383. } while (p !== start);
  65384. return leftmost;
  65385. }
  65386. // check if a point lies within a convex triangle
  65387. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  65388. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  65389. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  65390. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  65391. }
  65392. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  65393. function isValidDiagonal(a, b) {
  65394. return a.next.i !== b.i &&
  65395. a.prev.i !== b.i &&
  65396. !intersectsPolygon(a, b) &&
  65397. locallyInside(a, b) &&
  65398. locallyInside(b, a) &&
  65399. middleInside(a, b);
  65400. }
  65401. // signed area of a triangle
  65402. function area(p, q, r) {
  65403. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  65404. }
  65405. // check if two points are equal
  65406. function equals(p1, p2) {
  65407. return p1.x === p2.x && p1.y === p2.y;
  65408. }
  65409. // check if two segments intersect
  65410. function intersects(p1, q1, p2, q2) {
  65411. if ((equals(p1, q1) && equals(p2, q2)) ||
  65412. (equals(p1, q2) && equals(p2, q1)))
  65413. return true;
  65414. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  65415. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  65416. }
  65417. // check if a polygon diagonal intersects any polygon segments
  65418. function intersectsPolygon(a, b) {
  65419. var p = a;
  65420. do {
  65421. if (p.i !== a.i &&
  65422. p.next.i !== a.i &&
  65423. p.i !== b.i &&
  65424. p.next.i !== b.i &&
  65425. intersects(p, p.next, a, b))
  65426. return true;
  65427. p = p.next;
  65428. } while (p !== a);
  65429. return false;
  65430. }
  65431. // check if a polygon diagonal is locally inside the polygon
  65432. function locallyInside(a, b) {
  65433. return area(a.prev, a, a.next) < 0
  65434. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  65435. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  65436. }
  65437. // check if the middle point of a polygon diagonal is inside the polygon
  65438. function middleInside(a, b) {
  65439. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  65440. do {
  65441. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  65442. inside = !inside;
  65443. p = p.next;
  65444. } while (p !== a);
  65445. return inside;
  65446. }
  65447. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  65448. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  65449. function splitPolygon(a, b) {
  65450. 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;
  65451. a.next = b;
  65452. b.prev = a;
  65453. a2.next = an;
  65454. an.prev = a2;
  65455. b2.next = a2;
  65456. a2.prev = b2;
  65457. bp.next = b2;
  65458. b2.prev = bp;
  65459. return b2;
  65460. }
  65461. // create a node and optionally link it with previous one (in a circular doubly linked list)
  65462. function insertNode(i, x, y, last) {
  65463. var p = new Node(i, x, y);
  65464. if (!last) {
  65465. p.prev = p;
  65466. p.next = p;
  65467. }
  65468. else {
  65469. p.next = last.next;
  65470. p.prev = last;
  65471. last.next.prev = p;
  65472. last.next = p;
  65473. }
  65474. return p;
  65475. }
  65476. function removeNode(p) {
  65477. p.next.prev = p.prev;
  65478. p.prev.next = p.next;
  65479. if (p.prevZ)
  65480. p.prevZ.nextZ = p.nextZ;
  65481. if (p.nextZ)
  65482. p.nextZ.prevZ = p.prevZ;
  65483. }
  65484. /**
  65485. * return a percentage difference between the polygon area and its triangulation area;
  65486. * used to verify correctness of triangulation
  65487. */
  65488. function deviation(data, holeIndices, dim, triangles) {
  65489. var hasHoles = holeIndices && holeIndices.length;
  65490. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  65491. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  65492. if (hasHoles) {
  65493. for (var i = 0, len = holeIndices.length; i < len; i++) {
  65494. var start = holeIndices[i] * dim;
  65495. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  65496. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  65497. }
  65498. }
  65499. var trianglesArea = 0;
  65500. for (i = 0; i < triangles.length; i += 3) {
  65501. var a = triangles[i] * dim;
  65502. var b = triangles[i + 1] * dim;
  65503. var c = triangles[i + 2] * dim;
  65504. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  65505. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  65506. }
  65507. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  65508. }
  65509. Earcut.deviation = deviation;
  65510. ;
  65511. function signedArea(data, start, end, dim) {
  65512. var sum = 0;
  65513. for (var i = start, j = end - dim; i < end; i += dim) {
  65514. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  65515. j = i;
  65516. }
  65517. return sum;
  65518. }
  65519. /**
  65520. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  65521. */
  65522. function flatten(data) {
  65523. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  65524. for (var i = 0; i < data.length; i++) {
  65525. for (var j = 0; j < data[i].length; j++) {
  65526. for (var d = 0; d < dim; d++)
  65527. result.vertices.push(data[i][j][d]);
  65528. }
  65529. if (i > 0) {
  65530. holeIndex += data[i - 1].length;
  65531. result.holes.push(holeIndex);
  65532. }
  65533. }
  65534. return result;
  65535. }
  65536. Earcut.flatten = flatten;
  65537. ;
  65538. })(Earcut || (Earcut = {}));
  65539. //# sourceMappingURL=babylon.earcut.js.map
  65540. var BABYLON;
  65541. (function (BABYLON) {
  65542. var IndexedVector2 = /** @class */ (function (_super) {
  65543. __extends(IndexedVector2, _super);
  65544. function IndexedVector2(original, index) {
  65545. var _this = _super.call(this, original.x, original.y) || this;
  65546. _this.index = index;
  65547. return _this;
  65548. }
  65549. return IndexedVector2;
  65550. }(BABYLON.Vector2));
  65551. var PolygonPoints = /** @class */ (function () {
  65552. function PolygonPoints() {
  65553. this.elements = new Array();
  65554. }
  65555. PolygonPoints.prototype.add = function (originalPoints) {
  65556. var _this = this;
  65557. var result = new Array();
  65558. originalPoints.forEach(function (point) {
  65559. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  65560. var newPoint = new IndexedVector2(point, _this.elements.length);
  65561. result.push(newPoint);
  65562. _this.elements.push(newPoint);
  65563. }
  65564. });
  65565. return result;
  65566. };
  65567. PolygonPoints.prototype.computeBounds = function () {
  65568. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  65569. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  65570. this.elements.forEach(function (point) {
  65571. // x
  65572. if (point.x < lmin.x) {
  65573. lmin.x = point.x;
  65574. }
  65575. else if (point.x > lmax.x) {
  65576. lmax.x = point.x;
  65577. }
  65578. // y
  65579. if (point.y < lmin.y) {
  65580. lmin.y = point.y;
  65581. }
  65582. else if (point.y > lmax.y) {
  65583. lmax.y = point.y;
  65584. }
  65585. });
  65586. return {
  65587. min: lmin,
  65588. max: lmax,
  65589. width: lmax.x - lmin.x,
  65590. height: lmax.y - lmin.y
  65591. };
  65592. };
  65593. return PolygonPoints;
  65594. }());
  65595. var Polygon = /** @class */ (function () {
  65596. function Polygon() {
  65597. }
  65598. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  65599. return [
  65600. new BABYLON.Vector2(xmin, ymin),
  65601. new BABYLON.Vector2(xmax, ymin),
  65602. new BABYLON.Vector2(xmax, ymax),
  65603. new BABYLON.Vector2(xmin, ymax)
  65604. ];
  65605. };
  65606. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  65607. if (cx === void 0) { cx = 0; }
  65608. if (cy === void 0) { cy = 0; }
  65609. if (numberOfSides === void 0) { numberOfSides = 32; }
  65610. var result = new Array();
  65611. var angle = 0;
  65612. var increment = (Math.PI * 2) / numberOfSides;
  65613. for (var i = 0; i < numberOfSides; i++) {
  65614. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  65615. angle -= increment;
  65616. }
  65617. return result;
  65618. };
  65619. Polygon.Parse = function (input) {
  65620. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  65621. var i, result = [];
  65622. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  65623. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  65624. }
  65625. return result;
  65626. };
  65627. Polygon.StartingAt = function (x, y) {
  65628. return BABYLON.Path2.StartingAt(x, y);
  65629. };
  65630. return Polygon;
  65631. }());
  65632. BABYLON.Polygon = Polygon;
  65633. var PolygonMeshBuilder = /** @class */ (function () {
  65634. function PolygonMeshBuilder(name, contours, scene) {
  65635. this._points = new PolygonPoints();
  65636. this._outlinepoints = new PolygonPoints();
  65637. this._holes = new Array();
  65638. this._epoints = new Array();
  65639. this._eholes = new Array();
  65640. this._name = name;
  65641. this._scene = scene;
  65642. var points;
  65643. if (contours instanceof BABYLON.Path2) {
  65644. points = contours.getPoints();
  65645. }
  65646. else {
  65647. points = contours;
  65648. }
  65649. this._addToepoint(points);
  65650. this._points.add(points);
  65651. this._outlinepoints.add(points);
  65652. }
  65653. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  65654. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  65655. var p = points_1[_i];
  65656. this._epoints.push(p.x, p.y);
  65657. }
  65658. };
  65659. PolygonMeshBuilder.prototype.addHole = function (hole) {
  65660. this._points.add(hole);
  65661. var holepoints = new PolygonPoints();
  65662. holepoints.add(hole);
  65663. this._holes.push(holepoints);
  65664. this._eholes.push(this._epoints.length / 2);
  65665. this._addToepoint(hole);
  65666. return this;
  65667. };
  65668. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  65669. var _this = this;
  65670. if (updatable === void 0) { updatable = false; }
  65671. if (depth === void 0) { depth = 0; }
  65672. var result = new BABYLON.Mesh(this._name, this._scene);
  65673. var normals = new Array();
  65674. var positions = new Array();
  65675. var uvs = new Array();
  65676. var bounds = this._points.computeBounds();
  65677. this._points.elements.forEach(function (p) {
  65678. normals.push(0, 1.0, 0);
  65679. positions.push(p.x, 0, p.y);
  65680. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  65681. });
  65682. var indices = new Array();
  65683. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  65684. for (var i = 0; i < res.length; i++) {
  65685. indices.push(res[i]);
  65686. }
  65687. if (depth > 0) {
  65688. var positionscount = (positions.length / 3); //get the current pointcount
  65689. this._points.elements.forEach(function (p) {
  65690. normals.push(0, -1.0, 0);
  65691. positions.push(p.x, -depth, p.y);
  65692. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  65693. });
  65694. var totalCount = indices.length;
  65695. for (var i = 0; i < totalCount; i += 3) {
  65696. var i0 = indices[i + 0];
  65697. var i1 = indices[i + 1];
  65698. var i2 = indices[i + 2];
  65699. indices.push(i2 + positionscount);
  65700. indices.push(i1 + positionscount);
  65701. indices.push(i0 + positionscount);
  65702. }
  65703. //Add the sides
  65704. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  65705. this._holes.forEach(function (hole) {
  65706. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  65707. });
  65708. }
  65709. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  65710. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  65711. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  65712. result.setIndices(indices);
  65713. return result;
  65714. };
  65715. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  65716. var StartIndex = positions.length / 3;
  65717. var ulength = 0;
  65718. for (var i = 0; i < points.elements.length; i++) {
  65719. var p = points.elements[i];
  65720. var p1;
  65721. if ((i + 1) > points.elements.length - 1) {
  65722. p1 = points.elements[0];
  65723. }
  65724. else {
  65725. p1 = points.elements[i + 1];
  65726. }
  65727. positions.push(p.x, 0, p.y);
  65728. positions.push(p.x, -depth, p.y);
  65729. positions.push(p1.x, 0, p1.y);
  65730. positions.push(p1.x, -depth, p1.y);
  65731. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  65732. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  65733. var v3 = v2.subtract(v1);
  65734. var v4 = new BABYLON.Vector3(0, 1, 0);
  65735. var vn = BABYLON.Vector3.Cross(v3, v4);
  65736. vn = vn.normalize();
  65737. uvs.push(ulength / bounds.width, 0);
  65738. uvs.push(ulength / bounds.width, 1);
  65739. ulength += v3.length();
  65740. uvs.push((ulength / bounds.width), 0);
  65741. uvs.push((ulength / bounds.width), 1);
  65742. if (!flip) {
  65743. normals.push(-vn.x, -vn.y, -vn.z);
  65744. normals.push(-vn.x, -vn.y, -vn.z);
  65745. normals.push(-vn.x, -vn.y, -vn.z);
  65746. normals.push(-vn.x, -vn.y, -vn.z);
  65747. indices.push(StartIndex);
  65748. indices.push(StartIndex + 1);
  65749. indices.push(StartIndex + 2);
  65750. indices.push(StartIndex + 1);
  65751. indices.push(StartIndex + 3);
  65752. indices.push(StartIndex + 2);
  65753. }
  65754. else {
  65755. normals.push(vn.x, vn.y, vn.z);
  65756. normals.push(vn.x, vn.y, vn.z);
  65757. normals.push(vn.x, vn.y, vn.z);
  65758. normals.push(vn.x, vn.y, vn.z);
  65759. indices.push(StartIndex);
  65760. indices.push(StartIndex + 2);
  65761. indices.push(StartIndex + 1);
  65762. indices.push(StartIndex + 1);
  65763. indices.push(StartIndex + 2);
  65764. indices.push(StartIndex + 3);
  65765. }
  65766. StartIndex += 4;
  65767. }
  65768. ;
  65769. };
  65770. return PolygonMeshBuilder;
  65771. }());
  65772. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  65773. })(BABYLON || (BABYLON = {}));
  65774. //# sourceMappingURL=babylon.polygonMesh.js.map
  65775. var BABYLON;
  65776. (function (BABYLON) {
  65777. // Unique ID when we import meshes from Babylon to CSG
  65778. var currentCSGMeshId = 0;
  65779. // # class Vertex
  65780. // Represents a vertex of a polygon. Use your own vertex class instead of this
  65781. // one to provide additional features like texture coordinates and vertex
  65782. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  65783. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  65784. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  65785. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  65786. // is not used anywhere else.
  65787. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  65788. var Vertex = /** @class */ (function () {
  65789. function Vertex(pos, normal, uv) {
  65790. this.pos = pos;
  65791. this.normal = normal;
  65792. this.uv = uv;
  65793. }
  65794. Vertex.prototype.clone = function () {
  65795. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  65796. };
  65797. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  65798. // orientation of a polygon is flipped.
  65799. Vertex.prototype.flip = function () {
  65800. this.normal = this.normal.scale(-1);
  65801. };
  65802. // Create a new vertex between this vertex and `other` by linearly
  65803. // interpolating all properties using a parameter of `t`. Subclasses should
  65804. // override this to interpolate additional properties.
  65805. Vertex.prototype.interpolate = function (other, t) {
  65806. 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));
  65807. };
  65808. return Vertex;
  65809. }());
  65810. // # class Plane
  65811. // Represents a plane in 3D space.
  65812. var Plane = /** @class */ (function () {
  65813. function Plane(normal, w) {
  65814. this.normal = normal;
  65815. this.w = w;
  65816. }
  65817. Plane.FromPoints = function (a, b, c) {
  65818. var v0 = c.subtract(a);
  65819. var v1 = b.subtract(a);
  65820. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  65821. return null;
  65822. }
  65823. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  65824. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  65825. };
  65826. Plane.prototype.clone = function () {
  65827. return new Plane(this.normal.clone(), this.w);
  65828. };
  65829. Plane.prototype.flip = function () {
  65830. this.normal.scaleInPlace(-1);
  65831. this.w = -this.w;
  65832. };
  65833. // Split `polygon` by this plane if needed, then put the polygon or polygon
  65834. // fragments in the appropriate lists. Coplanar polygons go into either
  65835. // `coplanarFront` or `coplanarBack` depending on their orientation with
  65836. // respect to this plane. Polygons in front or in back of this plane go into
  65837. // either `front` or `back`.
  65838. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  65839. var COPLANAR = 0;
  65840. var FRONT = 1;
  65841. var BACK = 2;
  65842. var SPANNING = 3;
  65843. // Classify each point as well as the entire polygon into one of the above
  65844. // four classes.
  65845. var polygonType = 0;
  65846. var types = [];
  65847. var i;
  65848. var t;
  65849. for (i = 0; i < polygon.vertices.length; i++) {
  65850. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  65851. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  65852. polygonType |= type;
  65853. types.push(type);
  65854. }
  65855. // Put the polygon in the correct list, splitting it when necessary.
  65856. switch (polygonType) {
  65857. case COPLANAR:
  65858. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  65859. break;
  65860. case FRONT:
  65861. front.push(polygon);
  65862. break;
  65863. case BACK:
  65864. back.push(polygon);
  65865. break;
  65866. case SPANNING:
  65867. var f = [], b = [];
  65868. for (i = 0; i < polygon.vertices.length; i++) {
  65869. var j = (i + 1) % polygon.vertices.length;
  65870. var ti = types[i], tj = types[j];
  65871. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  65872. if (ti !== BACK)
  65873. f.push(vi);
  65874. if (ti !== FRONT)
  65875. b.push(ti !== BACK ? vi.clone() : vi);
  65876. if ((ti | tj) === SPANNING) {
  65877. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  65878. var v = vi.interpolate(vj, t);
  65879. f.push(v);
  65880. b.push(v.clone());
  65881. }
  65882. }
  65883. var poly;
  65884. if (f.length >= 3) {
  65885. poly = new Polygon(f, polygon.shared);
  65886. if (poly.plane)
  65887. front.push(poly);
  65888. }
  65889. if (b.length >= 3) {
  65890. poly = new Polygon(b, polygon.shared);
  65891. if (poly.plane)
  65892. back.push(poly);
  65893. }
  65894. break;
  65895. }
  65896. };
  65897. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  65898. // point is on the plane.
  65899. Plane.EPSILON = 1e-5;
  65900. return Plane;
  65901. }());
  65902. // # class Polygon
  65903. // Represents a convex polygon. The vertices used to initialize a polygon must
  65904. // be coplanar and form a convex loop.
  65905. //
  65906. // Each convex polygon has a `shared` property, which is shared between all
  65907. // polygons that are clones of each other or were split from the same polygon.
  65908. // This can be used to define per-polygon properties (such as surface color).
  65909. var Polygon = /** @class */ (function () {
  65910. function Polygon(vertices, shared) {
  65911. this.vertices = vertices;
  65912. this.shared = shared;
  65913. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  65914. }
  65915. Polygon.prototype.clone = function () {
  65916. var vertices = this.vertices.map(function (v) { return v.clone(); });
  65917. return new Polygon(vertices, this.shared);
  65918. };
  65919. Polygon.prototype.flip = function () {
  65920. this.vertices.reverse().map(function (v) { v.flip(); });
  65921. this.plane.flip();
  65922. };
  65923. return Polygon;
  65924. }());
  65925. // # class Node
  65926. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  65927. // by picking a polygon to split along. That polygon (and all other coplanar
  65928. // polygons) are added directly to that node and the other polygons are added to
  65929. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  65930. // no distinction between internal and leaf nodes.
  65931. var Node = /** @class */ (function () {
  65932. function Node(polygons) {
  65933. this.plane = null;
  65934. this.front = null;
  65935. this.back = null;
  65936. this.polygons = new Array();
  65937. if (polygons) {
  65938. this.build(polygons);
  65939. }
  65940. }
  65941. Node.prototype.clone = function () {
  65942. var node = new Node();
  65943. node.plane = this.plane && this.plane.clone();
  65944. node.front = this.front && this.front.clone();
  65945. node.back = this.back && this.back.clone();
  65946. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  65947. return node;
  65948. };
  65949. // Convert solid space to empty space and empty space to solid space.
  65950. Node.prototype.invert = function () {
  65951. for (var i = 0; i < this.polygons.length; i++) {
  65952. this.polygons[i].flip();
  65953. }
  65954. if (this.plane) {
  65955. this.plane.flip();
  65956. }
  65957. if (this.front) {
  65958. this.front.invert();
  65959. }
  65960. if (this.back) {
  65961. this.back.invert();
  65962. }
  65963. var temp = this.front;
  65964. this.front = this.back;
  65965. this.back = temp;
  65966. };
  65967. // Recursively remove all polygons in `polygons` that are inside this BSP
  65968. // tree.
  65969. Node.prototype.clipPolygons = function (polygons) {
  65970. if (!this.plane)
  65971. return polygons.slice();
  65972. var front = new Array(), back = new Array();
  65973. for (var i = 0; i < polygons.length; i++) {
  65974. this.plane.splitPolygon(polygons[i], front, back, front, back);
  65975. }
  65976. if (this.front) {
  65977. front = this.front.clipPolygons(front);
  65978. }
  65979. if (this.back) {
  65980. back = this.back.clipPolygons(back);
  65981. }
  65982. else {
  65983. back = [];
  65984. }
  65985. return front.concat(back);
  65986. };
  65987. // Remove all polygons in this BSP tree that are inside the other BSP tree
  65988. // `bsp`.
  65989. Node.prototype.clipTo = function (bsp) {
  65990. this.polygons = bsp.clipPolygons(this.polygons);
  65991. if (this.front)
  65992. this.front.clipTo(bsp);
  65993. if (this.back)
  65994. this.back.clipTo(bsp);
  65995. };
  65996. // Return a list of all polygons in this BSP tree.
  65997. Node.prototype.allPolygons = function () {
  65998. var polygons = this.polygons.slice();
  65999. if (this.front)
  66000. polygons = polygons.concat(this.front.allPolygons());
  66001. if (this.back)
  66002. polygons = polygons.concat(this.back.allPolygons());
  66003. return polygons;
  66004. };
  66005. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  66006. // new polygons are filtered down to the bottom of the tree and become new
  66007. // nodes there. Each set of polygons is partitioned using the first polygon
  66008. // (no heuristic is used to pick a good split).
  66009. Node.prototype.build = function (polygons) {
  66010. if (!polygons.length)
  66011. return;
  66012. if (!this.plane)
  66013. this.plane = polygons[0].plane.clone();
  66014. var front = new Array(), back = new Array();
  66015. for (var i = 0; i < polygons.length; i++) {
  66016. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  66017. }
  66018. if (front.length) {
  66019. if (!this.front)
  66020. this.front = new Node();
  66021. this.front.build(front);
  66022. }
  66023. if (back.length) {
  66024. if (!this.back)
  66025. this.back = new Node();
  66026. this.back.build(back);
  66027. }
  66028. };
  66029. return Node;
  66030. }());
  66031. var CSG = /** @class */ (function () {
  66032. function CSG() {
  66033. this.polygons = new Array();
  66034. }
  66035. // Convert BABYLON.Mesh to BABYLON.CSG
  66036. CSG.FromMesh = function (mesh) {
  66037. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  66038. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  66039. if (mesh instanceof BABYLON.Mesh) {
  66040. mesh.computeWorldMatrix(true);
  66041. matrix = mesh.getWorldMatrix();
  66042. meshPosition = mesh.position.clone();
  66043. meshRotation = mesh.rotation.clone();
  66044. if (mesh.rotationQuaternion) {
  66045. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  66046. }
  66047. meshScaling = mesh.scaling.clone();
  66048. }
  66049. else {
  66050. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  66051. }
  66052. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  66053. var subMeshes = mesh.subMeshes;
  66054. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  66055. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  66056. vertices = [];
  66057. for (var j = 0; j < 3; j++) {
  66058. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  66059. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  66060. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  66061. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  66062. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  66063. vertex = new Vertex(position, normal, uv);
  66064. vertices.push(vertex);
  66065. }
  66066. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  66067. // To handle the case of degenerated triangle
  66068. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  66069. if (polygon.plane)
  66070. polygons.push(polygon);
  66071. }
  66072. }
  66073. var csg = CSG.FromPolygons(polygons);
  66074. csg.matrix = matrix;
  66075. csg.position = meshPosition;
  66076. csg.rotation = meshRotation;
  66077. csg.scaling = meshScaling;
  66078. csg.rotationQuaternion = meshRotationQuaternion;
  66079. currentCSGMeshId++;
  66080. return csg;
  66081. };
  66082. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  66083. CSG.FromPolygons = function (polygons) {
  66084. var csg = new CSG();
  66085. csg.polygons = polygons;
  66086. return csg;
  66087. };
  66088. CSG.prototype.clone = function () {
  66089. var csg = new CSG();
  66090. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  66091. csg.copyTransformAttributes(this);
  66092. return csg;
  66093. };
  66094. CSG.prototype.union = function (csg) {
  66095. var a = new Node(this.clone().polygons);
  66096. var b = new Node(csg.clone().polygons);
  66097. a.clipTo(b);
  66098. b.clipTo(a);
  66099. b.invert();
  66100. b.clipTo(a);
  66101. b.invert();
  66102. a.build(b.allPolygons());
  66103. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  66104. };
  66105. CSG.prototype.unionInPlace = function (csg) {
  66106. var a = new Node(this.polygons);
  66107. var b = new Node(csg.polygons);
  66108. a.clipTo(b);
  66109. b.clipTo(a);
  66110. b.invert();
  66111. b.clipTo(a);
  66112. b.invert();
  66113. a.build(b.allPolygons());
  66114. this.polygons = a.allPolygons();
  66115. };
  66116. CSG.prototype.subtract = function (csg) {
  66117. var a = new Node(this.clone().polygons);
  66118. var b = new Node(csg.clone().polygons);
  66119. a.invert();
  66120. a.clipTo(b);
  66121. b.clipTo(a);
  66122. b.invert();
  66123. b.clipTo(a);
  66124. b.invert();
  66125. a.build(b.allPolygons());
  66126. a.invert();
  66127. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  66128. };
  66129. CSG.prototype.subtractInPlace = function (csg) {
  66130. var a = new Node(this.polygons);
  66131. var b = new Node(csg.polygons);
  66132. a.invert();
  66133. a.clipTo(b);
  66134. b.clipTo(a);
  66135. b.invert();
  66136. b.clipTo(a);
  66137. b.invert();
  66138. a.build(b.allPolygons());
  66139. a.invert();
  66140. this.polygons = a.allPolygons();
  66141. };
  66142. CSG.prototype.intersect = function (csg) {
  66143. var a = new Node(this.clone().polygons);
  66144. var b = new Node(csg.clone().polygons);
  66145. a.invert();
  66146. b.clipTo(a);
  66147. b.invert();
  66148. a.clipTo(b);
  66149. b.clipTo(a);
  66150. a.build(b.allPolygons());
  66151. a.invert();
  66152. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  66153. };
  66154. CSG.prototype.intersectInPlace = function (csg) {
  66155. var a = new Node(this.polygons);
  66156. var b = new Node(csg.polygons);
  66157. a.invert();
  66158. b.clipTo(a);
  66159. b.invert();
  66160. a.clipTo(b);
  66161. b.clipTo(a);
  66162. a.build(b.allPolygons());
  66163. a.invert();
  66164. this.polygons = a.allPolygons();
  66165. };
  66166. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  66167. // not modified.
  66168. CSG.prototype.inverse = function () {
  66169. var csg = this.clone();
  66170. csg.inverseInPlace();
  66171. return csg;
  66172. };
  66173. CSG.prototype.inverseInPlace = function () {
  66174. this.polygons.map(function (p) { p.flip(); });
  66175. };
  66176. // This is used to keep meshes transformations so they can be restored
  66177. // when we build back a Babylon Mesh
  66178. // NB : All CSG operations are performed in world coordinates
  66179. CSG.prototype.copyTransformAttributes = function (csg) {
  66180. this.matrix = csg.matrix;
  66181. this.position = csg.position;
  66182. this.rotation = csg.rotation;
  66183. this.scaling = csg.scaling;
  66184. this.rotationQuaternion = csg.rotationQuaternion;
  66185. return this;
  66186. };
  66187. // Build Raw mesh from CSG
  66188. // Coordinates here are in world space
  66189. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  66190. var matrix = this.matrix.clone();
  66191. matrix.invert();
  66192. 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;
  66193. if (keepSubMeshes) {
  66194. // Sort Polygons, since subMeshes are indices range
  66195. polygons.sort(function (a, b) {
  66196. if (a.shared.meshId === b.shared.meshId) {
  66197. return a.shared.subMeshId - b.shared.subMeshId;
  66198. }
  66199. else {
  66200. return a.shared.meshId - b.shared.meshId;
  66201. }
  66202. });
  66203. }
  66204. for (var i = 0, il = polygons.length; i < il; i++) {
  66205. polygon = polygons[i];
  66206. // Building SubMeshes
  66207. if (!subMesh_dict[polygon.shared.meshId]) {
  66208. subMesh_dict[polygon.shared.meshId] = {};
  66209. }
  66210. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  66211. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  66212. indexStart: +Infinity,
  66213. indexEnd: -Infinity,
  66214. materialIndex: polygon.shared.materialIndex
  66215. };
  66216. }
  66217. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  66218. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  66219. polygonIndices[0] = 0;
  66220. polygonIndices[1] = j - 1;
  66221. polygonIndices[2] = j;
  66222. for (var k = 0; k < 3; k++) {
  66223. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  66224. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  66225. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  66226. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  66227. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  66228. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  66229. // Check if 2 points can be merged
  66230. if (!(typeof vertex_idx !== 'undefined' &&
  66231. normals[vertex_idx * 3] === localNormal.x &&
  66232. normals[vertex_idx * 3 + 1] === localNormal.y &&
  66233. normals[vertex_idx * 3 + 2] === localNormal.z &&
  66234. uvs[vertex_idx * 2] === uv.x &&
  66235. uvs[vertex_idx * 2 + 1] === uv.y)) {
  66236. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  66237. uvs.push(uv.x, uv.y);
  66238. normals.push(normal.x, normal.y, normal.z);
  66239. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  66240. }
  66241. indices.push(vertex_idx);
  66242. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  66243. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  66244. currentIndex++;
  66245. }
  66246. }
  66247. }
  66248. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  66249. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  66250. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  66251. mesh.setIndices(indices, null);
  66252. if (keepSubMeshes) {
  66253. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  66254. var materialIndexOffset = 0, materialMaxIndex;
  66255. mesh.subMeshes = new Array();
  66256. for (var m in subMesh_dict) {
  66257. materialMaxIndex = -1;
  66258. for (var sm in subMesh_dict[m]) {
  66259. subMesh_obj = subMesh_dict[m][sm];
  66260. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  66261. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  66262. }
  66263. materialIndexOffset += ++materialMaxIndex;
  66264. }
  66265. }
  66266. return mesh;
  66267. };
  66268. // Build Mesh from CSG taking material and transforms into account
  66269. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  66270. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  66271. mesh.material = material;
  66272. mesh.position.copyFrom(this.position);
  66273. mesh.rotation.copyFrom(this.rotation);
  66274. if (this.rotationQuaternion) {
  66275. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  66276. }
  66277. mesh.scaling.copyFrom(this.scaling);
  66278. mesh.computeWorldMatrix(true);
  66279. return mesh;
  66280. };
  66281. return CSG;
  66282. }());
  66283. BABYLON.CSG = CSG;
  66284. })(BABYLON || (BABYLON = {}));
  66285. //# sourceMappingURL=babylon.csg.js.map
  66286. var BABYLON;
  66287. (function (BABYLON) {
  66288. var LensFlare = /** @class */ (function () {
  66289. function LensFlare(size, position, color, imgUrl, system) {
  66290. this.size = size;
  66291. this.position = position;
  66292. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  66293. this.color = color || new BABYLON.Color3(1, 1, 1);
  66294. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  66295. this._system = system;
  66296. system.lensFlares.push(this);
  66297. }
  66298. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  66299. return new LensFlare(size, position, color, imgUrl, system);
  66300. };
  66301. LensFlare.prototype.dispose = function () {
  66302. if (this.texture) {
  66303. this.texture.dispose();
  66304. }
  66305. // Remove from scene
  66306. var index = this._system.lensFlares.indexOf(this);
  66307. this._system.lensFlares.splice(index, 1);
  66308. };
  66309. ;
  66310. return LensFlare;
  66311. }());
  66312. BABYLON.LensFlare = LensFlare;
  66313. })(BABYLON || (BABYLON = {}));
  66314. //# sourceMappingURL=babylon.lensFlare.js.map
  66315. var BABYLON;
  66316. (function (BABYLON) {
  66317. var LensFlareSystem = /** @class */ (function () {
  66318. function LensFlareSystem(name, emitter, scene) {
  66319. this.name = name;
  66320. this.lensFlares = new Array();
  66321. this.borderLimit = 300;
  66322. this.viewportBorder = 0;
  66323. this.layerMask = 0x0FFFFFFF;
  66324. this._vertexBuffers = {};
  66325. this._isEnabled = true;
  66326. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  66327. this._emitter = emitter;
  66328. this.id = name;
  66329. scene.lensFlareSystems.push(this);
  66330. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  66331. var engine = scene.getEngine();
  66332. // VBO
  66333. var vertices = [];
  66334. vertices.push(1, 1);
  66335. vertices.push(-1, 1);
  66336. vertices.push(-1, -1);
  66337. vertices.push(1, -1);
  66338. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  66339. // Indices
  66340. var indices = [];
  66341. indices.push(0);
  66342. indices.push(1);
  66343. indices.push(2);
  66344. indices.push(0);
  66345. indices.push(2);
  66346. indices.push(3);
  66347. this._indexBuffer = engine.createIndexBuffer(indices);
  66348. // Effects
  66349. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  66350. }
  66351. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  66352. get: function () {
  66353. return this._isEnabled;
  66354. },
  66355. set: function (value) {
  66356. this._isEnabled = value;
  66357. },
  66358. enumerable: true,
  66359. configurable: true
  66360. });
  66361. LensFlareSystem.prototype.getScene = function () {
  66362. return this._scene;
  66363. };
  66364. LensFlareSystem.prototype.getEmitter = function () {
  66365. return this._emitter;
  66366. };
  66367. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  66368. this._emitter = newEmitter;
  66369. };
  66370. LensFlareSystem.prototype.getEmitterPosition = function () {
  66371. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  66372. };
  66373. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  66374. var position = this.getEmitterPosition();
  66375. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  66376. this._positionX = position.x;
  66377. this._positionY = position.y;
  66378. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  66379. if (this.viewportBorder > 0) {
  66380. globalViewport.x -= this.viewportBorder;
  66381. globalViewport.y -= this.viewportBorder;
  66382. globalViewport.width += this.viewportBorder * 2;
  66383. globalViewport.height += this.viewportBorder * 2;
  66384. position.x += this.viewportBorder;
  66385. position.y += this.viewportBorder;
  66386. this._positionX += this.viewportBorder;
  66387. this._positionY += this.viewportBorder;
  66388. }
  66389. if (position.z > 0) {
  66390. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  66391. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  66392. return true;
  66393. }
  66394. return true;
  66395. }
  66396. return false;
  66397. };
  66398. LensFlareSystem.prototype._isVisible = function () {
  66399. if (!this._isEnabled || !this._scene.activeCamera) {
  66400. return false;
  66401. }
  66402. var emitterPosition = this.getEmitterPosition();
  66403. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  66404. var distance = direction.length();
  66405. direction.normalize();
  66406. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  66407. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  66408. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  66409. };
  66410. LensFlareSystem.prototype.render = function () {
  66411. if (!this._effect.isReady() || !this._scene.activeCamera)
  66412. return false;
  66413. var engine = this._scene.getEngine();
  66414. var viewport = this._scene.activeCamera.viewport;
  66415. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  66416. // Position
  66417. if (!this.computeEffectivePosition(globalViewport)) {
  66418. return false;
  66419. }
  66420. // Visibility
  66421. if (!this._isVisible()) {
  66422. return false;
  66423. }
  66424. // Intensity
  66425. var awayX;
  66426. var awayY;
  66427. if (this._positionX < this.borderLimit + globalViewport.x) {
  66428. awayX = this.borderLimit + globalViewport.x - this._positionX;
  66429. }
  66430. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  66431. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  66432. }
  66433. else {
  66434. awayX = 0;
  66435. }
  66436. if (this._positionY < this.borderLimit + globalViewport.y) {
  66437. awayY = this.borderLimit + globalViewport.y - this._positionY;
  66438. }
  66439. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  66440. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  66441. }
  66442. else {
  66443. awayY = 0;
  66444. }
  66445. var away = (awayX > awayY) ? awayX : awayY;
  66446. away -= this.viewportBorder;
  66447. if (away > this.borderLimit) {
  66448. away = this.borderLimit;
  66449. }
  66450. var intensity = 1.0 - (away / this.borderLimit);
  66451. if (intensity < 0) {
  66452. return false;
  66453. }
  66454. if (intensity > 1.0) {
  66455. intensity = 1.0;
  66456. }
  66457. if (this.viewportBorder > 0) {
  66458. globalViewport.x += this.viewportBorder;
  66459. globalViewport.y += this.viewportBorder;
  66460. globalViewport.width -= this.viewportBorder * 2;
  66461. globalViewport.height -= this.viewportBorder * 2;
  66462. this._positionX -= this.viewportBorder;
  66463. this._positionY -= this.viewportBorder;
  66464. }
  66465. // Position
  66466. var centerX = globalViewport.x + globalViewport.width / 2;
  66467. var centerY = globalViewport.y + globalViewport.height / 2;
  66468. var distX = centerX - this._positionX;
  66469. var distY = centerY - this._positionY;
  66470. // Effects
  66471. engine.enableEffect(this._effect);
  66472. engine.setState(false);
  66473. engine.setDepthBuffer(false);
  66474. // VBOs
  66475. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  66476. // Flares
  66477. for (var index = 0; index < this.lensFlares.length; index++) {
  66478. var flare = this.lensFlares[index];
  66479. engine.setAlphaMode(flare.alphaMode);
  66480. var x = centerX - (distX * flare.position);
  66481. var y = centerY - (distY * flare.position);
  66482. var cw = flare.size;
  66483. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  66484. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  66485. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  66486. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  66487. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  66488. // Texture
  66489. this._effect.setTexture("textureSampler", flare.texture);
  66490. // Color
  66491. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  66492. // Draw order
  66493. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  66494. }
  66495. engine.setDepthBuffer(true);
  66496. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  66497. return true;
  66498. };
  66499. LensFlareSystem.prototype.dispose = function () {
  66500. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66501. if (vertexBuffer) {
  66502. vertexBuffer.dispose();
  66503. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  66504. }
  66505. if (this._indexBuffer) {
  66506. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  66507. this._indexBuffer = null;
  66508. }
  66509. while (this.lensFlares.length) {
  66510. this.lensFlares[0].dispose();
  66511. }
  66512. // Remove from scene
  66513. var index = this._scene.lensFlareSystems.indexOf(this);
  66514. this._scene.lensFlareSystems.splice(index, 1);
  66515. };
  66516. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  66517. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  66518. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  66519. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  66520. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  66521. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  66522. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  66523. var parsedFlare = parsedLensFlareSystem.flares[index];
  66524. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  66525. }
  66526. return lensFlareSystem;
  66527. };
  66528. LensFlareSystem.prototype.serialize = function () {
  66529. var serializationObject = {};
  66530. serializationObject.id = this.id;
  66531. serializationObject.name = this.name;
  66532. serializationObject.emitterId = this.getEmitter().id;
  66533. serializationObject.borderLimit = this.borderLimit;
  66534. serializationObject.flares = [];
  66535. for (var index = 0; index < this.lensFlares.length; index++) {
  66536. var flare = this.lensFlares[index];
  66537. serializationObject.flares.push({
  66538. size: flare.size,
  66539. position: flare.position,
  66540. color: flare.color.asArray(),
  66541. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  66542. });
  66543. }
  66544. return serializationObject;
  66545. };
  66546. return LensFlareSystem;
  66547. }());
  66548. BABYLON.LensFlareSystem = LensFlareSystem;
  66549. })(BABYLON || (BABYLON = {}));
  66550. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  66551. var BABYLON;
  66552. (function (BABYLON) {
  66553. /**
  66554. * This is a holder class for the physics joint created by the physics plugin.
  66555. * It holds a set of functions to control the underlying joint.
  66556. */
  66557. var PhysicsJoint = /** @class */ (function () {
  66558. function PhysicsJoint(type, jointData) {
  66559. this.type = type;
  66560. this.jointData = jointData;
  66561. jointData.nativeParams = jointData.nativeParams || {};
  66562. }
  66563. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  66564. get: function () {
  66565. return this._physicsJoint;
  66566. },
  66567. set: function (newJoint) {
  66568. if (this._physicsJoint) {
  66569. //remove from the wolrd
  66570. }
  66571. this._physicsJoint = newJoint;
  66572. },
  66573. enumerable: true,
  66574. configurable: true
  66575. });
  66576. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  66577. set: function (physicsPlugin) {
  66578. this._physicsPlugin = physicsPlugin;
  66579. },
  66580. enumerable: true,
  66581. configurable: true
  66582. });
  66583. /**
  66584. * Execute a function that is physics-plugin specific.
  66585. * @param {Function} func the function that will be executed.
  66586. * It accepts two parameters: the physics world and the physics joint.
  66587. */
  66588. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  66589. func(this._physicsPlugin.world, this._physicsJoint);
  66590. };
  66591. //TODO check if the native joints are the same
  66592. //Joint Types
  66593. PhysicsJoint.DistanceJoint = 0;
  66594. PhysicsJoint.HingeJoint = 1;
  66595. PhysicsJoint.BallAndSocketJoint = 2;
  66596. PhysicsJoint.WheelJoint = 3;
  66597. PhysicsJoint.SliderJoint = 4;
  66598. //OIMO
  66599. PhysicsJoint.PrismaticJoint = 5;
  66600. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  66601. PhysicsJoint.UniversalJoint = 6;
  66602. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  66603. //Cannon
  66604. //Similar to a Ball-Joint. Different in params
  66605. PhysicsJoint.PointToPointJoint = 8;
  66606. //Cannon only at the moment
  66607. PhysicsJoint.SpringJoint = 9;
  66608. PhysicsJoint.LockJoint = 10;
  66609. return PhysicsJoint;
  66610. }());
  66611. BABYLON.PhysicsJoint = PhysicsJoint;
  66612. /**
  66613. * A class representing a physics distance joint.
  66614. */
  66615. var DistanceJoint = /** @class */ (function (_super) {
  66616. __extends(DistanceJoint, _super);
  66617. function DistanceJoint(jointData) {
  66618. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  66619. }
  66620. /**
  66621. * Update the predefined distance.
  66622. */
  66623. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  66624. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  66625. };
  66626. return DistanceJoint;
  66627. }(PhysicsJoint));
  66628. BABYLON.DistanceJoint = DistanceJoint;
  66629. var MotorEnabledJoint = /** @class */ (function (_super) {
  66630. __extends(MotorEnabledJoint, _super);
  66631. function MotorEnabledJoint(type, jointData) {
  66632. return _super.call(this, type, jointData) || this;
  66633. }
  66634. /**
  66635. * Set the motor values.
  66636. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66637. * @param {number} force the force to apply
  66638. * @param {number} maxForce max force for this motor.
  66639. */
  66640. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  66641. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  66642. };
  66643. /**
  66644. * Set the motor's limits.
  66645. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66646. */
  66647. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  66648. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  66649. };
  66650. return MotorEnabledJoint;
  66651. }(PhysicsJoint));
  66652. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  66653. /**
  66654. * This class represents a single hinge physics joint
  66655. */
  66656. var HingeJoint = /** @class */ (function (_super) {
  66657. __extends(HingeJoint, _super);
  66658. function HingeJoint(jointData) {
  66659. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  66660. }
  66661. /**
  66662. * Set the motor values.
  66663. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66664. * @param {number} force the force to apply
  66665. * @param {number} maxForce max force for this motor.
  66666. */
  66667. HingeJoint.prototype.setMotor = function (force, maxForce) {
  66668. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  66669. };
  66670. /**
  66671. * Set the motor's limits.
  66672. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66673. */
  66674. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  66675. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  66676. };
  66677. return HingeJoint;
  66678. }(MotorEnabledJoint));
  66679. BABYLON.HingeJoint = HingeJoint;
  66680. /**
  66681. * This class represents a dual hinge physics joint (same as wheel joint)
  66682. */
  66683. var Hinge2Joint = /** @class */ (function (_super) {
  66684. __extends(Hinge2Joint, _super);
  66685. function Hinge2Joint(jointData) {
  66686. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  66687. }
  66688. /**
  66689. * Set the motor values.
  66690. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66691. * @param {number} force the force to apply
  66692. * @param {number} maxForce max force for this motor.
  66693. * @param {motorIndex} the motor's index, 0 or 1.
  66694. */
  66695. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  66696. if (motorIndex === void 0) { motorIndex = 0; }
  66697. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  66698. };
  66699. /**
  66700. * Set the motor limits.
  66701. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66702. * @param {number} upperLimit the upper limit
  66703. * @param {number} lowerLimit lower limit
  66704. * @param {motorIndex} the motor's index, 0 or 1.
  66705. */
  66706. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  66707. if (motorIndex === void 0) { motorIndex = 0; }
  66708. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  66709. };
  66710. return Hinge2Joint;
  66711. }(MotorEnabledJoint));
  66712. BABYLON.Hinge2Joint = Hinge2Joint;
  66713. })(BABYLON || (BABYLON = {}));
  66714. //# sourceMappingURL=babylon.physicsJoint.js.map
  66715. var BABYLON;
  66716. (function (BABYLON) {
  66717. var PhysicsImpostor = /** @class */ (function () {
  66718. function PhysicsImpostor(object, type, _options, _scene) {
  66719. if (_options === void 0) { _options = { mass: 0 }; }
  66720. var _this = this;
  66721. this.object = object;
  66722. this.type = type;
  66723. this._options = _options;
  66724. this._scene = _scene;
  66725. this._bodyUpdateRequired = false;
  66726. this._onBeforePhysicsStepCallbacks = new Array();
  66727. this._onAfterPhysicsStepCallbacks = new Array();
  66728. this._onPhysicsCollideCallbacks = [];
  66729. this._deltaPosition = BABYLON.Vector3.Zero();
  66730. this._isDisposed = false;
  66731. //temp variables for parent rotation calculations
  66732. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  66733. this._tmpQuat = new BABYLON.Quaternion();
  66734. this._tmpQuat2 = new BABYLON.Quaternion();
  66735. /**
  66736. * this function is executed by the physics engine.
  66737. */
  66738. this.beforeStep = function () {
  66739. if (!_this._physicsEngine) {
  66740. return;
  66741. }
  66742. _this.object.translate(_this._deltaPosition, -1);
  66743. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  66744. _this.object.computeWorldMatrix(false);
  66745. if (_this.object.parent && _this.object.rotationQuaternion) {
  66746. _this.getParentsRotation();
  66747. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  66748. }
  66749. else {
  66750. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  66751. }
  66752. if (!_this._options.disableBidirectionalTransformation) {
  66753. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  66754. }
  66755. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  66756. func(_this);
  66757. });
  66758. };
  66759. /**
  66760. * this function is executed by the physics engine.
  66761. */
  66762. this.afterStep = function () {
  66763. if (!_this._physicsEngine) {
  66764. return;
  66765. }
  66766. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  66767. func(_this);
  66768. });
  66769. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  66770. // object has now its world rotation. needs to be converted to local.
  66771. if (_this.object.parent && _this.object.rotationQuaternion) {
  66772. _this.getParentsRotation();
  66773. _this._tmpQuat.conjugateInPlace();
  66774. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  66775. }
  66776. // take the position set and make it the absolute position of this object.
  66777. _this.object.setAbsolutePosition(_this.object.position);
  66778. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  66779. _this.object.translate(_this._deltaPosition, 1);
  66780. };
  66781. /**
  66782. * Legacy collision detection event support
  66783. */
  66784. this.onCollideEvent = null;
  66785. //event and body object due to cannon's event-based architecture.
  66786. this.onCollide = function (e) {
  66787. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  66788. return;
  66789. }
  66790. if (!_this._physicsEngine) {
  66791. return;
  66792. }
  66793. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  66794. if (otherImpostor) {
  66795. // Legacy collision detection event support
  66796. if (_this.onCollideEvent) {
  66797. _this.onCollideEvent(_this, otherImpostor);
  66798. }
  66799. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  66800. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  66801. }).forEach(function (obj) {
  66802. obj.callback(_this, otherImpostor);
  66803. });
  66804. }
  66805. };
  66806. //sanity check!
  66807. if (!this.object) {
  66808. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  66809. return;
  66810. }
  66811. //legacy support for old syntax.
  66812. if (!this._scene && object.getScene) {
  66813. this._scene = object.getScene();
  66814. }
  66815. if (!this._scene) {
  66816. return;
  66817. }
  66818. this._physicsEngine = this._scene.getPhysicsEngine();
  66819. if (!this._physicsEngine) {
  66820. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  66821. }
  66822. else {
  66823. //set the object's quaternion, if not set
  66824. if (!this.object.rotationQuaternion) {
  66825. if (this.object.rotation) {
  66826. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  66827. }
  66828. else {
  66829. this.object.rotationQuaternion = new BABYLON.Quaternion();
  66830. }
  66831. }
  66832. //default options params
  66833. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  66834. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  66835. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  66836. this._joints = [];
  66837. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  66838. if (!this.object.parent || this._options.ignoreParent) {
  66839. this._init();
  66840. }
  66841. else if (this.object.parent.physicsImpostor) {
  66842. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  66843. }
  66844. }
  66845. }
  66846. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  66847. get: function () {
  66848. return this._isDisposed;
  66849. },
  66850. enumerable: true,
  66851. configurable: true
  66852. });
  66853. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  66854. get: function () {
  66855. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  66856. },
  66857. set: function (value) {
  66858. this.setMass(value);
  66859. },
  66860. enumerable: true,
  66861. configurable: true
  66862. });
  66863. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  66864. get: function () {
  66865. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  66866. },
  66867. set: function (value) {
  66868. if (!this._physicsEngine) {
  66869. return;
  66870. }
  66871. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  66872. },
  66873. enumerable: true,
  66874. configurable: true
  66875. });
  66876. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  66877. get: function () {
  66878. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  66879. },
  66880. set: function (value) {
  66881. if (!this._physicsEngine) {
  66882. return;
  66883. }
  66884. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  66885. },
  66886. enumerable: true,
  66887. configurable: true
  66888. });
  66889. /**
  66890. * This function will completly initialize this impostor.
  66891. * It will create a new body - but only if this mesh has no parent.
  66892. * If it has, this impostor will not be used other than to define the impostor
  66893. * of the child mesh.
  66894. */
  66895. PhysicsImpostor.prototype._init = function () {
  66896. if (!this._physicsEngine) {
  66897. return;
  66898. }
  66899. this._physicsEngine.removeImpostor(this);
  66900. this.physicsBody = null;
  66901. this._parent = this._parent || this._getPhysicsParent();
  66902. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  66903. this._physicsEngine.addImpostor(this);
  66904. }
  66905. };
  66906. PhysicsImpostor.prototype._getPhysicsParent = function () {
  66907. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  66908. var parentMesh = this.object.parent;
  66909. return parentMesh.physicsImpostor;
  66910. }
  66911. return null;
  66912. };
  66913. /**
  66914. * Should a new body be generated.
  66915. */
  66916. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  66917. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  66918. };
  66919. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  66920. this.forceUpdate();
  66921. };
  66922. /**
  66923. * Force a regeneration of this or the parent's impostor's body.
  66924. * Use under cautious - This will remove all joints already implemented.
  66925. */
  66926. PhysicsImpostor.prototype.forceUpdate = function () {
  66927. this._init();
  66928. if (this.parent && !this._options.ignoreParent) {
  66929. this.parent.forceUpdate();
  66930. }
  66931. };
  66932. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  66933. /*public get mesh(): AbstractMesh {
  66934. return this._mesh;
  66935. }*/
  66936. /**
  66937. * Gets the body that holds this impostor. Either its own, or its parent.
  66938. */
  66939. get: function () {
  66940. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  66941. },
  66942. /**
  66943. * Set the physics body. Used mainly by the physics engine/plugin
  66944. */
  66945. set: function (physicsBody) {
  66946. if (this._physicsBody && this._physicsEngine) {
  66947. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  66948. }
  66949. this._physicsBody = physicsBody;
  66950. this.resetUpdateFlags();
  66951. },
  66952. enumerable: true,
  66953. configurable: true
  66954. });
  66955. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  66956. get: function () {
  66957. return !this._options.ignoreParent && this._parent ? this._parent : null;
  66958. },
  66959. set: function (value) {
  66960. this._parent = value;
  66961. },
  66962. enumerable: true,
  66963. configurable: true
  66964. });
  66965. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  66966. this._bodyUpdateRequired = false;
  66967. };
  66968. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  66969. if (this.object.getBoundingInfo) {
  66970. var q = this.object.rotationQuaternion;
  66971. //reset rotation
  66972. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  66973. //calculate the world matrix with no rotation
  66974. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  66975. var boundingInfo = this.object.getBoundingInfo();
  66976. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  66977. //bring back the rotation
  66978. this.object.rotationQuaternion = q;
  66979. //calculate the world matrix with the new rotation
  66980. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  66981. return size;
  66982. }
  66983. else {
  66984. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  66985. }
  66986. };
  66987. PhysicsImpostor.prototype.getObjectCenter = function () {
  66988. if (this.object.getBoundingInfo) {
  66989. var boundingInfo = this.object.getBoundingInfo();
  66990. return boundingInfo.boundingBox.centerWorld;
  66991. }
  66992. else {
  66993. return this.object.position;
  66994. }
  66995. };
  66996. /**
  66997. * Get a specific parametes from the options parameter.
  66998. */
  66999. PhysicsImpostor.prototype.getParam = function (paramName) {
  67000. return this._options[paramName];
  67001. };
  67002. /**
  67003. * Sets a specific parameter in the options given to the physics plugin
  67004. */
  67005. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  67006. this._options[paramName] = value;
  67007. this._bodyUpdateRequired = true;
  67008. };
  67009. /**
  67010. * Specifically change the body's mass option. Won't recreate the physics body object
  67011. */
  67012. PhysicsImpostor.prototype.setMass = function (mass) {
  67013. if (this.getParam("mass") !== mass) {
  67014. this.setParam("mass", mass);
  67015. }
  67016. if (this._physicsEngine) {
  67017. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  67018. }
  67019. };
  67020. PhysicsImpostor.prototype.getLinearVelocity = function () {
  67021. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  67022. };
  67023. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  67024. if (this._physicsEngine) {
  67025. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  67026. }
  67027. };
  67028. PhysicsImpostor.prototype.getAngularVelocity = function () {
  67029. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  67030. };
  67031. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  67032. if (this._physicsEngine) {
  67033. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  67034. }
  67035. };
  67036. /**
  67037. * Execute a function with the physics plugin native code.
  67038. * Provide a function the will have two variables - the world object and the physics body object.
  67039. */
  67040. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  67041. if (this._physicsEngine) {
  67042. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  67043. }
  67044. };
  67045. /**
  67046. * Register a function that will be executed before the physics world is stepping forward.
  67047. */
  67048. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  67049. this._onBeforePhysicsStepCallbacks.push(func);
  67050. };
  67051. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  67052. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  67053. if (index > -1) {
  67054. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  67055. }
  67056. else {
  67057. BABYLON.Tools.Warn("Function to remove was not found");
  67058. }
  67059. };
  67060. /**
  67061. * Register a function that will be executed after the physics step
  67062. */
  67063. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  67064. this._onAfterPhysicsStepCallbacks.push(func);
  67065. };
  67066. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  67067. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  67068. if (index > -1) {
  67069. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  67070. }
  67071. else {
  67072. BABYLON.Tools.Warn("Function to remove was not found");
  67073. }
  67074. };
  67075. /**
  67076. * register a function that will be executed when this impostor collides against a different body.
  67077. */
  67078. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  67079. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  67080. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  67081. };
  67082. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  67083. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  67084. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  67085. if (index > -1) {
  67086. this._onPhysicsCollideCallbacks.splice(index, 1);
  67087. }
  67088. else {
  67089. BABYLON.Tools.Warn("Function to remove was not found");
  67090. }
  67091. };
  67092. PhysicsImpostor.prototype.getParentsRotation = function () {
  67093. var parent = this.object.parent;
  67094. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  67095. while (parent) {
  67096. if (parent.rotationQuaternion) {
  67097. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  67098. }
  67099. else {
  67100. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  67101. }
  67102. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  67103. parent = parent.parent;
  67104. }
  67105. return this._tmpQuat;
  67106. };
  67107. /**
  67108. * Apply a force
  67109. */
  67110. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  67111. if (this._physicsEngine) {
  67112. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  67113. }
  67114. return this;
  67115. };
  67116. /**
  67117. * Apply an impulse
  67118. */
  67119. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  67120. if (this._physicsEngine) {
  67121. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  67122. }
  67123. return this;
  67124. };
  67125. /**
  67126. * A help function to create a joint.
  67127. */
  67128. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  67129. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  67130. this.addJoint(otherImpostor, joint);
  67131. return this;
  67132. };
  67133. /**
  67134. * Add a joint to this impostor with a different impostor.
  67135. */
  67136. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  67137. this._joints.push({
  67138. otherImpostor: otherImpostor,
  67139. joint: joint
  67140. });
  67141. if (this._physicsEngine) {
  67142. this._physicsEngine.addJoint(this, otherImpostor, joint);
  67143. }
  67144. return this;
  67145. };
  67146. /**
  67147. * Will keep this body still, in a sleep mode.
  67148. */
  67149. PhysicsImpostor.prototype.sleep = function () {
  67150. if (this._physicsEngine) {
  67151. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  67152. }
  67153. return this;
  67154. };
  67155. /**
  67156. * Wake the body up.
  67157. */
  67158. PhysicsImpostor.prototype.wakeUp = function () {
  67159. if (this._physicsEngine) {
  67160. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  67161. }
  67162. return this;
  67163. };
  67164. PhysicsImpostor.prototype.clone = function (newObject) {
  67165. if (!newObject)
  67166. return null;
  67167. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  67168. };
  67169. PhysicsImpostor.prototype.dispose = function () {
  67170. var _this = this;
  67171. //no dispose if no physics engine is available.
  67172. if (!this._physicsEngine) {
  67173. return;
  67174. }
  67175. this._joints.forEach(function (j) {
  67176. if (_this._physicsEngine) {
  67177. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  67178. }
  67179. });
  67180. //dispose the physics body
  67181. this._physicsEngine.removeImpostor(this);
  67182. if (this.parent) {
  67183. this.parent.forceUpdate();
  67184. }
  67185. else {
  67186. /*this._object.getChildMeshes().forEach(function(mesh) {
  67187. if (mesh.physicsImpostor) {
  67188. if (disposeChildren) {
  67189. mesh.physicsImpostor.dispose();
  67190. mesh.physicsImpostor = null;
  67191. }
  67192. }
  67193. })*/
  67194. }
  67195. this._isDisposed = true;
  67196. };
  67197. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  67198. this._deltaPosition.copyFrom(position);
  67199. };
  67200. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  67201. if (!this._deltaRotation) {
  67202. this._deltaRotation = new BABYLON.Quaternion();
  67203. }
  67204. this._deltaRotation.copyFrom(rotation);
  67205. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  67206. };
  67207. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  67208. if (this._physicsEngine) {
  67209. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  67210. }
  67211. return this;
  67212. };
  67213. PhysicsImpostor.prototype.getRadius = function () {
  67214. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  67215. };
  67216. /**
  67217. * Sync a bone with this impostor
  67218. * @param bone The bone to sync to the impostor.
  67219. * @param boneMesh The mesh that the bone is influencing.
  67220. * @param jointPivot The pivot of the joint / bone in local space.
  67221. * @param distToJoint Optional distance from the impostor to the joint.
  67222. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  67223. */
  67224. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  67225. var tempVec = PhysicsImpostor._tmpVecs[0];
  67226. var mesh = this.object;
  67227. if (mesh.rotationQuaternion) {
  67228. if (adjustRotation) {
  67229. var tempQuat = PhysicsImpostor._tmpQuat;
  67230. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  67231. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  67232. }
  67233. else {
  67234. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  67235. }
  67236. }
  67237. tempVec.x = 0;
  67238. tempVec.y = 0;
  67239. tempVec.z = 0;
  67240. if (jointPivot) {
  67241. tempVec.x = jointPivot.x;
  67242. tempVec.y = jointPivot.y;
  67243. tempVec.z = jointPivot.z;
  67244. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  67245. if (distToJoint === undefined || distToJoint === null) {
  67246. distToJoint = jointPivot.length();
  67247. }
  67248. tempVec.x *= distToJoint;
  67249. tempVec.y *= distToJoint;
  67250. tempVec.z *= distToJoint;
  67251. }
  67252. if (bone.getParent()) {
  67253. tempVec.addInPlace(mesh.getAbsolutePosition());
  67254. bone.setAbsolutePosition(tempVec, boneMesh);
  67255. }
  67256. else {
  67257. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  67258. boneMesh.position.x -= tempVec.x;
  67259. boneMesh.position.y -= tempVec.y;
  67260. boneMesh.position.z -= tempVec.z;
  67261. }
  67262. };
  67263. /**
  67264. * Sync impostor to a bone
  67265. * @param bone The bone that the impostor will be synced to.
  67266. * @param boneMesh The mesh that the bone is influencing.
  67267. * @param jointPivot The pivot of the joint / bone in local space.
  67268. * @param distToJoint Optional distance from the impostor to the joint.
  67269. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  67270. * @param boneAxis Optional vector3 axis the bone is aligned with
  67271. */
  67272. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  67273. var mesh = this.object;
  67274. if (mesh.rotationQuaternion) {
  67275. if (adjustRotation) {
  67276. var tempQuat = PhysicsImpostor._tmpQuat;
  67277. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  67278. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  67279. }
  67280. else {
  67281. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  67282. }
  67283. }
  67284. var pos = PhysicsImpostor._tmpVecs[0];
  67285. var boneDir = PhysicsImpostor._tmpVecs[1];
  67286. if (!boneAxis) {
  67287. boneAxis = PhysicsImpostor._tmpVecs[2];
  67288. boneAxis.x = 0;
  67289. boneAxis.y = 1;
  67290. boneAxis.z = 0;
  67291. }
  67292. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  67293. bone.getAbsolutePositionToRef(boneMesh, pos);
  67294. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  67295. distToJoint = jointPivot.length();
  67296. }
  67297. if (distToJoint !== undefined && distToJoint !== null) {
  67298. pos.x += boneDir.x * distToJoint;
  67299. pos.y += boneDir.y * distToJoint;
  67300. pos.z += boneDir.z * distToJoint;
  67301. }
  67302. mesh.setAbsolutePosition(pos);
  67303. };
  67304. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  67305. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  67306. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67307. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  67308. //Impostor types
  67309. PhysicsImpostor.NoImpostor = 0;
  67310. PhysicsImpostor.SphereImpostor = 1;
  67311. PhysicsImpostor.BoxImpostor = 2;
  67312. PhysicsImpostor.PlaneImpostor = 3;
  67313. PhysicsImpostor.MeshImpostor = 4;
  67314. PhysicsImpostor.CylinderImpostor = 7;
  67315. PhysicsImpostor.ParticleImpostor = 8;
  67316. PhysicsImpostor.HeightmapImpostor = 9;
  67317. return PhysicsImpostor;
  67318. }());
  67319. BABYLON.PhysicsImpostor = PhysicsImpostor;
  67320. })(BABYLON || (BABYLON = {}));
  67321. //# sourceMappingURL=babylon.physicsImpostor.js.map
  67322. var BABYLON;
  67323. (function (BABYLON) {
  67324. var PhysicsEngine = /** @class */ (function () {
  67325. function PhysicsEngine(gravity, _physicsPlugin) {
  67326. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  67327. this._physicsPlugin = _physicsPlugin;
  67328. //new methods and parameters
  67329. this._impostors = [];
  67330. this._joints = [];
  67331. if (!this._physicsPlugin.isSupported()) {
  67332. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  67333. + "Please make sure it is included.");
  67334. }
  67335. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  67336. this.setGravity(gravity);
  67337. this.setTimeStep();
  67338. }
  67339. PhysicsEngine.prototype.setGravity = function (gravity) {
  67340. this.gravity = gravity;
  67341. this._physicsPlugin.setGravity(this.gravity);
  67342. };
  67343. /**
  67344. * Set the time step of the physics engine.
  67345. * default is 1/60.
  67346. * To slow it down, enter 1/600 for example.
  67347. * To speed it up, 1/30
  67348. * @param {number} newTimeStep the new timestep to apply to this world.
  67349. */
  67350. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  67351. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  67352. this._physicsPlugin.setTimeStep(newTimeStep);
  67353. };
  67354. /**
  67355. * Get the time step of the physics engine.
  67356. */
  67357. PhysicsEngine.prototype.getTimeStep = function () {
  67358. return this._physicsPlugin.getTimeStep();
  67359. };
  67360. PhysicsEngine.prototype.dispose = function () {
  67361. this._impostors.forEach(function (impostor) {
  67362. impostor.dispose();
  67363. });
  67364. this._physicsPlugin.dispose();
  67365. };
  67366. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  67367. return this._physicsPlugin.name;
  67368. };
  67369. /**
  67370. * Adding a new impostor for the impostor tracking.
  67371. * This will be done by the impostor itself.
  67372. * @param {PhysicsImpostor} impostor the impostor to add
  67373. */
  67374. PhysicsEngine.prototype.addImpostor = function (impostor) {
  67375. impostor.uniqueId = this._impostors.push(impostor);
  67376. //if no parent, generate the body
  67377. if (!impostor.parent) {
  67378. this._physicsPlugin.generatePhysicsBody(impostor);
  67379. }
  67380. };
  67381. /**
  67382. * Remove an impostor from the engine.
  67383. * This impostor and its mesh will not longer be updated by the physics engine.
  67384. * @param {PhysicsImpostor} impostor the impostor to remove
  67385. */
  67386. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  67387. var index = this._impostors.indexOf(impostor);
  67388. if (index > -1) {
  67389. var removed = this._impostors.splice(index, 1);
  67390. //Is it needed?
  67391. if (removed.length) {
  67392. //this will also remove it from the world.
  67393. removed[0].physicsBody = null;
  67394. }
  67395. }
  67396. };
  67397. /**
  67398. * Add a joint to the physics engine
  67399. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  67400. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  67401. * @param {PhysicsJoint} the joint that will connect both impostors.
  67402. */
  67403. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  67404. var impostorJoint = {
  67405. mainImpostor: mainImpostor,
  67406. connectedImpostor: connectedImpostor,
  67407. joint: joint
  67408. };
  67409. joint.physicsPlugin = this._physicsPlugin;
  67410. this._joints.push(impostorJoint);
  67411. this._physicsPlugin.generateJoint(impostorJoint);
  67412. };
  67413. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  67414. var matchingJoints = this._joints.filter(function (impostorJoint) {
  67415. return (impostorJoint.connectedImpostor === connectedImpostor
  67416. && impostorJoint.joint === joint
  67417. && impostorJoint.mainImpostor === mainImpostor);
  67418. });
  67419. if (matchingJoints.length) {
  67420. this._physicsPlugin.removeJoint(matchingJoints[0]);
  67421. //TODO remove it from the list as well
  67422. }
  67423. };
  67424. /**
  67425. * Called by the scene. no need to call it.
  67426. */
  67427. PhysicsEngine.prototype._step = function (delta) {
  67428. var _this = this;
  67429. //check if any mesh has no body / requires an update
  67430. this._impostors.forEach(function (impostor) {
  67431. if (impostor.isBodyInitRequired()) {
  67432. _this._physicsPlugin.generatePhysicsBody(impostor);
  67433. }
  67434. });
  67435. if (delta > 0.1) {
  67436. delta = 0.1;
  67437. }
  67438. else if (delta <= 0) {
  67439. delta = 1.0 / 60.0;
  67440. }
  67441. this._physicsPlugin.executeStep(delta, this._impostors);
  67442. };
  67443. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  67444. return this._physicsPlugin;
  67445. };
  67446. PhysicsEngine.prototype.getImpostors = function () {
  67447. return this._impostors;
  67448. };
  67449. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  67450. for (var i = 0; i < this._impostors.length; ++i) {
  67451. if (this._impostors[i].object === object) {
  67452. return this._impostors[i];
  67453. }
  67454. }
  67455. return null;
  67456. };
  67457. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  67458. for (var i = 0; i < this._impostors.length; ++i) {
  67459. if (this._impostors[i].physicsBody === body) {
  67460. return this._impostors[i];
  67461. }
  67462. }
  67463. return null;
  67464. };
  67465. // Statics
  67466. PhysicsEngine.Epsilon = 0.001;
  67467. return PhysicsEngine;
  67468. }());
  67469. BABYLON.PhysicsEngine = PhysicsEngine;
  67470. })(BABYLON || (BABYLON = {}));
  67471. //# sourceMappingURL=babylon.physicsEngine.js.map
  67472. var BABYLON;
  67473. (function (BABYLON) {
  67474. var PhysicsHelper = /** @class */ (function () {
  67475. function PhysicsHelper(scene) {
  67476. this._scene = scene;
  67477. this._physicsEngine = this._scene.getPhysicsEngine();
  67478. if (!this._physicsEngine) {
  67479. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  67480. }
  67481. }
  67482. /**
  67483. * @param {Vector3} origin the origin of the explosion
  67484. * @param {number} radius the explosion radius
  67485. * @param {number} strength the explosion strength
  67486. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  67487. */
  67488. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  67489. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  67490. if (!this._physicsEngine) {
  67491. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  67492. return null;
  67493. }
  67494. var impostors = this._physicsEngine.getImpostors();
  67495. if (impostors.length === 0) {
  67496. return null;
  67497. }
  67498. var event = new PhysicsRadialExplosionEvent(this._scene);
  67499. impostors.forEach(function (impostor) {
  67500. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  67501. if (!impostorForceAndContactPoint) {
  67502. return;
  67503. }
  67504. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  67505. });
  67506. event.dispose(false);
  67507. return event;
  67508. };
  67509. /**
  67510. * @param {Vector3} origin the origin of the explosion
  67511. * @param {number} radius the explosion radius
  67512. * @param {number} strength the explosion strength
  67513. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  67514. */
  67515. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  67516. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  67517. if (!this._physicsEngine) {
  67518. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  67519. return null;
  67520. }
  67521. var impostors = this._physicsEngine.getImpostors();
  67522. if (impostors.length === 0) {
  67523. return null;
  67524. }
  67525. var event = new PhysicsRadialExplosionEvent(this._scene);
  67526. impostors.forEach(function (impostor) {
  67527. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  67528. if (!impostorForceAndContactPoint) {
  67529. return;
  67530. }
  67531. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  67532. });
  67533. event.dispose(false);
  67534. return event;
  67535. };
  67536. /**
  67537. * @param {Vector3} origin the origin of the explosion
  67538. * @param {number} radius the explosion radius
  67539. * @param {number} strength the explosion strength
  67540. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  67541. */
  67542. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  67543. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  67544. if (!this._physicsEngine) {
  67545. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  67546. return null;
  67547. }
  67548. var impostors = this._physicsEngine.getImpostors();
  67549. if (impostors.length === 0) {
  67550. return null;
  67551. }
  67552. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  67553. event.dispose(false);
  67554. return event;
  67555. };
  67556. /**
  67557. * @param {Vector3} origin the origin of the updraft
  67558. * @param {number} radius the radius of the updraft
  67559. * @param {number} strength the strength of the updraft
  67560. * @param {number} height the height of the updraft
  67561. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  67562. */
  67563. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  67564. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  67565. if (!this._physicsEngine) {
  67566. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  67567. return null;
  67568. }
  67569. if (this._physicsEngine.getImpostors().length === 0) {
  67570. return null;
  67571. }
  67572. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  67573. event.dispose(false);
  67574. return event;
  67575. };
  67576. /**
  67577. * @param {Vector3} origin the of the vortex
  67578. * @param {number} radius the radius of the vortex
  67579. * @param {number} strength the strength of the vortex
  67580. * @param {number} height the height of the vortex
  67581. */
  67582. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  67583. if (!this._physicsEngine) {
  67584. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  67585. return null;
  67586. }
  67587. if (this._physicsEngine.getImpostors().length === 0) {
  67588. return null;
  67589. }
  67590. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  67591. event.dispose(false);
  67592. return event;
  67593. };
  67594. return PhysicsHelper;
  67595. }());
  67596. BABYLON.PhysicsHelper = PhysicsHelper;
  67597. /***** Radial explosion *****/
  67598. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  67599. function PhysicsRadialExplosionEvent(scene) {
  67600. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  67601. this._rays = [];
  67602. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  67603. this._scene = scene;
  67604. }
  67605. /**
  67606. * Returns the data related to the radial explosion event (sphere & rays).
  67607. * @returns {PhysicsRadialExplosionEventData}
  67608. */
  67609. PhysicsRadialExplosionEvent.prototype.getData = function () {
  67610. this._dataFetched = true;
  67611. return {
  67612. sphere: this._sphere,
  67613. rays: this._rays,
  67614. };
  67615. };
  67616. /**
  67617. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  67618. * @param impostor
  67619. * @param {Vector3} origin the origin of the explosion
  67620. * @param {number} radius the explosion radius
  67621. * @param {number} strength the explosion strength
  67622. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  67623. * @returns {Nullable<PhysicsForceAndContactPoint>}
  67624. */
  67625. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  67626. if (impostor.mass === 0) {
  67627. return null;
  67628. }
  67629. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  67630. return null;
  67631. }
  67632. if (impostor.object.getClassName() !== 'Mesh') {
  67633. return null;
  67634. }
  67635. var impostorObject = impostor.object;
  67636. var impostorObjectCenter = impostor.getObjectCenter();
  67637. var direction = impostorObjectCenter.subtract(origin);
  67638. var ray = new BABYLON.Ray(origin, direction, radius);
  67639. this._rays.push(ray);
  67640. var hit = ray.intersectsMesh(impostorObject);
  67641. var contactPoint = hit.pickedPoint;
  67642. if (!contactPoint) {
  67643. return null;
  67644. }
  67645. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  67646. if (distanceFromOrigin > radius) {
  67647. return null;
  67648. }
  67649. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  67650. ? strength
  67651. : strength * (1 - (distanceFromOrigin / radius));
  67652. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  67653. return { force: force, contactPoint: contactPoint };
  67654. };
  67655. /**
  67656. * Disposes the sphere.
  67657. * @param {bolean} force
  67658. */
  67659. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  67660. var _this = this;
  67661. if (force === void 0) { force = true; }
  67662. if (force) {
  67663. this._sphere.dispose();
  67664. }
  67665. else {
  67666. setTimeout(function () {
  67667. if (!_this._dataFetched) {
  67668. _this._sphere.dispose();
  67669. }
  67670. }, 0);
  67671. }
  67672. };
  67673. /*** Helpers ***/
  67674. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  67675. if (!this._sphere) {
  67676. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  67677. this._sphere.isVisible = false;
  67678. }
  67679. };
  67680. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  67681. var impostorObject = impostor.object;
  67682. this._prepareSphere();
  67683. this._sphere.position = origin;
  67684. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  67685. this._sphere._updateBoundingInfo();
  67686. this._sphere.computeWorldMatrix(true);
  67687. return this._sphere.intersectsMesh(impostorObject, true);
  67688. };
  67689. return PhysicsRadialExplosionEvent;
  67690. }());
  67691. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  67692. /***** Gravitational Field *****/
  67693. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  67694. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  67695. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  67696. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  67697. this._physicsHelper = physicsHelper;
  67698. this._scene = scene;
  67699. this._origin = origin;
  67700. this._radius = radius;
  67701. this._strength = strength;
  67702. this._falloff = falloff;
  67703. this._tickCallback = this._tick.bind(this);
  67704. }
  67705. /**
  67706. * Returns the data related to the gravitational field event (sphere).
  67707. * @returns {PhysicsGravitationalFieldEventData}
  67708. */
  67709. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  67710. this._dataFetched = true;
  67711. return {
  67712. sphere: this._sphere,
  67713. };
  67714. };
  67715. /**
  67716. * Enables the gravitational field.
  67717. */
  67718. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  67719. this._tickCallback.call(this);
  67720. this._scene.registerBeforeRender(this._tickCallback);
  67721. };
  67722. /**
  67723. * Disables the gravitational field.
  67724. */
  67725. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  67726. this._scene.unregisterBeforeRender(this._tickCallback);
  67727. };
  67728. /**
  67729. * Disposes the sphere.
  67730. * @param {bolean} force
  67731. */
  67732. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  67733. var _this = this;
  67734. if (force === void 0) { force = true; }
  67735. if (force) {
  67736. this._sphere.dispose();
  67737. }
  67738. else {
  67739. setTimeout(function () {
  67740. if (!_this._dataFetched) {
  67741. _this._sphere.dispose();
  67742. }
  67743. }, 0);
  67744. }
  67745. };
  67746. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  67747. // Since the params won't change, we fetch the event only once
  67748. if (this._sphere) {
  67749. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  67750. }
  67751. else {
  67752. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  67753. if (radialExplosionEvent) {
  67754. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  67755. }
  67756. }
  67757. };
  67758. return PhysicsGravitationalFieldEvent;
  67759. }());
  67760. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  67761. /***** Updraft *****/
  67762. var PhysicsUpdraftEvent = /** @class */ (function () {
  67763. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  67764. this._scene = _scene;
  67765. this._origin = _origin;
  67766. this._radius = _radius;
  67767. this._strength = _strength;
  67768. this._height = _height;
  67769. this._updraftMode = _updraftMode;
  67770. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  67771. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  67772. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  67773. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  67774. this._physicsEngine = this._scene.getPhysicsEngine();
  67775. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  67776. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  67777. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  67778. this._originDirection = this._origin.subtract(this._originTop).normalize();
  67779. }
  67780. this._tickCallback = this._tick.bind(this);
  67781. }
  67782. /**
  67783. * Returns the data related to the updraft event (cylinder).
  67784. * @returns {PhysicsUpdraftEventData}
  67785. */
  67786. PhysicsUpdraftEvent.prototype.getData = function () {
  67787. this._dataFetched = true;
  67788. return {
  67789. cylinder: this._cylinder,
  67790. };
  67791. };
  67792. /**
  67793. * Enables the updraft.
  67794. */
  67795. PhysicsUpdraftEvent.prototype.enable = function () {
  67796. this._tickCallback.call(this);
  67797. this._scene.registerBeforeRender(this._tickCallback);
  67798. };
  67799. /**
  67800. * Disables the cortex.
  67801. */
  67802. PhysicsUpdraftEvent.prototype.disable = function () {
  67803. this._scene.unregisterBeforeRender(this._tickCallback);
  67804. };
  67805. /**
  67806. * Disposes the sphere.
  67807. * @param {bolean} force
  67808. */
  67809. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  67810. var _this = this;
  67811. if (force === void 0) { force = true; }
  67812. if (force) {
  67813. this._cylinder.dispose();
  67814. }
  67815. else {
  67816. setTimeout(function () {
  67817. if (!_this._dataFetched) {
  67818. _this._cylinder.dispose();
  67819. }
  67820. }, 0);
  67821. }
  67822. };
  67823. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  67824. if (impostor.mass === 0) {
  67825. return null;
  67826. }
  67827. if (!this._intersectsWithCylinder(impostor)) {
  67828. return null;
  67829. }
  67830. var impostorObjectCenter = impostor.getObjectCenter();
  67831. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  67832. var direction = this._originDirection;
  67833. }
  67834. else {
  67835. var direction = impostorObjectCenter.subtract(this._originTop);
  67836. }
  67837. var multiplier = this._strength * -1;
  67838. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  67839. return { force: force, contactPoint: impostorObjectCenter };
  67840. };
  67841. PhysicsUpdraftEvent.prototype._tick = function () {
  67842. var _this = this;
  67843. this._physicsEngine.getImpostors().forEach(function (impostor) {
  67844. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  67845. if (!impostorForceAndContactPoint) {
  67846. return;
  67847. }
  67848. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  67849. });
  67850. };
  67851. /*** Helpers ***/
  67852. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  67853. if (!this._cylinder) {
  67854. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  67855. height: this._height,
  67856. diameter: this._radius * 2,
  67857. }, this._scene);
  67858. this._cylinder.isVisible = false;
  67859. }
  67860. };
  67861. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  67862. var impostorObject = impostor.object;
  67863. this._prepareCylinder();
  67864. this._cylinder.position = this._cylinderPosition;
  67865. return this._cylinder.intersectsMesh(impostorObject, true);
  67866. };
  67867. return PhysicsUpdraftEvent;
  67868. }());
  67869. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  67870. /***** Vortex *****/
  67871. var PhysicsVortexEvent = /** @class */ (function () {
  67872. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  67873. this._scene = _scene;
  67874. this._origin = _origin;
  67875. this._radius = _radius;
  67876. this._strength = _strength;
  67877. this._height = _height;
  67878. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  67879. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  67880. this._updraftMultiplier = 0.02;
  67881. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  67882. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  67883. this._physicsEngine = this._scene.getPhysicsEngine();
  67884. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  67885. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  67886. this._tickCallback = this._tick.bind(this);
  67887. }
  67888. /**
  67889. * Returns the data related to the vortex event (cylinder).
  67890. * @returns {PhysicsVortexEventData}
  67891. */
  67892. PhysicsVortexEvent.prototype.getData = function () {
  67893. this._dataFetched = true;
  67894. return {
  67895. cylinder: this._cylinder,
  67896. };
  67897. };
  67898. /**
  67899. * Enables the vortex.
  67900. */
  67901. PhysicsVortexEvent.prototype.enable = function () {
  67902. this._tickCallback.call(this);
  67903. this._scene.registerBeforeRender(this._tickCallback);
  67904. };
  67905. /**
  67906. * Disables the cortex.
  67907. */
  67908. PhysicsVortexEvent.prototype.disable = function () {
  67909. this._scene.unregisterBeforeRender(this._tickCallback);
  67910. };
  67911. /**
  67912. * Disposes the sphere.
  67913. * @param {bolean} force
  67914. */
  67915. PhysicsVortexEvent.prototype.dispose = function (force) {
  67916. var _this = this;
  67917. if (force === void 0) { force = true; }
  67918. if (force) {
  67919. this._cylinder.dispose();
  67920. }
  67921. else {
  67922. setTimeout(function () {
  67923. if (!_this._dataFetched) {
  67924. _this._cylinder.dispose();
  67925. }
  67926. }, 0);
  67927. }
  67928. };
  67929. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  67930. if (impostor.mass === 0) {
  67931. return null;
  67932. }
  67933. if (!this._intersectsWithCylinder(impostor)) {
  67934. return null;
  67935. }
  67936. if (impostor.object.getClassName() !== 'Mesh') {
  67937. return null;
  67938. }
  67939. var impostorObject = impostor.object;
  67940. var impostorObjectCenter = impostor.getObjectCenter();
  67941. var originOnPlane = new BABYLON.Vector3(this._origin.x, impostorObjectCenter.y, this._origin.z); // the distance to the origin as if both objects were on a plane (Y-axis)
  67942. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  67943. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  67944. var hit = ray.intersectsMesh(impostorObject);
  67945. var contactPoint = hit.pickedPoint;
  67946. if (!contactPoint) {
  67947. return null;
  67948. }
  67949. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  67950. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  67951. var directionToOrigin = contactPoint.normalize();
  67952. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  67953. directionToOrigin = directionToOrigin.negate();
  67954. }
  67955. // TODO: find a more physically based solution
  67956. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  67957. var forceX = directionToOrigin.x * this._strength / 8;
  67958. var forceY = directionToOrigin.y * this._updraftMultiplier;
  67959. var forceZ = directionToOrigin.z * this._strength / 8;
  67960. }
  67961. else {
  67962. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  67963. var forceY = this._originTop.y * this._updraftMultiplier;
  67964. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  67965. }
  67966. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  67967. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  67968. return { force: force, contactPoint: impostorObjectCenter };
  67969. };
  67970. PhysicsVortexEvent.prototype._tick = function () {
  67971. var _this = this;
  67972. this._physicsEngine.getImpostors().forEach(function (impostor) {
  67973. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  67974. if (!impostorForceAndContactPoint) {
  67975. return;
  67976. }
  67977. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  67978. });
  67979. };
  67980. /*** Helpers ***/
  67981. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  67982. if (!this._cylinder) {
  67983. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  67984. height: this._height,
  67985. diameter: this._radius * 2,
  67986. }, this._scene);
  67987. this._cylinder.isVisible = false;
  67988. }
  67989. };
  67990. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  67991. var impostorObject = impostor.object;
  67992. this._prepareCylinder();
  67993. this._cylinder.position = this._cylinderPosition;
  67994. return this._cylinder.intersectsMesh(impostorObject, true);
  67995. };
  67996. return PhysicsVortexEvent;
  67997. }());
  67998. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  67999. /***** Enums *****/
  68000. /**
  68001. * The strenght of the force in correspondence to the distance of the affected object
  68002. */
  68003. var PhysicsRadialImpulseFalloff;
  68004. (function (PhysicsRadialImpulseFalloff) {
  68005. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  68006. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  68007. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  68008. /**
  68009. * The strenght of the force in correspondence to the distance of the affected object
  68010. */
  68011. var PhysicsUpdraftMode;
  68012. (function (PhysicsUpdraftMode) {
  68013. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  68014. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  68015. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  68016. })(BABYLON || (BABYLON = {}));
  68017. //# sourceMappingURL=babylon.physicsHelper.js.map
  68018. var BABYLON;
  68019. (function (BABYLON) {
  68020. var CannonJSPlugin = /** @class */ (function () {
  68021. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  68022. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  68023. if (iterations === void 0) { iterations = 10; }
  68024. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  68025. this.name = "CannonJSPlugin";
  68026. this._physicsMaterials = new Array();
  68027. this._fixedTimeStep = 1 / 60;
  68028. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  68029. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  68030. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  68031. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  68032. this._tmpPosition = BABYLON.Vector3.Zero();
  68033. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  68034. this._tmpUnityRotation = new BABYLON.Quaternion();
  68035. if (!this.isSupported()) {
  68036. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  68037. return;
  68038. }
  68039. this._extendNamespace();
  68040. this.world = new this.BJSCANNON.World();
  68041. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  68042. this.world.solver.iterations = iterations;
  68043. }
  68044. CannonJSPlugin.prototype.setGravity = function (gravity) {
  68045. this.world.gravity.copy(gravity);
  68046. };
  68047. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  68048. this._fixedTimeStep = timeStep;
  68049. };
  68050. CannonJSPlugin.prototype.getTimeStep = function () {
  68051. return this._fixedTimeStep;
  68052. };
  68053. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  68054. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  68055. };
  68056. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  68057. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  68058. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  68059. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  68060. };
  68061. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  68062. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  68063. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  68064. impostor.physicsBody.applyForce(impulse, worldPoint);
  68065. };
  68066. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  68067. //parent-child relationship. Does this impostor has a parent impostor?
  68068. if (impostor.parent) {
  68069. if (impostor.physicsBody) {
  68070. this.removePhysicsBody(impostor);
  68071. //TODO is that needed?
  68072. impostor.forceUpdate();
  68073. }
  68074. return;
  68075. }
  68076. //should a new body be created for this impostor?
  68077. if (impostor.isBodyInitRequired()) {
  68078. var shape = this._createShape(impostor);
  68079. //unregister events, if body is being changed
  68080. var oldBody = impostor.physicsBody;
  68081. if (oldBody) {
  68082. this.removePhysicsBody(impostor);
  68083. }
  68084. //create the body and material
  68085. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  68086. var bodyCreationObject = {
  68087. mass: impostor.getParam("mass"),
  68088. material: material
  68089. };
  68090. // A simple extend, in case native options were used.
  68091. var nativeOptions = impostor.getParam("nativeOptions");
  68092. for (var key in nativeOptions) {
  68093. if (nativeOptions.hasOwnProperty(key)) {
  68094. bodyCreationObject[key] = nativeOptions[key];
  68095. }
  68096. }
  68097. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  68098. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  68099. this.world.addEventListener("preStep", impostor.beforeStep);
  68100. this.world.addEventListener("postStep", impostor.afterStep);
  68101. impostor.physicsBody.addShape(shape);
  68102. this.world.add(impostor.physicsBody);
  68103. //try to keep the body moving in the right direction by taking old properties.
  68104. //Should be tested!
  68105. if (oldBody) {
  68106. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  68107. impostor.physicsBody[param].copy(oldBody[param]);
  68108. });
  68109. }
  68110. this._processChildMeshes(impostor);
  68111. }
  68112. //now update the body's transformation
  68113. this._updatePhysicsBodyTransformation(impostor);
  68114. };
  68115. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  68116. var _this = this;
  68117. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  68118. var currentRotation = mainImpostor.object.rotationQuaternion;
  68119. if (meshChildren.length) {
  68120. var processMesh = function (localPosition, mesh) {
  68121. if (!currentRotation || !mesh.rotationQuaternion) {
  68122. return;
  68123. }
  68124. var childImpostor = mesh.getPhysicsImpostor();
  68125. if (childImpostor) {
  68126. var parent = childImpostor.parent;
  68127. if (parent !== mainImpostor) {
  68128. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  68129. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  68130. if (childImpostor.physicsBody) {
  68131. _this.removePhysicsBody(childImpostor);
  68132. childImpostor.physicsBody = null;
  68133. }
  68134. childImpostor.parent = mainImpostor;
  68135. childImpostor.resetUpdateFlags();
  68136. 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));
  68137. //Add the mass of the children.
  68138. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  68139. }
  68140. }
  68141. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  68142. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  68143. };
  68144. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  68145. }
  68146. };
  68147. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  68148. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  68149. this.world.removeEventListener("preStep", impostor.beforeStep);
  68150. this.world.removeEventListener("postStep", impostor.afterStep);
  68151. this.world.remove(impostor.physicsBody);
  68152. };
  68153. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  68154. var mainBody = impostorJoint.mainImpostor.physicsBody;
  68155. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  68156. if (!mainBody || !connectedBody) {
  68157. return;
  68158. }
  68159. var constraint;
  68160. var jointData = impostorJoint.joint.jointData;
  68161. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  68162. var constraintData = {
  68163. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  68164. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  68165. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  68166. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  68167. maxForce: jointData.nativeParams.maxForce,
  68168. collideConnected: !!jointData.collision
  68169. };
  68170. switch (impostorJoint.joint.type) {
  68171. case BABYLON.PhysicsJoint.HingeJoint:
  68172. case BABYLON.PhysicsJoint.Hinge2Joint:
  68173. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  68174. break;
  68175. case BABYLON.PhysicsJoint.DistanceJoint:
  68176. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  68177. break;
  68178. case BABYLON.PhysicsJoint.SpringJoint:
  68179. var springData = jointData;
  68180. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  68181. restLength: springData.length,
  68182. stiffness: springData.stiffness,
  68183. damping: springData.damping,
  68184. localAnchorA: constraintData.pivotA,
  68185. localAnchorB: constraintData.pivotB
  68186. });
  68187. break;
  68188. case BABYLON.PhysicsJoint.LockJoint:
  68189. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  68190. break;
  68191. case BABYLON.PhysicsJoint.PointToPointJoint:
  68192. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  68193. default:
  68194. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  68195. break;
  68196. }
  68197. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  68198. constraint.collideConnected = !!jointData.collision;
  68199. impostorJoint.joint.physicsJoint = constraint;
  68200. //don't add spring as constraint, as it is not one.
  68201. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  68202. this.world.addConstraint(constraint);
  68203. }
  68204. else {
  68205. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  68206. constraint.applyForce();
  68207. });
  68208. }
  68209. };
  68210. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  68211. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  68212. };
  68213. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  68214. var index;
  68215. var mat;
  68216. for (index = 0; index < this._physicsMaterials.length; index++) {
  68217. mat = this._physicsMaterials[index];
  68218. if (mat.friction === friction && mat.restitution === restitution) {
  68219. return mat;
  68220. }
  68221. }
  68222. var currentMat = new this.BJSCANNON.Material(name);
  68223. currentMat.friction = friction;
  68224. currentMat.restitution = restitution;
  68225. this._physicsMaterials.push(currentMat);
  68226. return currentMat;
  68227. };
  68228. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  68229. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  68230. };
  68231. CannonJSPlugin.prototype._createShape = function (impostor) {
  68232. var object = impostor.object;
  68233. var returnValue;
  68234. var extendSize = impostor.getObjectExtendSize();
  68235. switch (impostor.type) {
  68236. case BABYLON.PhysicsImpostor.SphereImpostor:
  68237. var radiusX = extendSize.x;
  68238. var radiusY = extendSize.y;
  68239. var radiusZ = extendSize.z;
  68240. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  68241. break;
  68242. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  68243. case BABYLON.PhysicsImpostor.CylinderImpostor:
  68244. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  68245. break;
  68246. case BABYLON.PhysicsImpostor.BoxImpostor:
  68247. var box = extendSize.scale(0.5);
  68248. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  68249. break;
  68250. case BABYLON.PhysicsImpostor.PlaneImpostor:
  68251. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  68252. returnValue = new this.BJSCANNON.Plane();
  68253. break;
  68254. case BABYLON.PhysicsImpostor.MeshImpostor:
  68255. // should transform the vertex data to world coordinates!!
  68256. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  68257. var rawFaces = object.getIndices ? object.getIndices() : [];
  68258. if (!rawVerts)
  68259. return;
  68260. // get only scale! so the object could transform correctly.
  68261. var oldPosition = object.position.clone();
  68262. var oldRotation = object.rotation && object.rotation.clone();
  68263. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  68264. object.position.copyFromFloats(0, 0, 0);
  68265. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  68266. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  68267. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  68268. var transform = object.computeWorldMatrix(true);
  68269. // convert rawVerts to object space
  68270. var temp = new Array();
  68271. var index;
  68272. for (index = 0; index < rawVerts.length; index += 3) {
  68273. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  68274. }
  68275. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  68276. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  68277. //now set back the transformation!
  68278. object.position.copyFrom(oldPosition);
  68279. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  68280. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  68281. break;
  68282. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  68283. var oldPosition2 = object.position.clone();
  68284. var oldRotation2 = object.rotation && object.rotation.clone();
  68285. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  68286. object.position.copyFromFloats(0, 0, 0);
  68287. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  68288. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  68289. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  68290. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  68291. returnValue = this._createHeightmap(object);
  68292. object.position.copyFrom(oldPosition2);
  68293. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  68294. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  68295. object.computeWorldMatrix(true);
  68296. break;
  68297. case BABYLON.PhysicsImpostor.ParticleImpostor:
  68298. returnValue = new this.BJSCANNON.Particle();
  68299. break;
  68300. }
  68301. return returnValue;
  68302. };
  68303. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  68304. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  68305. var transform = object.computeWorldMatrix(true);
  68306. // convert rawVerts to object space
  68307. var temp = new Array();
  68308. var index;
  68309. for (index = 0; index < pos.length; index += 3) {
  68310. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  68311. }
  68312. pos = temp;
  68313. var matrix = new Array();
  68314. //For now pointDepth will not be used and will be automatically calculated.
  68315. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  68316. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  68317. var boundingInfo = object.getBoundingInfo();
  68318. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  68319. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  68320. var elementSize = dim * 2 / arraySize;
  68321. for (var i = 0; i < pos.length; i = i + 3) {
  68322. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  68323. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  68324. var y = -pos[i + 2] + minY;
  68325. if (!matrix[x]) {
  68326. matrix[x] = [];
  68327. }
  68328. if (!matrix[x][z]) {
  68329. matrix[x][z] = y;
  68330. }
  68331. matrix[x][z] = Math.max(y, matrix[x][z]);
  68332. }
  68333. for (var x = 0; x <= arraySize; ++x) {
  68334. if (!matrix[x]) {
  68335. var loc = 1;
  68336. while (!matrix[(x + loc) % arraySize]) {
  68337. loc++;
  68338. }
  68339. matrix[x] = matrix[(x + loc) % arraySize].slice();
  68340. //console.log("missing x", x);
  68341. }
  68342. for (var z = 0; z <= arraySize; ++z) {
  68343. if (!matrix[x][z]) {
  68344. var loc = 1;
  68345. var newValue;
  68346. while (newValue === undefined) {
  68347. newValue = matrix[x][(z + loc++) % arraySize];
  68348. }
  68349. matrix[x][z] = newValue;
  68350. }
  68351. }
  68352. }
  68353. var shape = new this.BJSCANNON.Heightfield(matrix, {
  68354. elementSize: elementSize
  68355. });
  68356. //For future reference, needed for body transformation
  68357. shape.minY = minY;
  68358. return shape;
  68359. };
  68360. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  68361. var object = impostor.object;
  68362. //make sure it is updated...
  68363. object.computeWorldMatrix && object.computeWorldMatrix(true);
  68364. // The delta between the mesh position and the mesh bounding box center
  68365. var bInfo = object.getBoundingInfo();
  68366. if (!bInfo)
  68367. return;
  68368. var center = impostor.getObjectCenter();
  68369. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  68370. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  68371. this._tmpPosition.copyFrom(center);
  68372. var quaternion = object.rotationQuaternion;
  68373. if (!quaternion) {
  68374. return;
  68375. }
  68376. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  68377. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  68378. //-90 DEG in X, precalculated
  68379. quaternion = quaternion.multiply(this._minus90X);
  68380. //Invert! (Precalculated, 90 deg in X)
  68381. //No need to clone. this will never change.
  68382. impostor.setDeltaRotation(this._plus90X);
  68383. }
  68384. //If it is a heightfield, if should be centered.
  68385. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  68386. var mesh = object;
  68387. var boundingInfo = mesh.getBoundingInfo();
  68388. //calculate the correct body position:
  68389. var rotationQuaternion = mesh.rotationQuaternion;
  68390. mesh.rotationQuaternion = this._tmpUnityRotation;
  68391. mesh.computeWorldMatrix(true);
  68392. //get original center with no rotation
  68393. var c = center.clone();
  68394. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  68395. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  68396. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  68397. mesh.setPivotMatrix(p);
  68398. mesh.computeWorldMatrix(true);
  68399. //calculate the translation
  68400. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  68401. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  68402. //add it inverted to the delta
  68403. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  68404. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  68405. //rotation is back
  68406. mesh.rotationQuaternion = rotationQuaternion;
  68407. mesh.setPivotMatrix(oldPivot);
  68408. mesh.computeWorldMatrix(true);
  68409. }
  68410. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  68411. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  68412. //this._tmpPosition.copyFrom(object.position);
  68413. }
  68414. impostor.setDeltaPosition(this._tmpDeltaPosition);
  68415. //Now update the impostor object
  68416. impostor.physicsBody.position.copy(this._tmpPosition);
  68417. impostor.physicsBody.quaternion.copy(quaternion);
  68418. };
  68419. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  68420. impostor.object.position.copyFrom(impostor.physicsBody.position);
  68421. if (impostor.object.rotationQuaternion) {
  68422. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  68423. }
  68424. };
  68425. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  68426. impostor.physicsBody.position.copy(newPosition);
  68427. impostor.physicsBody.quaternion.copy(newRotation);
  68428. };
  68429. CannonJSPlugin.prototype.isSupported = function () {
  68430. return this.BJSCANNON !== undefined;
  68431. };
  68432. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  68433. impostor.physicsBody.velocity.copy(velocity);
  68434. };
  68435. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  68436. impostor.physicsBody.angularVelocity.copy(velocity);
  68437. };
  68438. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  68439. var v = impostor.physicsBody.velocity;
  68440. if (!v) {
  68441. return null;
  68442. }
  68443. return new BABYLON.Vector3(v.x, v.y, v.z);
  68444. };
  68445. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  68446. var v = impostor.physicsBody.angularVelocity;
  68447. if (!v) {
  68448. return null;
  68449. }
  68450. return new BABYLON.Vector3(v.x, v.y, v.z);
  68451. };
  68452. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  68453. impostor.physicsBody.mass = mass;
  68454. impostor.physicsBody.updateMassProperties();
  68455. };
  68456. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  68457. return impostor.physicsBody.mass;
  68458. };
  68459. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  68460. return impostor.physicsBody.material.friction;
  68461. };
  68462. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  68463. impostor.physicsBody.material.friction = friction;
  68464. };
  68465. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  68466. return impostor.physicsBody.material.restitution;
  68467. };
  68468. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  68469. impostor.physicsBody.material.restitution = restitution;
  68470. };
  68471. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  68472. impostor.physicsBody.sleep();
  68473. };
  68474. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  68475. impostor.physicsBody.wakeUp();
  68476. };
  68477. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  68478. joint.physicsJoint.distance = maxDistance;
  68479. };
  68480. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  68481. // if (!motorIndex) {
  68482. // joint.physicsJoint.enableMotor();
  68483. // }
  68484. // }
  68485. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  68486. // if (!motorIndex) {
  68487. // joint.physicsJoint.disableMotor();
  68488. // }
  68489. // }
  68490. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  68491. if (!motorIndex) {
  68492. joint.physicsJoint.enableMotor();
  68493. joint.physicsJoint.setMotorSpeed(speed);
  68494. if (maxForce) {
  68495. this.setLimit(joint, maxForce);
  68496. }
  68497. }
  68498. };
  68499. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  68500. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  68501. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  68502. };
  68503. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  68504. var body = impostor.physicsBody;
  68505. mesh.position.x = body.position.x;
  68506. mesh.position.y = body.position.y;
  68507. mesh.position.z = body.position.z;
  68508. if (mesh.rotationQuaternion) {
  68509. mesh.rotationQuaternion.x = body.quaternion.x;
  68510. mesh.rotationQuaternion.y = body.quaternion.y;
  68511. mesh.rotationQuaternion.z = body.quaternion.z;
  68512. mesh.rotationQuaternion.w = body.quaternion.w;
  68513. }
  68514. };
  68515. CannonJSPlugin.prototype.getRadius = function (impostor) {
  68516. var shape = impostor.physicsBody.shapes[0];
  68517. return shape.boundingSphereRadius;
  68518. };
  68519. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  68520. var shape = impostor.physicsBody.shapes[0];
  68521. result.x = shape.halfExtents.x * 2;
  68522. result.y = shape.halfExtents.y * 2;
  68523. result.z = shape.halfExtents.z * 2;
  68524. };
  68525. CannonJSPlugin.prototype.dispose = function () {
  68526. };
  68527. CannonJSPlugin.prototype._extendNamespace = function () {
  68528. //this will force cannon to execute at least one step when using interpolation
  68529. var step_tmp1 = new this.BJSCANNON.Vec3();
  68530. var Engine = this.BJSCANNON;
  68531. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  68532. maxSubSteps = maxSubSteps || 10;
  68533. timeSinceLastCalled = timeSinceLastCalled || 0;
  68534. if (timeSinceLastCalled === 0) {
  68535. this.internalStep(dt);
  68536. this.time += dt;
  68537. }
  68538. else {
  68539. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  68540. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  68541. var t0 = performance.now();
  68542. for (var i = 0; i !== internalSteps; i++) {
  68543. this.internalStep(dt);
  68544. if (performance.now() - t0 > dt * 1000) {
  68545. break;
  68546. }
  68547. }
  68548. this.time += timeSinceLastCalled;
  68549. var h = this.time % dt;
  68550. var h_div_dt = h / dt;
  68551. var interpvelo = step_tmp1;
  68552. var bodies = this.bodies;
  68553. for (var j = 0; j !== bodies.length; j++) {
  68554. var b = bodies[j];
  68555. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  68556. b.position.vsub(b.previousPosition, interpvelo);
  68557. interpvelo.scale(h_div_dt, interpvelo);
  68558. b.position.vadd(interpvelo, b.interpolatedPosition);
  68559. }
  68560. else {
  68561. b.interpolatedPosition.copy(b.position);
  68562. b.interpolatedQuaternion.copy(b.quaternion);
  68563. }
  68564. }
  68565. }
  68566. };
  68567. };
  68568. return CannonJSPlugin;
  68569. }());
  68570. BABYLON.CannonJSPlugin = CannonJSPlugin;
  68571. })(BABYLON || (BABYLON = {}));
  68572. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  68573. var BABYLON;
  68574. (function (BABYLON) {
  68575. var OimoJSPlugin = /** @class */ (function () {
  68576. function OimoJSPlugin(iterations) {
  68577. this.name = "OimoJSPlugin";
  68578. this._tmpImpostorsArray = [];
  68579. this._tmpPositionVector = BABYLON.Vector3.Zero();
  68580. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  68581. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  68582. this.world.worldscale(1);
  68583. this.world.clear();
  68584. //making sure no stats are calculated
  68585. this.world.isNoStat = true;
  68586. }
  68587. OimoJSPlugin.prototype.setGravity = function (gravity) {
  68588. this.world.gravity.copy(gravity);
  68589. };
  68590. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  68591. this.world.timeStep = timeStep;
  68592. };
  68593. OimoJSPlugin.prototype.getTimeStep = function () {
  68594. return this.world.timeStep;
  68595. };
  68596. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  68597. var _this = this;
  68598. impostors.forEach(function (impostor) {
  68599. impostor.beforeStep();
  68600. });
  68601. this.world.step();
  68602. impostors.forEach(function (impostor) {
  68603. impostor.afterStep();
  68604. //update the ordered impostors array
  68605. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  68606. });
  68607. //check for collisions
  68608. var contact = this.world.contacts;
  68609. while (contact !== null) {
  68610. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  68611. contact = contact.next;
  68612. continue;
  68613. }
  68614. //is this body colliding with any other? get the impostor
  68615. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  68616. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  68617. if (!mainImpostor || !collidingImpostor) {
  68618. contact = contact.next;
  68619. continue;
  68620. }
  68621. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  68622. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  68623. contact = contact.next;
  68624. }
  68625. };
  68626. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  68627. var mass = impostor.physicsBody.massInfo.mass;
  68628. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  68629. };
  68630. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  68631. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  68632. this.applyImpulse(impostor, force, contactPoint);
  68633. };
  68634. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  68635. var _this = this;
  68636. //parent-child relationship. Does this impostor has a parent impostor?
  68637. if (impostor.parent) {
  68638. if (impostor.physicsBody) {
  68639. this.removePhysicsBody(impostor);
  68640. //TODO is that needed?
  68641. impostor.forceUpdate();
  68642. }
  68643. return;
  68644. }
  68645. if (impostor.isBodyInitRequired()) {
  68646. var bodyConfig = {
  68647. name: impostor.uniqueId,
  68648. //Oimo must have mass, also for static objects.
  68649. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  68650. size: [],
  68651. type: [],
  68652. pos: [],
  68653. rot: [],
  68654. move: impostor.getParam("mass") !== 0,
  68655. //Supporting older versions of Oimo
  68656. world: this.world
  68657. };
  68658. var impostors = [impostor];
  68659. var addToArray = function (parent) {
  68660. if (!parent.getChildMeshes)
  68661. return;
  68662. parent.getChildMeshes().forEach(function (m) {
  68663. if (m.physicsImpostor) {
  68664. impostors.push(m.physicsImpostor);
  68665. //m.physicsImpostor._init();
  68666. }
  68667. });
  68668. };
  68669. addToArray(impostor.object);
  68670. var checkWithEpsilon_1 = function (value) {
  68671. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  68672. };
  68673. impostors.forEach(function (i) {
  68674. if (!impostor.object.rotationQuaternion) {
  68675. return;
  68676. }
  68677. //get the correct bounding box
  68678. var oldQuaternion = i.object.rotationQuaternion;
  68679. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  68680. x: impostor.object.rotationQuaternion.x,
  68681. y: impostor.object.rotationQuaternion.y,
  68682. z: impostor.object.rotationQuaternion.z,
  68683. s: impostor.object.rotationQuaternion.w
  68684. });
  68685. var extendSize = i.getObjectExtendSize();
  68686. if (i === impostor) {
  68687. var center = impostor.getObjectCenter();
  68688. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  68689. //Can also use Array.prototype.push.apply
  68690. bodyConfig.pos.push(center.x);
  68691. bodyConfig.pos.push(center.y);
  68692. bodyConfig.pos.push(center.z);
  68693. //tmp solution
  68694. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  68695. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  68696. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  68697. }
  68698. else {
  68699. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  68700. bodyConfig.pos.push(localPosition.x);
  68701. bodyConfig.pos.push(localPosition.y);
  68702. bodyConfig.pos.push(localPosition.z);
  68703. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  68704. bodyConfig.rot.push(0);
  68705. bodyConfig.rot.push(0);
  68706. bodyConfig.rot.push(0);
  68707. }
  68708. // register mesh
  68709. switch (i.type) {
  68710. case BABYLON.PhysicsImpostor.ParticleImpostor:
  68711. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  68712. case BABYLON.PhysicsImpostor.SphereImpostor:
  68713. var radiusX = extendSize.x;
  68714. var radiusY = extendSize.y;
  68715. var radiusZ = extendSize.z;
  68716. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  68717. bodyConfig.type.push('sphere');
  68718. //due to the way oimo works with compounds, add 3 times
  68719. bodyConfig.size.push(size);
  68720. bodyConfig.size.push(size);
  68721. bodyConfig.size.push(size);
  68722. break;
  68723. case BABYLON.PhysicsImpostor.CylinderImpostor:
  68724. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  68725. var sizeY = checkWithEpsilon_1(extendSize.y);
  68726. bodyConfig.type.push('cylinder');
  68727. bodyConfig.size.push(sizeX);
  68728. bodyConfig.size.push(sizeY);
  68729. //due to the way oimo works with compounds, add one more value.
  68730. bodyConfig.size.push(sizeY);
  68731. break;
  68732. case BABYLON.PhysicsImpostor.PlaneImpostor:
  68733. case BABYLON.PhysicsImpostor.BoxImpostor:
  68734. default:
  68735. var sizeX = checkWithEpsilon_1(extendSize.x);
  68736. var sizeY = checkWithEpsilon_1(extendSize.y);
  68737. var sizeZ = checkWithEpsilon_1(extendSize.z);
  68738. bodyConfig.type.push('box');
  68739. bodyConfig.size.push(sizeX);
  68740. bodyConfig.size.push(sizeY);
  68741. bodyConfig.size.push(sizeZ);
  68742. break;
  68743. }
  68744. //actually not needed, but hey...
  68745. i.object.rotationQuaternion = oldQuaternion;
  68746. });
  68747. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  68748. }
  68749. else {
  68750. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  68751. }
  68752. impostor.setDeltaPosition(this._tmpPositionVector);
  68753. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  68754. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  68755. };
  68756. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  68757. //impostor.physicsBody.dispose();
  68758. //Same as : (older oimo versions)
  68759. this.world.removeRigidBody(impostor.physicsBody);
  68760. };
  68761. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  68762. var mainBody = impostorJoint.mainImpostor.physicsBody;
  68763. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  68764. if (!mainBody || !connectedBody) {
  68765. return;
  68766. }
  68767. var jointData = impostorJoint.joint.jointData;
  68768. var options = jointData.nativeParams || {};
  68769. var type;
  68770. var nativeJointData = {
  68771. body1: mainBody,
  68772. body2: connectedBody,
  68773. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  68774. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  68775. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  68776. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  68777. min: options.min,
  68778. max: options.max,
  68779. collision: options.collision || jointData.collision,
  68780. spring: options.spring,
  68781. //supporting older version of Oimo
  68782. world: this.world
  68783. };
  68784. switch (impostorJoint.joint.type) {
  68785. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  68786. type = "jointBall";
  68787. break;
  68788. case BABYLON.PhysicsJoint.SpringJoint:
  68789. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  68790. var springData = jointData;
  68791. nativeJointData.min = springData.length || nativeJointData.min;
  68792. //Max should also be set, just make sure it is at least min
  68793. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  68794. case BABYLON.PhysicsJoint.DistanceJoint:
  68795. type = "jointDistance";
  68796. nativeJointData.max = jointData.maxDistance;
  68797. break;
  68798. case BABYLON.PhysicsJoint.PrismaticJoint:
  68799. type = "jointPrisme";
  68800. break;
  68801. case BABYLON.PhysicsJoint.SliderJoint:
  68802. type = "jointSlide";
  68803. break;
  68804. case BABYLON.PhysicsJoint.WheelJoint:
  68805. type = "jointWheel";
  68806. break;
  68807. case BABYLON.PhysicsJoint.HingeJoint:
  68808. default:
  68809. type = "jointHinge";
  68810. break;
  68811. }
  68812. nativeJointData.type = type;
  68813. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  68814. };
  68815. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  68816. //Bug in Oimo prevents us from disposing a joint in the playground
  68817. //joint.joint.physicsJoint.dispose();
  68818. //So we will bruteforce it!
  68819. try {
  68820. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  68821. }
  68822. catch (e) {
  68823. BABYLON.Tools.Warn(e);
  68824. }
  68825. };
  68826. OimoJSPlugin.prototype.isSupported = function () {
  68827. return this.BJSOIMO !== undefined;
  68828. };
  68829. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  68830. if (!impostor.physicsBody.sleeping) {
  68831. //TODO check that
  68832. if (impostor.physicsBody.shapes.next) {
  68833. var parentShape = this._getLastShape(impostor.physicsBody);
  68834. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  68835. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  68836. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  68837. }
  68838. else {
  68839. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  68840. }
  68841. if (impostor.object.rotationQuaternion) {
  68842. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  68843. impostor.object.rotationQuaternion.normalize();
  68844. }
  68845. }
  68846. };
  68847. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  68848. var body = impostor.physicsBody;
  68849. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  68850. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  68851. body.syncShapes();
  68852. body.awake();
  68853. };
  68854. OimoJSPlugin.prototype._getLastShape = function (body) {
  68855. var lastShape = body.shapes;
  68856. while (lastShape.next) {
  68857. lastShape = lastShape.next;
  68858. }
  68859. return lastShape;
  68860. };
  68861. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  68862. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  68863. };
  68864. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  68865. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  68866. };
  68867. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  68868. var v = impostor.physicsBody.linearVelocity;
  68869. if (!v) {
  68870. return null;
  68871. }
  68872. return new BABYLON.Vector3(v.x, v.y, v.z);
  68873. };
  68874. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  68875. var v = impostor.physicsBody.angularVelocity;
  68876. if (!v) {
  68877. return null;
  68878. }
  68879. return new BABYLON.Vector3(v.x, v.y, v.z);
  68880. };
  68881. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  68882. var staticBody = mass === 0;
  68883. //this will actually set the body's density and not its mass.
  68884. //But this is how oimo treats the mass variable.
  68885. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  68886. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  68887. };
  68888. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  68889. return impostor.physicsBody.shapes.density;
  68890. };
  68891. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  68892. return impostor.physicsBody.shapes.friction;
  68893. };
  68894. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  68895. impostor.physicsBody.shapes.friction = friction;
  68896. };
  68897. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  68898. return impostor.physicsBody.shapes.restitution;
  68899. };
  68900. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  68901. impostor.physicsBody.shapes.restitution = restitution;
  68902. };
  68903. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  68904. impostor.physicsBody.sleep();
  68905. };
  68906. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  68907. impostor.physicsBody.awake();
  68908. };
  68909. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  68910. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  68911. if (minDistance !== void 0) {
  68912. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  68913. }
  68914. };
  68915. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  68916. //TODO separate rotational and transational motors.
  68917. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  68918. if (motor) {
  68919. motor.setMotor(speed, maxForce);
  68920. }
  68921. };
  68922. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  68923. //TODO separate rotational and transational motors.
  68924. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  68925. if (motor) {
  68926. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  68927. }
  68928. };
  68929. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  68930. var body = impostor.physicsBody;
  68931. mesh.position.x = body.position.x;
  68932. mesh.position.y = body.position.y;
  68933. mesh.position.z = body.position.z;
  68934. if (mesh.rotationQuaternion) {
  68935. mesh.rotationQuaternion.x = body.orientation.x;
  68936. mesh.rotationQuaternion.y = body.orientation.y;
  68937. mesh.rotationQuaternion.z = body.orientation.z;
  68938. mesh.rotationQuaternion.w = body.orientation.s;
  68939. }
  68940. };
  68941. OimoJSPlugin.prototype.getRadius = function (impostor) {
  68942. return impostor.physicsBody.shapes.radius;
  68943. };
  68944. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  68945. var shape = impostor.physicsBody.shapes;
  68946. result.x = shape.halfWidth * 2;
  68947. result.y = shape.halfHeight * 2;
  68948. result.z = shape.halfDepth * 2;
  68949. };
  68950. OimoJSPlugin.prototype.dispose = function () {
  68951. this.world.clear();
  68952. };
  68953. return OimoJSPlugin;
  68954. }());
  68955. BABYLON.OimoJSPlugin = OimoJSPlugin;
  68956. })(BABYLON || (BABYLON = {}));
  68957. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  68958. var BABYLON;
  68959. (function (BABYLON) {
  68960. var Internals;
  68961. (function (Internals) {
  68962. /*
  68963. * Based on jsTGALoader - Javascript loader for TGA file
  68964. * By Vincent Thibault
  68965. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  68966. */
  68967. var TGATools = /** @class */ (function () {
  68968. function TGATools() {
  68969. }
  68970. TGATools.GetTGAHeader = function (data) {
  68971. var offset = 0;
  68972. var header = {
  68973. id_length: data[offset++],
  68974. colormap_type: data[offset++],
  68975. image_type: data[offset++],
  68976. colormap_index: data[offset++] | data[offset++] << 8,
  68977. colormap_length: data[offset++] | data[offset++] << 8,
  68978. colormap_size: data[offset++],
  68979. origin: [
  68980. data[offset++] | data[offset++] << 8,
  68981. data[offset++] | data[offset++] << 8
  68982. ],
  68983. width: data[offset++] | data[offset++] << 8,
  68984. height: data[offset++] | data[offset++] << 8,
  68985. pixel_size: data[offset++],
  68986. flags: data[offset++]
  68987. };
  68988. return header;
  68989. };
  68990. TGATools.UploadContent = function (gl, data) {
  68991. // Not enough data to contain header ?
  68992. if (data.length < 19) {
  68993. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  68994. return;
  68995. }
  68996. // Read Header
  68997. var offset = 18;
  68998. var header = TGATools.GetTGAHeader(data);
  68999. // Assume it's a valid Targa file.
  69000. if (header.id_length + offset > data.length) {
  69001. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  69002. return;
  69003. }
  69004. // Skip not needed data
  69005. offset += header.id_length;
  69006. var use_rle = false;
  69007. var use_pal = false;
  69008. var use_grey = false;
  69009. // Get some informations.
  69010. switch (header.image_type) {
  69011. case TGATools._TYPE_RLE_INDEXED:
  69012. use_rle = true;
  69013. case TGATools._TYPE_INDEXED:
  69014. use_pal = true;
  69015. break;
  69016. case TGATools._TYPE_RLE_RGB:
  69017. use_rle = true;
  69018. case TGATools._TYPE_RGB:
  69019. // use_rgb = true;
  69020. break;
  69021. case TGATools._TYPE_RLE_GREY:
  69022. use_rle = true;
  69023. case TGATools._TYPE_GREY:
  69024. use_grey = true;
  69025. break;
  69026. }
  69027. var pixel_data;
  69028. // var numAlphaBits = header.flags & 0xf;
  69029. var pixel_size = header.pixel_size >> 3;
  69030. var pixel_total = header.width * header.height * pixel_size;
  69031. // Read palettes
  69032. var palettes;
  69033. if (use_pal) {
  69034. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  69035. }
  69036. // Read LRE
  69037. if (use_rle) {
  69038. pixel_data = new Uint8Array(pixel_total);
  69039. var c, count, i;
  69040. var localOffset = 0;
  69041. var pixels = new Uint8Array(pixel_size);
  69042. while (offset < pixel_total && localOffset < pixel_total) {
  69043. c = data[offset++];
  69044. count = (c & 0x7f) + 1;
  69045. // RLE pixels
  69046. if (c & 0x80) {
  69047. // Bind pixel tmp array
  69048. for (i = 0; i < pixel_size; ++i) {
  69049. pixels[i] = data[offset++];
  69050. }
  69051. // Copy pixel array
  69052. for (i = 0; i < count; ++i) {
  69053. pixel_data.set(pixels, localOffset + i * pixel_size);
  69054. }
  69055. localOffset += pixel_size * count;
  69056. }
  69057. else {
  69058. count *= pixel_size;
  69059. for (i = 0; i < count; ++i) {
  69060. pixel_data[localOffset + i] = data[offset++];
  69061. }
  69062. localOffset += count;
  69063. }
  69064. }
  69065. }
  69066. else {
  69067. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  69068. }
  69069. // Load to texture
  69070. var x_start, y_start, x_step, y_step, y_end, x_end;
  69071. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  69072. default:
  69073. case TGATools._ORIGIN_UL:
  69074. x_start = 0;
  69075. x_step = 1;
  69076. x_end = header.width;
  69077. y_start = 0;
  69078. y_step = 1;
  69079. y_end = header.height;
  69080. break;
  69081. case TGATools._ORIGIN_BL:
  69082. x_start = 0;
  69083. x_step = 1;
  69084. x_end = header.width;
  69085. y_start = header.height - 1;
  69086. y_step = -1;
  69087. y_end = -1;
  69088. break;
  69089. case TGATools._ORIGIN_UR:
  69090. x_start = header.width - 1;
  69091. x_step = -1;
  69092. x_end = -1;
  69093. y_start = 0;
  69094. y_step = 1;
  69095. y_end = header.height;
  69096. break;
  69097. case TGATools._ORIGIN_BR:
  69098. x_start = header.width - 1;
  69099. x_step = -1;
  69100. x_end = -1;
  69101. y_start = header.height - 1;
  69102. y_step = -1;
  69103. y_end = -1;
  69104. break;
  69105. }
  69106. // Load the specify method
  69107. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  69108. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  69109. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  69110. };
  69111. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  69112. var image = pixel_data, colormap = palettes;
  69113. var width = header.width, height = header.height;
  69114. var color, i = 0, x, y;
  69115. var imageData = new Uint8Array(width * height * 4);
  69116. for (y = y_start; y !== y_end; y += y_step) {
  69117. for (x = x_start; x !== x_end; x += x_step, i++) {
  69118. color = image[i];
  69119. imageData[(x + width * y) * 4 + 3] = 255;
  69120. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  69121. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  69122. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  69123. }
  69124. }
  69125. return imageData;
  69126. };
  69127. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  69128. var image = pixel_data;
  69129. var width = header.width, height = header.height;
  69130. var color, i = 0, x, y;
  69131. var imageData = new Uint8Array(width * height * 4);
  69132. for (y = y_start; y !== y_end; y += y_step) {
  69133. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  69134. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  69135. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  69136. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  69137. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  69138. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  69139. }
  69140. }
  69141. return imageData;
  69142. };
  69143. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  69144. var image = pixel_data;
  69145. var width = header.width, height = header.height;
  69146. var i = 0, x, y;
  69147. var imageData = new Uint8Array(width * height * 4);
  69148. for (y = y_start; y !== y_end; y += y_step) {
  69149. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  69150. imageData[(x + width * y) * 4 + 3] = 255;
  69151. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  69152. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  69153. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  69154. }
  69155. }
  69156. return imageData;
  69157. };
  69158. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  69159. var image = pixel_data;
  69160. var width = header.width, height = header.height;
  69161. var i = 0, x, y;
  69162. var imageData = new Uint8Array(width * height * 4);
  69163. for (y = y_start; y !== y_end; y += y_step) {
  69164. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  69165. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  69166. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  69167. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  69168. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  69169. }
  69170. }
  69171. return imageData;
  69172. };
  69173. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  69174. var image = pixel_data;
  69175. var width = header.width, height = header.height;
  69176. var color, i = 0, x, y;
  69177. var imageData = new Uint8Array(width * height * 4);
  69178. for (y = y_start; y !== y_end; y += y_step) {
  69179. for (x = x_start; x !== x_end; x += x_step, i++) {
  69180. color = image[i];
  69181. imageData[(x + width * y) * 4 + 0] = color;
  69182. imageData[(x + width * y) * 4 + 1] = color;
  69183. imageData[(x + width * y) * 4 + 2] = color;
  69184. imageData[(x + width * y) * 4 + 3] = 255;
  69185. }
  69186. }
  69187. return imageData;
  69188. };
  69189. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  69190. var image = pixel_data;
  69191. var width = header.width, height = header.height;
  69192. var i = 0, x, y;
  69193. var imageData = new Uint8Array(width * height * 4);
  69194. for (y = y_start; y !== y_end; y += y_step) {
  69195. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  69196. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  69197. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  69198. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  69199. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  69200. }
  69201. }
  69202. return imageData;
  69203. };
  69204. //private static _TYPE_NO_DATA = 0;
  69205. TGATools._TYPE_INDEXED = 1;
  69206. TGATools._TYPE_RGB = 2;
  69207. TGATools._TYPE_GREY = 3;
  69208. TGATools._TYPE_RLE_INDEXED = 9;
  69209. TGATools._TYPE_RLE_RGB = 10;
  69210. TGATools._TYPE_RLE_GREY = 11;
  69211. TGATools._ORIGIN_MASK = 0x30;
  69212. TGATools._ORIGIN_SHIFT = 0x04;
  69213. TGATools._ORIGIN_BL = 0x00;
  69214. TGATools._ORIGIN_BR = 0x01;
  69215. TGATools._ORIGIN_UL = 0x02;
  69216. TGATools._ORIGIN_UR = 0x03;
  69217. return TGATools;
  69218. }());
  69219. Internals.TGATools = TGATools;
  69220. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  69221. })(BABYLON || (BABYLON = {}));
  69222. //# sourceMappingURL=babylon.tga.js.map
  69223. var BABYLON;
  69224. (function (BABYLON) {
  69225. var Internals;
  69226. (function (Internals) {
  69227. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  69228. // All values and structures referenced from:
  69229. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  69230. var DDS_MAGIC = 0x20534444;
  69231. var
  69232. //DDSD_CAPS = 0x1,
  69233. //DDSD_HEIGHT = 0x2,
  69234. //DDSD_WIDTH = 0x4,
  69235. //DDSD_PITCH = 0x8,
  69236. //DDSD_PIXELFORMAT = 0x1000,
  69237. DDSD_MIPMAPCOUNT = 0x20000;
  69238. //DDSD_LINEARSIZE = 0x80000,
  69239. //DDSD_DEPTH = 0x800000;
  69240. // var DDSCAPS_COMPLEX = 0x8,
  69241. // DDSCAPS_MIPMAP = 0x400000,
  69242. // DDSCAPS_TEXTURE = 0x1000;
  69243. var DDSCAPS2_CUBEMAP = 0x200;
  69244. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  69245. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  69246. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  69247. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  69248. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  69249. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  69250. // DDSCAPS2_VOLUME = 0x200000;
  69251. var
  69252. //DDPF_ALPHAPIXELS = 0x1,
  69253. //DDPF_ALPHA = 0x2,
  69254. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  69255. //DDPF_YUV = 0x200,
  69256. DDPF_LUMINANCE = 0x20000;
  69257. function FourCCToInt32(value) {
  69258. return value.charCodeAt(0) +
  69259. (value.charCodeAt(1) << 8) +
  69260. (value.charCodeAt(2) << 16) +
  69261. (value.charCodeAt(3) << 24);
  69262. }
  69263. function Int32ToFourCC(value) {
  69264. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  69265. }
  69266. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  69267. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  69268. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  69269. var FOURCC_DX10 = FourCCToInt32("DX10");
  69270. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  69271. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  69272. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  69273. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  69274. var headerLengthInt = 31; // The header length in 32 bit ints
  69275. // Offsets into the header array
  69276. var off_magic = 0;
  69277. var off_size = 1;
  69278. var off_flags = 2;
  69279. var off_height = 3;
  69280. var off_width = 4;
  69281. var off_mipmapCount = 7;
  69282. var off_pfFlags = 20;
  69283. var off_pfFourCC = 21;
  69284. var off_RGBbpp = 22;
  69285. // var off_RMask = 23;
  69286. // var off_GMask = 24;
  69287. // var off_BMask = 25;
  69288. // var off_AMask = 26;
  69289. // var off_caps1 = 27;
  69290. var off_caps2 = 28;
  69291. // var off_caps3 = 29;
  69292. // var off_caps4 = 30;
  69293. var off_dxgiFormat = 32;
  69294. ;
  69295. var DDSTools = /** @class */ (function () {
  69296. function DDSTools() {
  69297. }
  69298. DDSTools.GetDDSInfo = function (arrayBuffer) {
  69299. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  69300. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  69301. var mipmapCount = 1;
  69302. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  69303. mipmapCount = Math.max(1, header[off_mipmapCount]);
  69304. }
  69305. var fourCC = header[off_pfFourCC];
  69306. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  69307. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69308. switch (fourCC) {
  69309. case FOURCC_D3DFMT_R16G16B16A16F:
  69310. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69311. break;
  69312. case FOURCC_D3DFMT_R32G32B32A32F:
  69313. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69314. break;
  69315. case FOURCC_DX10:
  69316. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  69317. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69318. break;
  69319. }
  69320. }
  69321. return {
  69322. width: header[off_width],
  69323. height: header[off_height],
  69324. mipmapCount: mipmapCount,
  69325. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  69326. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  69327. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  69328. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  69329. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  69330. dxgiFormat: dxgiFormat,
  69331. textureType: textureType
  69332. };
  69333. };
  69334. DDSTools._ToHalfFloat = function (value) {
  69335. if (!DDSTools._FloatView) {
  69336. DDSTools._FloatView = new Float32Array(1);
  69337. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  69338. }
  69339. DDSTools._FloatView[0] = value;
  69340. var x = DDSTools._Int32View[0];
  69341. var bits = (x >> 16) & 0x8000; /* Get the sign */
  69342. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  69343. var e = (x >> 23) & 0xff; /* Using int is faster here */
  69344. /* If zero, or denormal, or exponent underflows too much for a denormal
  69345. * half, return signed zero. */
  69346. if (e < 103) {
  69347. return bits;
  69348. }
  69349. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  69350. if (e > 142) {
  69351. bits |= 0x7c00;
  69352. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  69353. * not Inf, so make sure we set one mantissa bit too. */
  69354. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  69355. return bits;
  69356. }
  69357. /* If exponent underflows but not too much, return a denormal */
  69358. if (e < 113) {
  69359. m |= 0x0800;
  69360. /* Extra rounding may overflow and set mantissa to 0 and exponent
  69361. * to 1, which is OK. */
  69362. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  69363. return bits;
  69364. }
  69365. bits |= ((e - 112) << 10) | (m >> 1);
  69366. bits += m & 1;
  69367. return bits;
  69368. };
  69369. DDSTools._FromHalfFloat = function (value) {
  69370. var s = (value & 0x8000) >> 15;
  69371. var e = (value & 0x7C00) >> 10;
  69372. var f = value & 0x03FF;
  69373. if (e === 0) {
  69374. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  69375. }
  69376. else if (e == 0x1F) {
  69377. return f ? NaN : ((s ? -1 : 1) * Infinity);
  69378. }
  69379. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  69380. };
  69381. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  69382. var destArray = new Float32Array(dataLength);
  69383. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  69384. var index = 0;
  69385. for (var y = 0; y < height; y++) {
  69386. for (var x = 0; x < width; x++) {
  69387. var srcPos = (x + y * width) * 4;
  69388. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  69389. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  69390. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  69391. if (DDSTools.StoreLODInAlphaChannel) {
  69392. destArray[index + 3] = lod;
  69393. }
  69394. else {
  69395. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  69396. }
  69397. index += 4;
  69398. }
  69399. }
  69400. return destArray;
  69401. };
  69402. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  69403. if (DDSTools.StoreLODInAlphaChannel) {
  69404. var destArray = new Uint16Array(dataLength);
  69405. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  69406. var index = 0;
  69407. for (var y = 0; y < height; y++) {
  69408. for (var x = 0; x < width; x++) {
  69409. var srcPos = (x + y * width) * 4;
  69410. destArray[index] = srcData[srcPos];
  69411. destArray[index + 1] = srcData[srcPos + 1];
  69412. destArray[index + 2] = srcData[srcPos + 2];
  69413. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  69414. index += 4;
  69415. }
  69416. }
  69417. return destArray;
  69418. }
  69419. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  69420. };
  69421. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  69422. if (DDSTools.StoreLODInAlphaChannel) {
  69423. var destArray = new Float32Array(dataLength);
  69424. var srcData = new Float32Array(arrayBuffer, dataOffset);
  69425. var index = 0;
  69426. for (var y = 0; y < height; y++) {
  69427. for (var x = 0; x < width; x++) {
  69428. var srcPos = (x + y * width) * 4;
  69429. destArray[index] = srcData[srcPos];
  69430. destArray[index + 1] = srcData[srcPos + 1];
  69431. destArray[index + 2] = srcData[srcPos + 2];
  69432. destArray[index + 3] = lod;
  69433. index += 4;
  69434. }
  69435. }
  69436. return destArray;
  69437. }
  69438. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  69439. };
  69440. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  69441. var destArray = new Uint8Array(dataLength);
  69442. var srcData = new Float32Array(arrayBuffer, dataOffset);
  69443. var index = 0;
  69444. for (var y = 0; y < height; y++) {
  69445. for (var x = 0; x < width; x++) {
  69446. var srcPos = (x + y * width) * 4;
  69447. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  69448. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  69449. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  69450. if (DDSTools.StoreLODInAlphaChannel) {
  69451. destArray[index + 3] = lod;
  69452. }
  69453. else {
  69454. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  69455. }
  69456. index += 4;
  69457. }
  69458. }
  69459. return destArray;
  69460. };
  69461. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  69462. var destArray = new Uint8Array(dataLength);
  69463. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  69464. var index = 0;
  69465. for (var y = 0; y < height; y++) {
  69466. for (var x = 0; x < width; x++) {
  69467. var srcPos = (x + y * width) * 4;
  69468. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  69469. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  69470. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  69471. if (DDSTools.StoreLODInAlphaChannel) {
  69472. destArray[index + 3] = lod;
  69473. }
  69474. else {
  69475. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  69476. }
  69477. index += 4;
  69478. }
  69479. }
  69480. return destArray;
  69481. };
  69482. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  69483. var byteArray = new Uint8Array(dataLength);
  69484. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  69485. var index = 0;
  69486. for (var y = 0; y < height; y++) {
  69487. for (var x = 0; x < width; x++) {
  69488. var srcPos = (x + y * width) * 4;
  69489. byteArray[index] = srcData[srcPos + 2];
  69490. byteArray[index + 1] = srcData[srcPos + 1];
  69491. byteArray[index + 2] = srcData[srcPos];
  69492. byteArray[index + 3] = srcData[srcPos + 3];
  69493. index += 4;
  69494. }
  69495. }
  69496. return byteArray;
  69497. };
  69498. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  69499. var byteArray = new Uint8Array(dataLength);
  69500. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  69501. var index = 0;
  69502. for (var y = 0; y < height; y++) {
  69503. for (var x = 0; x < width; x++) {
  69504. var srcPos = (x + y * width) * 3;
  69505. byteArray[index] = srcData[srcPos + 2];
  69506. byteArray[index + 1] = srcData[srcPos + 1];
  69507. byteArray[index + 2] = srcData[srcPos];
  69508. index += 3;
  69509. }
  69510. }
  69511. return byteArray;
  69512. };
  69513. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  69514. var byteArray = new Uint8Array(dataLength);
  69515. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  69516. var index = 0;
  69517. for (var y = 0; y < height; y++) {
  69518. for (var x = 0; x < width; x++) {
  69519. var srcPos = (x + y * width);
  69520. byteArray[index] = srcData[srcPos];
  69521. index++;
  69522. }
  69523. }
  69524. return byteArray;
  69525. };
  69526. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  69527. if (lodIndex === void 0) { lodIndex = -1; }
  69528. var ext = engine.getCaps().s3tc;
  69529. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  69530. var fourCC, width, height, dataLength = 0, dataOffset;
  69531. var byteArray, mipmapCount, mip;
  69532. var internalFormat = 0;
  69533. var format = 0;
  69534. var blockBytes = 1;
  69535. if (header[off_magic] !== DDS_MAGIC) {
  69536. BABYLON.Tools.Error("Invalid magic number in DDS header");
  69537. return;
  69538. }
  69539. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  69540. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  69541. return;
  69542. }
  69543. if (info.isCompressed && !ext) {
  69544. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  69545. return;
  69546. }
  69547. var bpp = header[off_RGBbpp];
  69548. dataOffset = header[off_size] + 4;
  69549. var computeFormats = false;
  69550. if (info.isFourCC) {
  69551. fourCC = header[off_pfFourCC];
  69552. switch (fourCC) {
  69553. case FOURCC_DXT1:
  69554. blockBytes = 8;
  69555. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  69556. break;
  69557. case FOURCC_DXT3:
  69558. blockBytes = 16;
  69559. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  69560. break;
  69561. case FOURCC_DXT5:
  69562. blockBytes = 16;
  69563. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  69564. break;
  69565. case FOURCC_D3DFMT_R16G16B16A16F:
  69566. computeFormats = true;
  69567. break;
  69568. case FOURCC_D3DFMT_R32G32B32A32F:
  69569. computeFormats = true;
  69570. break;
  69571. case FOURCC_DX10:
  69572. // There is an additionnal header so dataOffset need to be changed
  69573. dataOffset += 5 * 4; // 5 uints
  69574. var supported = false;
  69575. switch (info.dxgiFormat) {
  69576. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  69577. computeFormats = true;
  69578. supported = true;
  69579. break;
  69580. case DXGI_FORMAT_B8G8R8X8_UNORM:
  69581. info.isRGB = true;
  69582. info.isFourCC = false;
  69583. bpp = 32;
  69584. supported = true;
  69585. break;
  69586. }
  69587. if (supported) {
  69588. break;
  69589. }
  69590. default:
  69591. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  69592. return;
  69593. }
  69594. }
  69595. if (computeFormats) {
  69596. format = engine._getWebGLTextureType(info.textureType);
  69597. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  69598. }
  69599. mipmapCount = 1;
  69600. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  69601. mipmapCount = Math.max(1, header[off_mipmapCount]);
  69602. }
  69603. for (var face = 0; face < faces; face++) {
  69604. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  69605. width = header[off_width];
  69606. height = header[off_height];
  69607. for (mip = 0; mip < mipmapCount; ++mip) {
  69608. if (lodIndex === -1 || lodIndex === mip) {
  69609. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  69610. var i = (lodIndex === -1) ? mip : 0;
  69611. if (!info.isCompressed && info.isFourCC) {
  69612. dataLength = width * height * 4;
  69613. var floatArray = null;
  69614. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  69615. if (bpp === 128) {
  69616. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  69617. }
  69618. else if (bpp === 64) {
  69619. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  69620. }
  69621. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69622. format = engine._getWebGLTextureType(info.textureType);
  69623. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  69624. }
  69625. else {
  69626. if (bpp === 128) {
  69627. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  69628. }
  69629. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  69630. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  69631. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69632. format = engine._getWebGLTextureType(info.textureType);
  69633. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  69634. }
  69635. else {
  69636. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  69637. }
  69638. }
  69639. if (floatArray) {
  69640. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  69641. }
  69642. }
  69643. else if (info.isRGB) {
  69644. if (bpp === 24) {
  69645. dataLength = width * height * 3;
  69646. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  69647. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  69648. }
  69649. else {
  69650. dataLength = width * height * 4;
  69651. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  69652. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  69653. }
  69654. }
  69655. else if (info.isLuminance) {
  69656. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  69657. var unpaddedRowSize = width;
  69658. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  69659. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  69660. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  69661. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  69662. }
  69663. else {
  69664. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  69665. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  69666. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  69667. }
  69668. }
  69669. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  69670. width *= 0.5;
  69671. height *= 0.5;
  69672. width = Math.max(1.0, width);
  69673. height = Math.max(1.0, height);
  69674. }
  69675. if (currentFace !== undefined) {
  69676. // Loading a single face
  69677. break;
  69678. }
  69679. }
  69680. };
  69681. DDSTools.StoreLODInAlphaChannel = false;
  69682. return DDSTools;
  69683. }());
  69684. Internals.DDSTools = DDSTools;
  69685. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  69686. })(BABYLON || (BABYLON = {}));
  69687. //# sourceMappingURL=babylon.dds.js.map
  69688. var BABYLON;
  69689. (function (BABYLON) {
  69690. var Internals;
  69691. (function (Internals) {
  69692. /**
  69693. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  69694. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  69695. */
  69696. var KhronosTextureContainer = /** @class */ (function () {
  69697. /**
  69698. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  69699. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  69700. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  69701. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  69702. */
  69703. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  69704. this.arrayBuffer = arrayBuffer;
  69705. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  69706. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  69707. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  69708. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  69709. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  69710. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  69711. BABYLON.Tools.Error("texture missing KTX identifier");
  69712. return;
  69713. }
  69714. // load the reset of the header in native 32 bit int
  69715. var header = new Int32Array(this.arrayBuffer, 12, 13);
  69716. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  69717. var oppositeEndianess = header[0] === 0x01020304;
  69718. // read all the header elements in order they exist in the file, without modification (sans endainness)
  69719. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  69720. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  69721. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  69722. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  69723. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  69724. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  69725. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  69726. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  69727. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  69728. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  69729. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  69730. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  69731. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  69732. if (this.glType !== 0) {
  69733. BABYLON.Tools.Error("only compressed formats currently supported");
  69734. return;
  69735. }
  69736. else {
  69737. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  69738. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  69739. }
  69740. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  69741. BABYLON.Tools.Error("only 2D textures currently supported");
  69742. return;
  69743. }
  69744. if (this.numberOfArrayElements !== 0) {
  69745. BABYLON.Tools.Error("texture arrays not currently supported");
  69746. return;
  69747. }
  69748. if (this.numberOfFaces !== facesExpected) {
  69749. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  69750. return;
  69751. }
  69752. // we now have a completely validated file, so could use existence of loadType as success
  69753. // would need to make this more elaborate & adjust checks above to support more than one load type
  69754. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  69755. }
  69756. // not as fast hardware based, but will probably never need to use
  69757. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  69758. return ((val & 0xFF) << 24)
  69759. | ((val & 0xFF00) << 8)
  69760. | ((val >> 8) & 0xFF00)
  69761. | ((val >> 24) & 0xFF);
  69762. };
  69763. /**
  69764. * It is assumed that the texture has already been created & is currently bound
  69765. */
  69766. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  69767. switch (this.loadType) {
  69768. case KhronosTextureContainer.COMPRESSED_2D:
  69769. this._upload2DCompressedLevels(gl, loadMipmaps);
  69770. break;
  69771. case KhronosTextureContainer.TEX_2D:
  69772. case KhronosTextureContainer.COMPRESSED_3D:
  69773. case KhronosTextureContainer.TEX_3D:
  69774. }
  69775. };
  69776. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  69777. // initialize width & height for level 1
  69778. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  69779. var width = this.pixelWidth;
  69780. var height = this.pixelHeight;
  69781. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  69782. for (var level = 0; level < mipmapCount; level++) {
  69783. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  69784. for (var face = 0; face < this.numberOfFaces; face++) {
  69785. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  69786. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  69787. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  69788. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  69789. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  69790. }
  69791. width = Math.max(1.0, width * 0.5);
  69792. height = Math.max(1.0, height * 0.5);
  69793. }
  69794. };
  69795. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  69796. // load types
  69797. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  69798. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  69799. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  69800. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  69801. return KhronosTextureContainer;
  69802. }());
  69803. Internals.KhronosTextureContainer = KhronosTextureContainer;
  69804. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  69805. })(BABYLON || (BABYLON = {}));
  69806. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  69807. var BABYLON;
  69808. (function (BABYLON) {
  69809. var Debug;
  69810. (function (Debug) {
  69811. /**
  69812. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  69813. */
  69814. var SkeletonViewer = /** @class */ (function () {
  69815. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  69816. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  69817. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  69818. this.skeleton = skeleton;
  69819. this.mesh = mesh;
  69820. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  69821. this.renderingGroupId = renderingGroupId;
  69822. this.color = BABYLON.Color3.White();
  69823. this._debugLines = new Array();
  69824. this._isEnabled = false;
  69825. this._scene = scene;
  69826. this.update();
  69827. this._renderFunction = this.update.bind(this);
  69828. }
  69829. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  69830. get: function () {
  69831. return this._isEnabled;
  69832. },
  69833. set: function (value) {
  69834. if (this._isEnabled === value) {
  69835. return;
  69836. }
  69837. this._isEnabled = value;
  69838. if (value) {
  69839. this._scene.registerBeforeRender(this._renderFunction);
  69840. }
  69841. else {
  69842. this._scene.unregisterBeforeRender(this._renderFunction);
  69843. }
  69844. },
  69845. enumerable: true,
  69846. configurable: true
  69847. });
  69848. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  69849. if (x === void 0) { x = 0; }
  69850. if (y === void 0) { y = 0; }
  69851. if (z === void 0) { z = 0; }
  69852. var tmat = BABYLON.Tmp.Matrix[0];
  69853. var parentBone = bone.getParent();
  69854. tmat.copyFrom(bone.getLocalMatrix());
  69855. if (x !== 0 || y !== 0 || z !== 0) {
  69856. var tmat2 = BABYLON.Tmp.Matrix[1];
  69857. BABYLON.Matrix.IdentityToRef(tmat2);
  69858. tmat2.m[12] = x;
  69859. tmat2.m[13] = y;
  69860. tmat2.m[14] = z;
  69861. tmat2.multiplyToRef(tmat, tmat);
  69862. }
  69863. if (parentBone) {
  69864. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  69865. }
  69866. tmat.multiplyToRef(meshMat, tmat);
  69867. position.x = tmat.m[12];
  69868. position.y = tmat.m[13];
  69869. position.z = tmat.m[14];
  69870. };
  69871. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  69872. var len = bones.length;
  69873. var meshPos = this.mesh.position;
  69874. for (var i = 0; i < len; i++) {
  69875. var bone = bones[i];
  69876. var points = this._debugLines[i];
  69877. if (!points) {
  69878. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69879. this._debugLines[i] = points;
  69880. }
  69881. this._getBonePosition(points[0], bone, meshMat);
  69882. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  69883. points[0].subtractInPlace(meshPos);
  69884. points[1].subtractInPlace(meshPos);
  69885. }
  69886. };
  69887. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  69888. var len = bones.length;
  69889. var boneNum = 0;
  69890. var meshPos = this.mesh.position;
  69891. for (var i = len - 1; i >= 0; i--) {
  69892. var childBone = bones[i];
  69893. var parentBone = childBone.getParent();
  69894. if (!parentBone) {
  69895. continue;
  69896. }
  69897. var points = this._debugLines[boneNum];
  69898. if (!points) {
  69899. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69900. this._debugLines[boneNum] = points;
  69901. }
  69902. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  69903. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  69904. points[0].subtractInPlace(meshPos);
  69905. points[1].subtractInPlace(meshPos);
  69906. boneNum++;
  69907. }
  69908. };
  69909. SkeletonViewer.prototype.update = function () {
  69910. if (this.autoUpdateBonesMatrices) {
  69911. this.skeleton.computeAbsoluteTransforms();
  69912. }
  69913. if (this.skeleton.bones[0].length === undefined) {
  69914. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  69915. }
  69916. else {
  69917. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  69918. }
  69919. if (!this._debugMesh) {
  69920. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  69921. this._debugMesh.renderingGroupId = this.renderingGroupId;
  69922. }
  69923. else {
  69924. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  69925. }
  69926. this._debugMesh.position.copyFrom(this.mesh.position);
  69927. this._debugMesh.color = this.color;
  69928. };
  69929. SkeletonViewer.prototype.dispose = function () {
  69930. if (this._debugMesh) {
  69931. this.isEnabled = false;
  69932. this._debugMesh.dispose();
  69933. this._debugMesh = null;
  69934. }
  69935. };
  69936. return SkeletonViewer;
  69937. }());
  69938. Debug.SkeletonViewer = SkeletonViewer;
  69939. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  69940. })(BABYLON || (BABYLON = {}));
  69941. //# sourceMappingURL=babylon.skeletonViewer.js.map
  69942. var BABYLON;
  69943. (function (BABYLON) {
  69944. var Debug;
  69945. (function (Debug) {
  69946. var AxesViewer = /** @class */ (function () {
  69947. function AxesViewer(scene, scaleLines) {
  69948. if (scaleLines === void 0) { scaleLines = 1; }
  69949. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69950. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69951. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69952. this.scaleLines = 1;
  69953. this.scaleLines = scaleLines;
  69954. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  69955. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  69956. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  69957. this._xmesh.renderingGroupId = 2;
  69958. this._ymesh.renderingGroupId = 2;
  69959. this._zmesh.renderingGroupId = 2;
  69960. this._xmesh.material.checkReadyOnlyOnce = true;
  69961. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  69962. this._ymesh.material.checkReadyOnlyOnce = true;
  69963. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  69964. this._zmesh.material.checkReadyOnlyOnce = true;
  69965. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  69966. this.scene = scene;
  69967. }
  69968. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  69969. var scaleLines = this.scaleLines;
  69970. if (this._xmesh) {
  69971. this._xmesh.position.copyFrom(position);
  69972. }
  69973. if (this._ymesh) {
  69974. this._ymesh.position.copyFrom(position);
  69975. }
  69976. if (this._zmesh) {
  69977. this._zmesh.position.copyFrom(position);
  69978. }
  69979. var point2 = this._xline[1];
  69980. point2.x = xaxis.x * scaleLines;
  69981. point2.y = xaxis.y * scaleLines;
  69982. point2.z = xaxis.z * scaleLines;
  69983. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  69984. point2 = this._yline[1];
  69985. point2.x = yaxis.x * scaleLines;
  69986. point2.y = yaxis.y * scaleLines;
  69987. point2.z = yaxis.z * scaleLines;
  69988. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  69989. point2 = this._zline[1];
  69990. point2.x = zaxis.x * scaleLines;
  69991. point2.y = zaxis.y * scaleLines;
  69992. point2.z = zaxis.z * scaleLines;
  69993. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  69994. };
  69995. AxesViewer.prototype.dispose = function () {
  69996. if (this._xmesh) {
  69997. this._xmesh.dispose();
  69998. }
  69999. if (this._ymesh) {
  70000. this._ymesh.dispose();
  70001. }
  70002. if (this._zmesh) {
  70003. this._zmesh.dispose();
  70004. }
  70005. this._xmesh = null;
  70006. this._ymesh = null;
  70007. this._zmesh = null;
  70008. this.scene = null;
  70009. };
  70010. return AxesViewer;
  70011. }());
  70012. Debug.AxesViewer = AxesViewer;
  70013. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  70014. })(BABYLON || (BABYLON = {}));
  70015. //# sourceMappingURL=babylon.axesViewer.js.map
  70016. var BABYLON;
  70017. (function (BABYLON) {
  70018. var Debug;
  70019. (function (Debug) {
  70020. var BoneAxesViewer = /** @class */ (function (_super) {
  70021. __extends(BoneAxesViewer, _super);
  70022. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  70023. if (scaleLines === void 0) { scaleLines = 1; }
  70024. var _this = _super.call(this, scene, scaleLines) || this;
  70025. _this.pos = BABYLON.Vector3.Zero();
  70026. _this.xaxis = BABYLON.Vector3.Zero();
  70027. _this.yaxis = BABYLON.Vector3.Zero();
  70028. _this.zaxis = BABYLON.Vector3.Zero();
  70029. _this.mesh = mesh;
  70030. _this.bone = bone;
  70031. return _this;
  70032. }
  70033. BoneAxesViewer.prototype.update = function () {
  70034. if (!this.mesh || !this.bone) {
  70035. return;
  70036. }
  70037. var bone = this.bone;
  70038. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  70039. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  70040. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  70041. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  70042. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  70043. };
  70044. BoneAxesViewer.prototype.dispose = function () {
  70045. if (this.mesh) {
  70046. this.mesh = null;
  70047. this.bone = null;
  70048. _super.prototype.dispose.call(this);
  70049. }
  70050. };
  70051. return BoneAxesViewer;
  70052. }(Debug.AxesViewer));
  70053. Debug.BoneAxesViewer = BoneAxesViewer;
  70054. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  70055. })(BABYLON || (BABYLON = {}));
  70056. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  70057. var BABYLON;
  70058. (function (BABYLON) {
  70059. var RayHelper = /** @class */ (function () {
  70060. function RayHelper(ray) {
  70061. this.ray = ray;
  70062. }
  70063. RayHelper.CreateAndShow = function (ray, scene, color) {
  70064. var helper = new RayHelper(ray);
  70065. helper.show(scene, color);
  70066. return helper;
  70067. };
  70068. RayHelper.prototype.show = function (scene, color) {
  70069. if (!this._renderFunction && this.ray) {
  70070. var ray = this.ray;
  70071. this._renderFunction = this._render.bind(this);
  70072. this._scene = scene;
  70073. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  70074. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  70075. if (this._renderFunction) {
  70076. this._scene.registerBeforeRender(this._renderFunction);
  70077. }
  70078. }
  70079. if (color && this._renderLine) {
  70080. this._renderLine.color.copyFrom(color);
  70081. }
  70082. };
  70083. RayHelper.prototype.hide = function () {
  70084. if (this._renderFunction && this._scene) {
  70085. this._scene.unregisterBeforeRender(this._renderFunction);
  70086. this._scene = null;
  70087. this._renderFunction = null;
  70088. if (this._renderLine) {
  70089. this._renderLine.dispose();
  70090. this._renderLine = null;
  70091. }
  70092. this._renderPoints = [];
  70093. }
  70094. };
  70095. RayHelper.prototype._render = function () {
  70096. var ray = this.ray;
  70097. if (!ray) {
  70098. return;
  70099. }
  70100. var point = this._renderPoints[1];
  70101. var len = Math.min(ray.length, 1000000);
  70102. point.copyFrom(ray.direction);
  70103. point.scaleInPlace(len);
  70104. point.addInPlace(ray.origin);
  70105. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  70106. };
  70107. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  70108. this._attachedToMesh = mesh;
  70109. var ray = this.ray;
  70110. if (!ray) {
  70111. return;
  70112. }
  70113. if (!ray.direction) {
  70114. ray.direction = BABYLON.Vector3.Zero();
  70115. }
  70116. if (!ray.origin) {
  70117. ray.origin = BABYLON.Vector3.Zero();
  70118. }
  70119. if (length) {
  70120. ray.length = length;
  70121. }
  70122. if (!meshSpaceOrigin) {
  70123. meshSpaceOrigin = BABYLON.Vector3.Zero();
  70124. }
  70125. if (!meshSpaceDirection) {
  70126. // -1 so that this will work with Mesh.lookAt
  70127. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  70128. }
  70129. if (!this._meshSpaceDirection) {
  70130. this._meshSpaceDirection = meshSpaceDirection.clone();
  70131. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  70132. }
  70133. else {
  70134. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  70135. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  70136. }
  70137. if (!this._updateToMeshFunction) {
  70138. this._updateToMeshFunction = this._updateToMesh.bind(this);
  70139. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  70140. }
  70141. this._updateToMesh();
  70142. };
  70143. RayHelper.prototype.detachFromMesh = function () {
  70144. if (this._attachedToMesh) {
  70145. if (this._updateToMeshFunction) {
  70146. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  70147. }
  70148. this._attachedToMesh = null;
  70149. this._updateToMeshFunction = null;
  70150. }
  70151. };
  70152. RayHelper.prototype._updateToMesh = function () {
  70153. var ray = this.ray;
  70154. if (!this._attachedToMesh || !ray) {
  70155. return;
  70156. }
  70157. if (this._attachedToMesh._isDisposed) {
  70158. this.detachFromMesh();
  70159. return;
  70160. }
  70161. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  70162. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  70163. };
  70164. RayHelper.prototype.dispose = function () {
  70165. this.hide();
  70166. this.detachFromMesh();
  70167. this.ray = null;
  70168. };
  70169. return RayHelper;
  70170. }());
  70171. BABYLON.RayHelper = RayHelper;
  70172. })(BABYLON || (BABYLON = {}));
  70173. //# sourceMappingURL=babylon.rayHelper.js.map
  70174. var BABYLON;
  70175. (function (BABYLON) {
  70176. // load the inspector using require, if not present in the global namespace.
  70177. var DebugLayer = /** @class */ (function () {
  70178. function DebugLayer(scene) {
  70179. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  70180. this._scene = scene;
  70181. // load inspector using require, if it doesn't exist on the global namespace.
  70182. }
  70183. /** Creates the inspector window. */
  70184. DebugLayer.prototype._createInspector = function (config) {
  70185. if (config === void 0) { config = {}; }
  70186. var popup = config.popup || false;
  70187. var initialTab = config.initialTab || 0;
  70188. var parentElement = config.parentElement || null;
  70189. if (!this._inspector) {
  70190. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  70191. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  70192. } // else nothing to do,; instance is already existing
  70193. };
  70194. DebugLayer.prototype.isVisible = function () {
  70195. if (!this._inspector) {
  70196. return false;
  70197. }
  70198. return true;
  70199. };
  70200. DebugLayer.prototype.hide = function () {
  70201. if (this._inspector) {
  70202. try {
  70203. this._inspector.dispose();
  70204. }
  70205. catch (e) {
  70206. // If the inspector has been removed directly from the inspector tool
  70207. }
  70208. this._inspector = null;
  70209. }
  70210. };
  70211. DebugLayer.prototype.show = function (config) {
  70212. if (config === void 0) { config = {}; }
  70213. if (typeof this.BJSINSPECTOR == 'undefined') {
  70214. // Load inspector and add it to the DOM
  70215. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  70216. }
  70217. else {
  70218. // Otherwise creates the inspector
  70219. this._createInspector(config);
  70220. }
  70221. };
  70222. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  70223. return DebugLayer;
  70224. }());
  70225. BABYLON.DebugLayer = DebugLayer;
  70226. })(BABYLON || (BABYLON = {}));
  70227. //# sourceMappingURL=babylon.debugLayer.js.map
  70228. var BABYLON;
  70229. (function (BABYLON) {
  70230. var Debug;
  70231. (function (Debug) {
  70232. var PhysicsViewer = /** @class */ (function () {
  70233. function PhysicsViewer(scene) {
  70234. this._impostors = [];
  70235. this._meshes = [];
  70236. this._numMeshes = 0;
  70237. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  70238. var physicEngine = this._scene.getPhysicsEngine();
  70239. if (physicEngine) {
  70240. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  70241. }
  70242. }
  70243. PhysicsViewer.prototype._updateDebugMeshes = function () {
  70244. var plugin = this._physicsEnginePlugin;
  70245. for (var i = 0; i < this._numMeshes; i++) {
  70246. var impostor = this._impostors[i];
  70247. if (!impostor) {
  70248. continue;
  70249. }
  70250. if (impostor.isDisposed) {
  70251. this.hideImpostor(this._impostors[i--]);
  70252. }
  70253. else {
  70254. var mesh = this._meshes[i];
  70255. if (mesh && plugin) {
  70256. plugin.syncMeshWithImpostor(mesh, impostor);
  70257. }
  70258. }
  70259. }
  70260. };
  70261. PhysicsViewer.prototype.showImpostor = function (impostor) {
  70262. if (!this._scene) {
  70263. return;
  70264. }
  70265. for (var i = 0; i < this._numMeshes; i++) {
  70266. if (this._impostors[i] == impostor) {
  70267. return;
  70268. }
  70269. }
  70270. var debugMesh = this._getDebugMesh(impostor, this._scene);
  70271. if (debugMesh) {
  70272. this._impostors[this._numMeshes] = impostor;
  70273. this._meshes[this._numMeshes] = debugMesh;
  70274. if (this._numMeshes === 0) {
  70275. this._renderFunction = this._updateDebugMeshes.bind(this);
  70276. this._scene.registerBeforeRender(this._renderFunction);
  70277. }
  70278. this._numMeshes++;
  70279. }
  70280. };
  70281. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  70282. if (!impostor || !this._scene) {
  70283. return;
  70284. }
  70285. var removed = false;
  70286. for (var i = 0; i < this._numMeshes; i++) {
  70287. if (this._impostors[i] == impostor) {
  70288. var mesh = this._meshes[i];
  70289. if (!mesh) {
  70290. continue;
  70291. }
  70292. this._scene.removeMesh(mesh);
  70293. mesh.dispose();
  70294. this._numMeshes--;
  70295. if (this._numMeshes > 0) {
  70296. this._meshes[i] = this._meshes[this._numMeshes];
  70297. this._impostors[i] = this._impostors[this._numMeshes];
  70298. this._meshes[this._numMeshes] = null;
  70299. this._impostors[this._numMeshes] = null;
  70300. }
  70301. else {
  70302. this._meshes[0] = null;
  70303. this._impostors[0] = null;
  70304. }
  70305. removed = true;
  70306. break;
  70307. }
  70308. }
  70309. if (removed && this._numMeshes === 0) {
  70310. this._scene.unregisterBeforeRender(this._renderFunction);
  70311. }
  70312. };
  70313. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  70314. if (!this._debugMaterial) {
  70315. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  70316. this._debugMaterial.wireframe = true;
  70317. }
  70318. return this._debugMaterial;
  70319. };
  70320. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  70321. if (!this._debugBoxMesh) {
  70322. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  70323. this._debugBoxMesh.renderingGroupId = 1;
  70324. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  70325. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  70326. scene.removeMesh(this._debugBoxMesh);
  70327. }
  70328. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  70329. };
  70330. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  70331. if (!this._debugSphereMesh) {
  70332. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  70333. this._debugSphereMesh.renderingGroupId = 1;
  70334. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  70335. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  70336. scene.removeMesh(this._debugSphereMesh);
  70337. }
  70338. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  70339. };
  70340. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  70341. var mesh = null;
  70342. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  70343. mesh = this._getDebugBoxMesh(scene);
  70344. impostor.getBoxSizeToRef(mesh.scaling);
  70345. }
  70346. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  70347. mesh = this._getDebugSphereMesh(scene);
  70348. var radius = impostor.getRadius();
  70349. mesh.scaling.x = radius * 2;
  70350. mesh.scaling.y = radius * 2;
  70351. mesh.scaling.z = radius * 2;
  70352. }
  70353. return mesh;
  70354. };
  70355. PhysicsViewer.prototype.dispose = function () {
  70356. for (var i = 0; i < this._numMeshes; i++) {
  70357. this.hideImpostor(this._impostors[i]);
  70358. }
  70359. if (this._debugBoxMesh) {
  70360. this._debugBoxMesh.dispose();
  70361. }
  70362. if (this._debugSphereMesh) {
  70363. this._debugSphereMesh.dispose();
  70364. }
  70365. if (this._debugMaterial) {
  70366. this._debugMaterial.dispose();
  70367. }
  70368. this._impostors.length = 0;
  70369. this._scene = null;
  70370. this._physicsEnginePlugin = null;
  70371. };
  70372. return PhysicsViewer;
  70373. }());
  70374. Debug.PhysicsViewer = PhysicsViewer;
  70375. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  70376. })(BABYLON || (BABYLON = {}));
  70377. //# sourceMappingURL=babylon.physicsViewer.js.map
  70378. var BABYLON;
  70379. (function (BABYLON) {
  70380. var BoundingBoxRenderer = /** @class */ (function () {
  70381. function BoundingBoxRenderer(scene) {
  70382. this.frontColor = new BABYLON.Color3(1, 1, 1);
  70383. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  70384. this.showBackLines = true;
  70385. this.renderList = new BABYLON.SmartArray(32);
  70386. this._vertexBuffers = {};
  70387. this._scene = scene;
  70388. }
  70389. BoundingBoxRenderer.prototype._prepareRessources = function () {
  70390. if (this._colorShader) {
  70391. return;
  70392. }
  70393. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  70394. attributes: [BABYLON.VertexBuffer.PositionKind],
  70395. uniforms: ["world", "viewProjection", "color"]
  70396. });
  70397. var engine = this._scene.getEngine();
  70398. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  70399. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  70400. this._createIndexBuffer();
  70401. };
  70402. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  70403. var engine = this._scene.getEngine();
  70404. 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]);
  70405. };
  70406. BoundingBoxRenderer.prototype._rebuild = function () {
  70407. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70408. if (vb) {
  70409. vb._rebuild();
  70410. }
  70411. this._createIndexBuffer();
  70412. };
  70413. BoundingBoxRenderer.prototype.reset = function () {
  70414. this.renderList.reset();
  70415. };
  70416. BoundingBoxRenderer.prototype.render = function () {
  70417. if (this.renderList.length === 0) {
  70418. return;
  70419. }
  70420. this._prepareRessources();
  70421. if (!this._colorShader.isReady()) {
  70422. return;
  70423. }
  70424. var engine = this._scene.getEngine();
  70425. engine.setDepthWrite(false);
  70426. this._colorShader._preBind();
  70427. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  70428. var boundingBox = this.renderList.data[boundingBoxIndex];
  70429. var min = boundingBox.minimum;
  70430. var max = boundingBox.maximum;
  70431. var diff = max.subtract(min);
  70432. var median = min.add(diff.scale(0.5));
  70433. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  70434. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  70435. .multiply(boundingBox.getWorldMatrix());
  70436. // VBOs
  70437. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  70438. if (this.showBackLines) {
  70439. // Back
  70440. engine.setDepthFunctionToGreaterOrEqual();
  70441. this._scene.resetCachedMaterial();
  70442. this._colorShader.setColor4("color", this.backColor.toColor4());
  70443. this._colorShader.bind(worldMatrix);
  70444. // Draw order
  70445. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  70446. }
  70447. // Front
  70448. engine.setDepthFunctionToLess();
  70449. this._scene.resetCachedMaterial();
  70450. this._colorShader.setColor4("color", this.frontColor.toColor4());
  70451. this._colorShader.bind(worldMatrix);
  70452. // Draw order
  70453. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  70454. }
  70455. this._colorShader.unbind();
  70456. engine.setDepthFunctionToLessOrEqual();
  70457. engine.setDepthWrite(true);
  70458. };
  70459. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  70460. this._prepareRessources();
  70461. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  70462. return;
  70463. }
  70464. var engine = this._scene.getEngine();
  70465. engine.setDepthWrite(false);
  70466. engine.setColorWrite(false);
  70467. this._colorShader._preBind();
  70468. var boundingBox = mesh._boundingInfo.boundingBox;
  70469. var min = boundingBox.minimum;
  70470. var max = boundingBox.maximum;
  70471. var diff = max.subtract(min);
  70472. var median = min.add(diff.scale(0.5));
  70473. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  70474. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  70475. .multiply(boundingBox.getWorldMatrix());
  70476. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  70477. engine.setDepthFunctionToLess();
  70478. this._scene.resetCachedMaterial();
  70479. this._colorShader.bind(worldMatrix);
  70480. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 24);
  70481. this._colorShader.unbind();
  70482. engine.setDepthFunctionToLessOrEqual();
  70483. engine.setDepthWrite(true);
  70484. engine.setColorWrite(true);
  70485. };
  70486. BoundingBoxRenderer.prototype.dispose = function () {
  70487. if (!this._colorShader) {
  70488. return;
  70489. }
  70490. this.renderList.dispose();
  70491. this._colorShader.dispose();
  70492. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70493. if (buffer) {
  70494. buffer.dispose();
  70495. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70496. }
  70497. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  70498. };
  70499. return BoundingBoxRenderer;
  70500. }());
  70501. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  70502. })(BABYLON || (BABYLON = {}));
  70503. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  70504. var BABYLON;
  70505. (function (BABYLON) {
  70506. var MorphTarget = /** @class */ (function () {
  70507. function MorphTarget(name, influence) {
  70508. if (influence === void 0) { influence = 0; }
  70509. this.name = name;
  70510. this.animations = new Array();
  70511. this._positions = null;
  70512. this._normals = null;
  70513. this._tangents = null;
  70514. this.onInfluenceChanged = new BABYLON.Observable();
  70515. this.influence = influence;
  70516. }
  70517. Object.defineProperty(MorphTarget.prototype, "influence", {
  70518. get: function () {
  70519. return this._influence;
  70520. },
  70521. set: function (influence) {
  70522. if (this._influence === influence) {
  70523. return;
  70524. }
  70525. var previous = this._influence;
  70526. this._influence = influence;
  70527. if (this.onInfluenceChanged.hasObservers) {
  70528. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  70529. }
  70530. },
  70531. enumerable: true,
  70532. configurable: true
  70533. });
  70534. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  70535. get: function () {
  70536. return !!this._positions;
  70537. },
  70538. enumerable: true,
  70539. configurable: true
  70540. });
  70541. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  70542. get: function () {
  70543. return !!this._normals;
  70544. },
  70545. enumerable: true,
  70546. configurable: true
  70547. });
  70548. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  70549. get: function () {
  70550. return !!this._tangents;
  70551. },
  70552. enumerable: true,
  70553. configurable: true
  70554. });
  70555. MorphTarget.prototype.setPositions = function (data) {
  70556. this._positions = data;
  70557. };
  70558. MorphTarget.prototype.getPositions = function () {
  70559. return this._positions;
  70560. };
  70561. MorphTarget.prototype.setNormals = function (data) {
  70562. this._normals = data;
  70563. };
  70564. MorphTarget.prototype.getNormals = function () {
  70565. return this._normals;
  70566. };
  70567. MorphTarget.prototype.setTangents = function (data) {
  70568. this._tangents = data;
  70569. };
  70570. MorphTarget.prototype.getTangents = function () {
  70571. return this._tangents;
  70572. };
  70573. /**
  70574. * Serializes the current target into a Serialization object.
  70575. * Returns the serialized object.
  70576. */
  70577. MorphTarget.prototype.serialize = function () {
  70578. var serializationObject = {};
  70579. serializationObject.name = this.name;
  70580. serializationObject.influence = this.influence;
  70581. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  70582. if (this.hasNormals) {
  70583. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  70584. }
  70585. if (this.hasTangents) {
  70586. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  70587. }
  70588. // Animations
  70589. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  70590. return serializationObject;
  70591. };
  70592. // Statics
  70593. MorphTarget.Parse = function (serializationObject) {
  70594. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  70595. result.setPositions(serializationObject.positions);
  70596. if (serializationObject.normals) {
  70597. result.setNormals(serializationObject.normals);
  70598. }
  70599. if (serializationObject.tangents) {
  70600. result.setTangents(serializationObject.tangents);
  70601. }
  70602. // Animations
  70603. if (serializationObject.animations) {
  70604. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  70605. var parsedAnimation = serializationObject.animations[animationIndex];
  70606. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  70607. }
  70608. }
  70609. return result;
  70610. };
  70611. MorphTarget.FromMesh = function (mesh, name, influence) {
  70612. if (!name) {
  70613. name = mesh.name;
  70614. }
  70615. var result = new MorphTarget(name, influence);
  70616. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  70617. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  70618. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  70619. }
  70620. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  70621. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  70622. }
  70623. return result;
  70624. };
  70625. return MorphTarget;
  70626. }());
  70627. BABYLON.MorphTarget = MorphTarget;
  70628. })(BABYLON || (BABYLON = {}));
  70629. //# sourceMappingURL=babylon.morphTarget.js.map
  70630. var BABYLON;
  70631. (function (BABYLON) {
  70632. var MorphTargetManager = /** @class */ (function () {
  70633. function MorphTargetManager(scene) {
  70634. if (scene === void 0) { scene = null; }
  70635. this._targets = new Array();
  70636. this._targetObservable = new Array();
  70637. this._activeTargets = new BABYLON.SmartArray(16);
  70638. this._supportsNormals = false;
  70639. this._supportsTangents = false;
  70640. this._vertexCount = 0;
  70641. this._uniqueId = 0;
  70642. this._tempInfluences = new Array();
  70643. if (!scene) {
  70644. scene = BABYLON.Engine.LastCreatedScene;
  70645. }
  70646. this._scene = scene;
  70647. if (this._scene) {
  70648. this._scene.morphTargetManagers.push(this);
  70649. this._uniqueId = this._scene.getUniqueId();
  70650. }
  70651. }
  70652. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  70653. get: function () {
  70654. return this._uniqueId;
  70655. },
  70656. enumerable: true,
  70657. configurable: true
  70658. });
  70659. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  70660. get: function () {
  70661. return this._vertexCount;
  70662. },
  70663. enumerable: true,
  70664. configurable: true
  70665. });
  70666. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  70667. get: function () {
  70668. return this._supportsNormals;
  70669. },
  70670. enumerable: true,
  70671. configurable: true
  70672. });
  70673. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  70674. get: function () {
  70675. return this._supportsTangents;
  70676. },
  70677. enumerable: true,
  70678. configurable: true
  70679. });
  70680. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  70681. get: function () {
  70682. return this._targets.length;
  70683. },
  70684. enumerable: true,
  70685. configurable: true
  70686. });
  70687. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  70688. get: function () {
  70689. return this._activeTargets.length;
  70690. },
  70691. enumerable: true,
  70692. configurable: true
  70693. });
  70694. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  70695. get: function () {
  70696. return this._influences;
  70697. },
  70698. enumerable: true,
  70699. configurable: true
  70700. });
  70701. MorphTargetManager.prototype.getActiveTarget = function (index) {
  70702. return this._activeTargets.data[index];
  70703. };
  70704. MorphTargetManager.prototype.getTarget = function (index) {
  70705. return this._targets[index];
  70706. };
  70707. MorphTargetManager.prototype.addTarget = function (target) {
  70708. var _this = this;
  70709. this._targets.push(target);
  70710. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  70711. _this._syncActiveTargets(needUpdate);
  70712. }));
  70713. this._syncActiveTargets(true);
  70714. };
  70715. MorphTargetManager.prototype.removeTarget = function (target) {
  70716. var index = this._targets.indexOf(target);
  70717. if (index >= 0) {
  70718. this._targets.splice(index, 1);
  70719. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  70720. this._syncActiveTargets(true);
  70721. }
  70722. };
  70723. /**
  70724. * Serializes the current manager into a Serialization object.
  70725. * Returns the serialized object.
  70726. */
  70727. MorphTargetManager.prototype.serialize = function () {
  70728. var serializationObject = {};
  70729. serializationObject.id = this.uniqueId;
  70730. serializationObject.targets = [];
  70731. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  70732. var target = _a[_i];
  70733. serializationObject.targets.push(target.serialize());
  70734. }
  70735. return serializationObject;
  70736. };
  70737. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  70738. var influenceCount = 0;
  70739. this._activeTargets.reset();
  70740. this._supportsNormals = true;
  70741. this._supportsTangents = true;
  70742. this._vertexCount = 0;
  70743. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  70744. var target = _a[_i];
  70745. if (target.influence > 0) {
  70746. this._activeTargets.push(target);
  70747. this._tempInfluences[influenceCount++] = target.influence;
  70748. this._supportsNormals = this._supportsNormals && target.hasNormals;
  70749. this._supportsTangents = this._supportsTangents && target.hasTangents;
  70750. var positions = target.getPositions();
  70751. if (!positions) {
  70752. BABYLON.Tools.Error("Invalid target. Target must positions.");
  70753. return;
  70754. }
  70755. var vertexCount = positions.length / 3;
  70756. if (this._vertexCount === 0) {
  70757. this._vertexCount = vertexCount;
  70758. }
  70759. else if (this._vertexCount !== vertexCount) {
  70760. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  70761. return;
  70762. }
  70763. }
  70764. }
  70765. if (!this._influences || this._influences.length !== influenceCount) {
  70766. this._influences = new Float32Array(influenceCount);
  70767. }
  70768. for (var index = 0; index < influenceCount; index++) {
  70769. this._influences[index] = this._tempInfluences[index];
  70770. }
  70771. if (needUpdate && this._scene) {
  70772. // Flag meshes as dirty to resync with the active targets
  70773. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  70774. var mesh = _c[_b];
  70775. if (mesh.morphTargetManager === this) {
  70776. mesh._syncGeometryWithMorphTargetManager();
  70777. }
  70778. }
  70779. }
  70780. };
  70781. // Statics
  70782. MorphTargetManager.Parse = function (serializationObject, scene) {
  70783. var result = new MorphTargetManager(scene);
  70784. result._uniqueId = serializationObject.id;
  70785. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  70786. var targetData = _a[_i];
  70787. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  70788. }
  70789. return result;
  70790. };
  70791. return MorphTargetManager;
  70792. }());
  70793. BABYLON.MorphTargetManager = MorphTargetManager;
  70794. })(BABYLON || (BABYLON = {}));
  70795. //# sourceMappingURL=babylon.morphTargetManager.js.map
  70796. var BABYLON;
  70797. (function (BABYLON) {
  70798. var Octree = /** @class */ (function () {
  70799. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  70800. if (maxDepth === void 0) { maxDepth = 2; }
  70801. this.maxDepth = maxDepth;
  70802. this.dynamicContent = new Array();
  70803. this._maxBlockCapacity = maxBlockCapacity || 64;
  70804. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  70805. this._creationFunc = creationFunc;
  70806. }
  70807. // Methods
  70808. Octree.prototype.update = function (worldMin, worldMax, entries) {
  70809. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  70810. };
  70811. Octree.prototype.addMesh = function (entry) {
  70812. for (var index = 0; index < this.blocks.length; index++) {
  70813. var block = this.blocks[index];
  70814. block.addEntry(entry);
  70815. }
  70816. };
  70817. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  70818. this._selectionContent.reset();
  70819. for (var index = 0; index < this.blocks.length; index++) {
  70820. var block = this.blocks[index];
  70821. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  70822. }
  70823. if (allowDuplicate) {
  70824. this._selectionContent.concat(this.dynamicContent);
  70825. }
  70826. else {
  70827. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  70828. }
  70829. return this._selectionContent;
  70830. };
  70831. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  70832. this._selectionContent.reset();
  70833. for (var index = 0; index < this.blocks.length; index++) {
  70834. var block = this.blocks[index];
  70835. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  70836. }
  70837. if (allowDuplicate) {
  70838. this._selectionContent.concat(this.dynamicContent);
  70839. }
  70840. else {
  70841. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  70842. }
  70843. return this._selectionContent;
  70844. };
  70845. Octree.prototype.intersectsRay = function (ray) {
  70846. this._selectionContent.reset();
  70847. for (var index = 0; index < this.blocks.length; index++) {
  70848. var block = this.blocks[index];
  70849. block.intersectsRay(ray, this._selectionContent);
  70850. }
  70851. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  70852. return this._selectionContent;
  70853. };
  70854. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  70855. target.blocks = new Array();
  70856. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  70857. // Segmenting space
  70858. for (var x = 0; x < 2; x++) {
  70859. for (var y = 0; y < 2; y++) {
  70860. for (var z = 0; z < 2; z++) {
  70861. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  70862. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  70863. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  70864. block.addEntries(entries);
  70865. target.blocks.push(block);
  70866. }
  70867. }
  70868. }
  70869. };
  70870. Octree.CreationFuncForMeshes = function (entry, block) {
  70871. var boundingInfo = entry.getBoundingInfo();
  70872. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  70873. block.entries.push(entry);
  70874. }
  70875. };
  70876. Octree.CreationFuncForSubMeshes = function (entry, block) {
  70877. var boundingInfo = entry.getBoundingInfo();
  70878. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  70879. block.entries.push(entry);
  70880. }
  70881. };
  70882. return Octree;
  70883. }());
  70884. BABYLON.Octree = Octree;
  70885. })(BABYLON || (BABYLON = {}));
  70886. //# sourceMappingURL=babylon.octree.js.map
  70887. var BABYLON;
  70888. (function (BABYLON) {
  70889. var OctreeBlock = /** @class */ (function () {
  70890. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  70891. this.entries = new Array();
  70892. this._boundingVectors = new Array();
  70893. this._capacity = capacity;
  70894. this._depth = depth;
  70895. this._maxDepth = maxDepth;
  70896. this._creationFunc = creationFunc;
  70897. this._minPoint = minPoint;
  70898. this._maxPoint = maxPoint;
  70899. this._boundingVectors.push(minPoint.clone());
  70900. this._boundingVectors.push(maxPoint.clone());
  70901. this._boundingVectors.push(minPoint.clone());
  70902. this._boundingVectors[2].x = maxPoint.x;
  70903. this._boundingVectors.push(minPoint.clone());
  70904. this._boundingVectors[3].y = maxPoint.y;
  70905. this._boundingVectors.push(minPoint.clone());
  70906. this._boundingVectors[4].z = maxPoint.z;
  70907. this._boundingVectors.push(maxPoint.clone());
  70908. this._boundingVectors[5].z = minPoint.z;
  70909. this._boundingVectors.push(maxPoint.clone());
  70910. this._boundingVectors[6].x = minPoint.x;
  70911. this._boundingVectors.push(maxPoint.clone());
  70912. this._boundingVectors[7].y = minPoint.y;
  70913. }
  70914. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  70915. // Property
  70916. get: function () {
  70917. return this._capacity;
  70918. },
  70919. enumerable: true,
  70920. configurable: true
  70921. });
  70922. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  70923. get: function () {
  70924. return this._minPoint;
  70925. },
  70926. enumerable: true,
  70927. configurable: true
  70928. });
  70929. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  70930. get: function () {
  70931. return this._maxPoint;
  70932. },
  70933. enumerable: true,
  70934. configurable: true
  70935. });
  70936. // Methods
  70937. OctreeBlock.prototype.addEntry = function (entry) {
  70938. if (this.blocks) {
  70939. for (var index = 0; index < this.blocks.length; index++) {
  70940. var block = this.blocks[index];
  70941. block.addEntry(entry);
  70942. }
  70943. return;
  70944. }
  70945. this._creationFunc(entry, this);
  70946. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  70947. this.createInnerBlocks();
  70948. }
  70949. };
  70950. OctreeBlock.prototype.addEntries = function (entries) {
  70951. for (var index = 0; index < entries.length; index++) {
  70952. var mesh = entries[index];
  70953. this.addEntry(mesh);
  70954. }
  70955. };
  70956. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  70957. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  70958. if (this.blocks) {
  70959. for (var index = 0; index < this.blocks.length; index++) {
  70960. var block = this.blocks[index];
  70961. block.select(frustumPlanes, selection, allowDuplicate);
  70962. }
  70963. return;
  70964. }
  70965. if (allowDuplicate) {
  70966. selection.concat(this.entries);
  70967. }
  70968. else {
  70969. selection.concatWithNoDuplicate(this.entries);
  70970. }
  70971. }
  70972. };
  70973. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  70974. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  70975. if (this.blocks) {
  70976. for (var index = 0; index < this.blocks.length; index++) {
  70977. var block = this.blocks[index];
  70978. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  70979. }
  70980. return;
  70981. }
  70982. if (allowDuplicate) {
  70983. selection.concat(this.entries);
  70984. }
  70985. else {
  70986. selection.concatWithNoDuplicate(this.entries);
  70987. }
  70988. }
  70989. };
  70990. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  70991. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  70992. if (this.blocks) {
  70993. for (var index = 0; index < this.blocks.length; index++) {
  70994. var block = this.blocks[index];
  70995. block.intersectsRay(ray, selection);
  70996. }
  70997. return;
  70998. }
  70999. selection.concatWithNoDuplicate(this.entries);
  71000. }
  71001. };
  71002. OctreeBlock.prototype.createInnerBlocks = function () {
  71003. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  71004. };
  71005. return OctreeBlock;
  71006. }());
  71007. BABYLON.OctreeBlock = OctreeBlock;
  71008. })(BABYLON || (BABYLON = {}));
  71009. //# sourceMappingURL=babylon.octreeBlock.js.map
  71010. var BABYLON;
  71011. (function (BABYLON) {
  71012. var SIMDVector3 = /** @class */ (function () {
  71013. function SIMDVector3() {
  71014. }
  71015. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  71016. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  71017. };
  71018. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  71019. var m = transformation.m;
  71020. var m0 = SIMD.Float32x4.load(m, 0);
  71021. var m1 = SIMD.Float32x4.load(m, 4);
  71022. var m2 = SIMD.Float32x4.load(m, 8);
  71023. var m3 = SIMD.Float32x4.load(m, 12);
  71024. 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));
  71025. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  71026. result.x = SIMD.Float32x4.extractLane(r, 0);
  71027. result.y = SIMD.Float32x4.extractLane(r, 1);
  71028. result.z = SIMD.Float32x4.extractLane(r, 2);
  71029. };
  71030. return SIMDVector3;
  71031. }());
  71032. var SIMDMatrix = /** @class */ (function () {
  71033. function SIMDMatrix() {
  71034. }
  71035. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  71036. var tm = this.m;
  71037. var om = other.m;
  71038. var m0 = SIMD.Float32x4.load(om, 0);
  71039. var m1 = SIMD.Float32x4.load(om, 4);
  71040. var m2 = SIMD.Float32x4.load(om, 8);
  71041. var m3 = SIMD.Float32x4.load(om, 12);
  71042. for (var i = 0; i < 16; i += 4) {
  71043. 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)))));
  71044. }
  71045. return this;
  71046. };
  71047. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  71048. var src = this.m;
  71049. var dest = other.m;
  71050. // Load the 4 rows
  71051. var src0 = SIMD.Float32x4.load(src, 0);
  71052. var src1 = SIMD.Float32x4.load(src, 4);
  71053. var src2 = SIMD.Float32x4.load(src, 8);
  71054. var src3 = SIMD.Float32x4.load(src, 12);
  71055. // Transpose the source matrix. Sort of. Not a true transpose operation
  71056. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  71057. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  71058. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  71059. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  71060. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  71061. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  71062. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  71063. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  71064. // This is a true transposition, but it will lead to an incorrect result
  71065. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  71066. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  71067. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  71068. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  71069. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  71070. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  71071. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  71072. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  71073. // ----
  71074. tmp1 = SIMD.Float32x4.mul(row2, row3);
  71075. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  71076. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  71077. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  71078. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  71079. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  71080. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  71081. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  71082. // ----
  71083. tmp1 = SIMD.Float32x4.mul(row1, row2);
  71084. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  71085. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  71086. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  71087. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  71088. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  71089. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  71090. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  71091. // ----
  71092. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  71093. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  71094. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  71095. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  71096. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  71097. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  71098. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  71099. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  71100. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  71101. // ----
  71102. tmp1 = SIMD.Float32x4.mul(row0, row1);
  71103. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  71104. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  71105. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  71106. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  71107. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  71108. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  71109. // ----
  71110. tmp1 = SIMD.Float32x4.mul(row0, row3);
  71111. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  71112. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  71113. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  71114. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  71115. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  71116. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  71117. // ----
  71118. tmp1 = SIMD.Float32x4.mul(row0, row2);
  71119. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  71120. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  71121. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  71122. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  71123. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  71124. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  71125. // Compute determinant
  71126. var det = SIMD.Float32x4.mul(row0, minor0);
  71127. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  71128. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  71129. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  71130. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  71131. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  71132. // These shuffles aren't necessary if the faulty transposition is done
  71133. // up at the top of this function.
  71134. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  71135. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  71136. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  71137. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  71138. // Compute final values by multiplying with 1/det
  71139. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  71140. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  71141. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  71142. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  71143. return this;
  71144. };
  71145. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  71146. var out = result.m;
  71147. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  71148. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  71149. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  71150. // cc.kmVec3Subtract(f, pCenter, pEye);
  71151. var f = SIMD.Float32x4.sub(center, eye);
  71152. // cc.kmVec3Normalize(f, f);
  71153. var tmp = SIMD.Float32x4.mul(f, f);
  71154. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  71155. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  71156. // cc.kmVec3Assign(up, pUp);
  71157. // cc.kmVec3Normalize(up, up);
  71158. tmp = SIMD.Float32x4.mul(up, up);
  71159. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  71160. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  71161. // cc.kmVec3Cross(s, f, up);
  71162. 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)));
  71163. // cc.kmVec3Normalize(s, s);
  71164. tmp = SIMD.Float32x4.mul(s, s);
  71165. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  71166. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  71167. // cc.kmVec3Cross(u, s, f);
  71168. 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)));
  71169. // cc.kmVec3Normalize(s, s);
  71170. tmp = SIMD.Float32x4.mul(s, s);
  71171. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  71172. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  71173. var zero = SIMD.Float32x4.splat(0.0);
  71174. s = SIMD.Float32x4.neg(s);
  71175. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  71176. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  71177. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  71178. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  71179. 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);
  71180. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  71181. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  71182. 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)))));
  71183. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  71184. 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)))));
  71185. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  71186. 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)))));
  71187. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  71188. 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)))));
  71189. };
  71190. return SIMDMatrix;
  71191. }());
  71192. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  71193. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  71194. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  71195. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  71196. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  71197. var SIMDHelper = /** @class */ (function () {
  71198. function SIMDHelper() {
  71199. }
  71200. Object.defineProperty(SIMDHelper, "IsEnabled", {
  71201. get: function () {
  71202. return SIMDHelper._isEnabled;
  71203. },
  71204. enumerable: true,
  71205. configurable: true
  71206. });
  71207. SIMDHelper.DisableSIMD = function () {
  71208. // Replace functions
  71209. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  71210. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  71211. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  71212. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  71213. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  71214. SIMDHelper._isEnabled = false;
  71215. };
  71216. SIMDHelper.EnableSIMD = function () {
  71217. if (self.SIMD === undefined) {
  71218. return;
  71219. }
  71220. // check if polyfills needed
  71221. if (!self.Math.fround) {
  71222. self.Math.fround = (function (array) { return function (x) {
  71223. return array[0] = x, array[0];
  71224. }; })(new Float32Array(1));
  71225. }
  71226. if (!self.Math.imul) {
  71227. self.Math.imul = function (a, b) {
  71228. var ah = (a >>> 16) & 0xffff;
  71229. var al = a & 0xffff;
  71230. var bh = (b >>> 16) & 0xffff;
  71231. var bl = b & 0xffff;
  71232. // the shift by 0 fixes the sign on the high part
  71233. // the final |0 converts the unsigned value into a signed value
  71234. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  71235. };
  71236. }
  71237. // Replace functions
  71238. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  71239. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  71240. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  71241. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  71242. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  71243. SIMDHelper._isEnabled = true;
  71244. };
  71245. SIMDHelper._isEnabled = false;
  71246. return SIMDHelper;
  71247. }());
  71248. BABYLON.SIMDHelper = SIMDHelper;
  71249. })(BABYLON || (BABYLON = {}));
  71250. //# sourceMappingURL=babylon.math.SIMD.js.map
  71251. var BABYLON;
  71252. (function (BABYLON) {
  71253. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  71254. __extends(VRDistortionCorrectionPostProcess, _super);
  71255. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  71256. var _this = _super.call(this, name, "vrDistortionCorrection", [
  71257. 'LensCenter',
  71258. 'Scale',
  71259. 'ScaleIn',
  71260. 'HmdWarpParam'
  71261. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  71262. _this._isRightEye = isRightEye;
  71263. _this._distortionFactors = vrMetrics.distortionK;
  71264. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  71265. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  71266. _this.adaptScaleToCurrentViewport = true;
  71267. _this.onSizeChangedObservable.add(function () {
  71268. _this.aspectRatio = _this.width * .5 / _this.height;
  71269. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  71270. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  71271. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  71272. });
  71273. _this.onApplyObservable.add(function (effect) {
  71274. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  71275. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  71276. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  71277. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  71278. });
  71279. return _this;
  71280. }
  71281. return VRDistortionCorrectionPostProcess;
  71282. }(BABYLON.PostProcess));
  71283. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  71284. })(BABYLON || (BABYLON = {}));
  71285. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  71286. var BABYLON;
  71287. (function (BABYLON) {
  71288. var AnaglyphPostProcess = /** @class */ (function (_super) {
  71289. __extends(AnaglyphPostProcess, _super);
  71290. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  71291. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  71292. _this._passedProcess = rigCameras[0]._rigPostProcess;
  71293. _this.onApplyObservable.add(function (effect) {
  71294. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  71295. });
  71296. return _this;
  71297. }
  71298. return AnaglyphPostProcess;
  71299. }(BABYLON.PostProcess));
  71300. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  71301. })(BABYLON || (BABYLON = {}));
  71302. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  71303. var BABYLON;
  71304. (function (BABYLON) {
  71305. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  71306. __extends(StereoscopicInterlacePostProcess, _super);
  71307. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  71308. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  71309. _this._passedProcess = rigCameras[0]._rigPostProcess;
  71310. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  71311. _this.onSizeChangedObservable.add(function () {
  71312. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  71313. });
  71314. _this.onApplyObservable.add(function (effect) {
  71315. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  71316. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  71317. });
  71318. return _this;
  71319. }
  71320. return StereoscopicInterlacePostProcess;
  71321. }(BABYLON.PostProcess));
  71322. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  71323. })(BABYLON || (BABYLON = {}));
  71324. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  71325. var BABYLON;
  71326. (function (BABYLON) {
  71327. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  71328. function FreeCameraDeviceOrientationInput() {
  71329. var _this = this;
  71330. this._screenOrientationAngle = 0;
  71331. this._screenQuaternion = new BABYLON.Quaternion();
  71332. this._alpha = 0;
  71333. this._beta = 0;
  71334. this._gamma = 0;
  71335. this._orientationChanged = function () {
  71336. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  71337. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  71338. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  71339. };
  71340. this._deviceOrientation = function (evt) {
  71341. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  71342. _this._beta = evt.beta !== null ? evt.beta : 0;
  71343. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  71344. };
  71345. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  71346. this._orientationChanged();
  71347. }
  71348. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  71349. get: function () {
  71350. return this._camera;
  71351. },
  71352. set: function (camera) {
  71353. this._camera = camera;
  71354. if (this._camera != null && !this._camera.rotationQuaternion) {
  71355. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  71356. }
  71357. },
  71358. enumerable: true,
  71359. configurable: true
  71360. });
  71361. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  71362. window.addEventListener("orientationchange", this._orientationChanged);
  71363. window.addEventListener("deviceorientation", this._deviceOrientation);
  71364. //In certain cases, the attach control is called AFTER orientation was changed,
  71365. //So this is needed.
  71366. this._orientationChanged();
  71367. };
  71368. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  71369. window.removeEventListener("orientationchange", this._orientationChanged);
  71370. window.removeEventListener("deviceorientation", this._deviceOrientation);
  71371. };
  71372. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  71373. //if no device orientation provided, don't update the rotation.
  71374. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  71375. if (!this._alpha)
  71376. return;
  71377. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  71378. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  71379. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  71380. //Mirror on XY Plane
  71381. this._camera.rotationQuaternion.z *= -1;
  71382. this._camera.rotationQuaternion.w *= -1;
  71383. };
  71384. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  71385. return "FreeCameraDeviceOrientationInput";
  71386. };
  71387. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  71388. return "deviceOrientation";
  71389. };
  71390. return FreeCameraDeviceOrientationInput;
  71391. }());
  71392. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  71393. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  71394. })(BABYLON || (BABYLON = {}));
  71395. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  71396. var BABYLON;
  71397. (function (BABYLON) {
  71398. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  71399. function ArcRotateCameraVRDeviceOrientationInput() {
  71400. this.alphaCorrection = 1;
  71401. this.betaCorrection = 1;
  71402. this.gammaCorrection = 1;
  71403. this._alpha = 0;
  71404. this._gamma = 0;
  71405. this._dirty = false;
  71406. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  71407. }
  71408. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  71409. this.camera.attachControl(element, noPreventDefault);
  71410. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  71411. };
  71412. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  71413. if (evt.alpha !== null) {
  71414. this._alpha = +evt.alpha | 0;
  71415. }
  71416. if (evt.gamma !== null) {
  71417. this._gamma = +evt.gamma | 0;
  71418. }
  71419. this._dirty = true;
  71420. };
  71421. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  71422. if (this._dirty) {
  71423. this._dirty = false;
  71424. if (this._gamma < 0) {
  71425. this._gamma = 180 + this._gamma;
  71426. }
  71427. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  71428. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  71429. }
  71430. };
  71431. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  71432. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  71433. };
  71434. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  71435. return "ArcRotateCameraVRDeviceOrientationInput";
  71436. };
  71437. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  71438. return "VRDeviceOrientation";
  71439. };
  71440. return ArcRotateCameraVRDeviceOrientationInput;
  71441. }());
  71442. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  71443. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  71444. })(BABYLON || (BABYLON = {}));
  71445. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  71446. var BABYLON;
  71447. (function (BABYLON) {
  71448. var VRCameraMetrics = /** @class */ (function () {
  71449. function VRCameraMetrics() {
  71450. this.compensateDistortion = true;
  71451. }
  71452. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  71453. get: function () {
  71454. return this.hResolution / (2 * this.vResolution);
  71455. },
  71456. enumerable: true,
  71457. configurable: true
  71458. });
  71459. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  71460. get: function () {
  71461. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  71462. },
  71463. enumerable: true,
  71464. configurable: true
  71465. });
  71466. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  71467. get: function () {
  71468. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  71469. var h = (4 * meters) / this.hScreenSize;
  71470. return BABYLON.Matrix.Translation(h, 0, 0);
  71471. },
  71472. enumerable: true,
  71473. configurable: true
  71474. });
  71475. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  71476. get: function () {
  71477. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  71478. var h = (4 * meters) / this.hScreenSize;
  71479. return BABYLON.Matrix.Translation(-h, 0, 0);
  71480. },
  71481. enumerable: true,
  71482. configurable: true
  71483. });
  71484. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  71485. get: function () {
  71486. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  71487. },
  71488. enumerable: true,
  71489. configurable: true
  71490. });
  71491. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  71492. get: function () {
  71493. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  71494. },
  71495. enumerable: true,
  71496. configurable: true
  71497. });
  71498. VRCameraMetrics.GetDefault = function () {
  71499. var result = new VRCameraMetrics();
  71500. result.hResolution = 1280;
  71501. result.vResolution = 800;
  71502. result.hScreenSize = 0.149759993;
  71503. result.vScreenSize = 0.0935999975;
  71504. result.vScreenCenter = 0.0467999987;
  71505. result.eyeToScreenDistance = 0.0410000011;
  71506. result.lensSeparationDistance = 0.0635000020;
  71507. result.interpupillaryDistance = 0.0640000030;
  71508. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  71509. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  71510. result.postProcessScaleFactor = 1.714605507808412;
  71511. result.lensCenterOffset = 0.151976421;
  71512. return result;
  71513. };
  71514. return VRCameraMetrics;
  71515. }());
  71516. BABYLON.VRCameraMetrics = VRCameraMetrics;
  71517. })(BABYLON || (BABYLON = {}));
  71518. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  71519. var BABYLON;
  71520. (function (BABYLON) {
  71521. var WebVRFreeCamera = /** @class */ (function (_super) {
  71522. __extends(WebVRFreeCamera, _super);
  71523. function WebVRFreeCamera(name, position, scene, webVROptions) {
  71524. if (webVROptions === void 0) { webVROptions = {}; }
  71525. var _this = _super.call(this, name, position, scene) || this;
  71526. _this.webVROptions = webVROptions;
  71527. _this._vrDevice = null;
  71528. _this.rawPose = null;
  71529. _this._specsVersion = "1.1";
  71530. _this._attached = false;
  71531. _this._descendants = [];
  71532. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71533. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71534. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  71535. _this._standingMatrix = null;
  71536. // Represents device position and rotation in babylon space
  71537. _this.devicePosition = BABYLON.Vector3.Zero();
  71538. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  71539. _this.deviceScaleFactor = 1;
  71540. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71541. _this._worldToDevice = BABYLON.Matrix.Identity();
  71542. _this.controllers = [];
  71543. _this.onControllersAttachedObservable = new BABYLON.Observable();
  71544. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  71545. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  71546. _this._defaultHeight = 0;
  71547. _this.deviceDistanceToRoomGround = function () {
  71548. if (_this._standingMatrix) {
  71549. // Add standing matrix offset to get real offset from ground in room
  71550. _this._standingMatrix.getTranslationToRef(_this._workingVector);
  71551. return _this._deviceRoomPosition.y + _this._workingVector.y;
  71552. }
  71553. else {
  71554. return _this._defaultHeight;
  71555. }
  71556. };
  71557. _this.useStandingMatrix = function (callback) {
  71558. if (callback === void 0) { callback = function (bool) { }; }
  71559. // Use standing matrix if availible
  71560. if (!navigator || !navigator.getVRDisplays) {
  71561. callback(false);
  71562. }
  71563. else {
  71564. navigator.getVRDisplays().then(function (displays) {
  71565. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  71566. callback(false);
  71567. }
  71568. else {
  71569. _this._standingMatrix = new BABYLON.Matrix();
  71570. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  71571. if (!_this.getScene().useRightHandedSystem) {
  71572. [2, 6, 8, 9, 14].forEach(function (num) {
  71573. if (_this._standingMatrix) {
  71574. _this._standingMatrix.m[num] *= -1;
  71575. }
  71576. });
  71577. }
  71578. callback(true);
  71579. }
  71580. });
  71581. }
  71582. };
  71583. _this._workingVector = BABYLON.Vector3.Zero();
  71584. _this._oneVector = BABYLON.Vector3.One();
  71585. _this._workingMatrix = BABYLON.Matrix.Identity();
  71586. _this._cache.position = BABYLON.Vector3.Zero();
  71587. if (webVROptions.defaultHeight) {
  71588. _this._defaultHeight = webVROptions.defaultHeight;
  71589. _this.position.y = _this._defaultHeight;
  71590. }
  71591. _this.minZ = 0.1;
  71592. //legacy support - the compensation boolean was removed.
  71593. if (arguments.length === 5) {
  71594. _this.webVROptions = arguments[4];
  71595. }
  71596. // default webVR options
  71597. if (_this.webVROptions.trackPosition == undefined) {
  71598. _this.webVROptions.trackPosition = true;
  71599. }
  71600. if (_this.webVROptions.controllerMeshes == undefined) {
  71601. _this.webVROptions.controllerMeshes = true;
  71602. }
  71603. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  71604. _this.webVROptions.defaultLightingOnControllers = true;
  71605. }
  71606. _this.rotationQuaternion = new BABYLON.Quaternion();
  71607. if (_this.webVROptions && _this.webVROptions.positionScale) {
  71608. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  71609. }
  71610. //enable VR
  71611. var engine = _this.getEngine();
  71612. _this._onVREnabled = function (success) { if (success) {
  71613. _this.initControllers();
  71614. } };
  71615. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  71616. engine.initWebVR().add(function (event) {
  71617. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  71618. return;
  71619. }
  71620. _this._vrDevice = event.vrDisplay;
  71621. //reset the rig parameters.
  71622. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  71623. if (_this._attached) {
  71624. _this.getEngine().enableVR();
  71625. }
  71626. });
  71627. if (typeof (VRFrameData) !== "undefined")
  71628. _this._frameData = new VRFrameData();
  71629. /**
  71630. * The idea behind the following lines:
  71631. * objects that have the camera as parent should actually have the rig cameras as a parent.
  71632. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  71633. * the second will not show it correctly.
  71634. *
  71635. * To solve this - each object that has the camera as parent will be added to a protected array.
  71636. * When the rig camera renders, it will take this array and set all of those to be its children.
  71637. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  71638. * Amazing!
  71639. */
  71640. scene.onBeforeCameraRenderObservable.add(function (camera) {
  71641. if (camera.parent === _this && _this.rigParenting) {
  71642. _this._descendants = _this.getDescendants(true, function (n) {
  71643. // don't take the cameras or the controllers!
  71644. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  71645. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  71646. return !isController && !isRigCamera;
  71647. });
  71648. _this._descendants.forEach(function (node) {
  71649. node.parent = camera;
  71650. });
  71651. }
  71652. });
  71653. scene.onAfterCameraRenderObservable.add(function (camera) {
  71654. if (camera.parent === _this && _this.rigParenting) {
  71655. _this._descendants.forEach(function (node) {
  71656. node.parent = _this;
  71657. });
  71658. }
  71659. });
  71660. return _this;
  71661. }
  71662. WebVRFreeCamera.prototype.dispose = function () {
  71663. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  71664. _super.prototype.dispose.call(this);
  71665. };
  71666. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  71667. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  71668. var gp = _a[_i];
  71669. if (gp.hand === name) {
  71670. return gp;
  71671. }
  71672. }
  71673. return null;
  71674. };
  71675. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  71676. get: function () {
  71677. if (!this._leftController) {
  71678. this._leftController = this.getControllerByName("left");
  71679. }
  71680. return this._leftController;
  71681. },
  71682. enumerable: true,
  71683. configurable: true
  71684. });
  71685. ;
  71686. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  71687. get: function () {
  71688. if (!this._rightController) {
  71689. this._rightController = this.getControllerByName("right");
  71690. }
  71691. return this._rightController;
  71692. },
  71693. enumerable: true,
  71694. configurable: true
  71695. });
  71696. ;
  71697. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  71698. if (length === void 0) { length = 100; }
  71699. if (this.leftCamera) {
  71700. // Use left eye to avoid computation to compute center on every call
  71701. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  71702. }
  71703. else {
  71704. return _super.prototype.getForwardRay.call(this, length);
  71705. }
  71706. };
  71707. WebVRFreeCamera.prototype._checkInputs = function () {
  71708. if (this._vrDevice && this._vrDevice.isPresenting) {
  71709. this._vrDevice.getFrameData(this._frameData);
  71710. this.updateFromDevice(this._frameData.pose);
  71711. }
  71712. _super.prototype._checkInputs.call(this);
  71713. };
  71714. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  71715. if (poseData && poseData.orientation) {
  71716. this.rawPose = poseData;
  71717. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  71718. if (this.getScene().useRightHandedSystem) {
  71719. this._deviceRoomRotationQuaternion.z *= -1;
  71720. this._deviceRoomRotationQuaternion.w *= -1;
  71721. }
  71722. if (this.webVROptions.trackPosition && this.rawPose.position) {
  71723. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  71724. if (this.getScene().useRightHandedSystem) {
  71725. this._deviceRoomPosition.z *= -1;
  71726. }
  71727. }
  71728. }
  71729. };
  71730. /**
  71731. * WebVR's attach control will start broadcasting frames to the device.
  71732. * Note that in certain browsers (chrome for example) this function must be called
  71733. * within a user-interaction callback. Example:
  71734. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  71735. *
  71736. * @param {HTMLElement} element
  71737. * @param {boolean} [noPreventDefault]
  71738. *
  71739. * @memberOf WebVRFreeCamera
  71740. */
  71741. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  71742. _super.prototype.attachControl.call(this, element, noPreventDefault);
  71743. this._attached = true;
  71744. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  71745. if (this._vrDevice) {
  71746. this.getEngine().enableVR();
  71747. }
  71748. };
  71749. WebVRFreeCamera.prototype.detachControl = function (element) {
  71750. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  71751. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  71752. _super.prototype.detachControl.call(this, element);
  71753. this._attached = false;
  71754. this.getEngine().disableVR();
  71755. };
  71756. WebVRFreeCamera.prototype.getClassName = function () {
  71757. return "WebVRFreeCamera";
  71758. };
  71759. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  71760. //uses the vrDisplay's "resetPose()".
  71761. //pitch and roll won't be affected.
  71762. this._vrDevice.resetPose();
  71763. };
  71764. WebVRFreeCamera.prototype._updateRigCameras = function () {
  71765. var camLeft = this._rigCameras[0];
  71766. var camRight = this._rigCameras[1];
  71767. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  71768. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  71769. camLeft.position.copyFrom(this._deviceRoomPosition);
  71770. camRight.position.copyFrom(this._deviceRoomPosition);
  71771. };
  71772. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  71773. var _this = this;
  71774. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  71775. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  71776. this.update();
  71777. // Set working vector to the device position in room space rotated by the new rotation
  71778. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  71779. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  71780. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  71781. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  71782. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  71783. // Add translation from anchor position
  71784. this._deviceToWorld.getTranslationToRef(this._workingVector);
  71785. this._workingVector.addInPlace(this.position);
  71786. this._workingVector.subtractInPlace(this._cache.position);
  71787. this._deviceToWorld.setTranslation(this._workingVector);
  71788. // Set an inverted matrix to be used when updating the camera
  71789. this._deviceToWorld.invertToRef(this._worldToDevice);
  71790. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  71791. this.controllers.forEach(function (controller) {
  71792. controller._deviceToWorld = _this._deviceToWorld;
  71793. controller.update();
  71794. });
  71795. this.update();
  71796. }
  71797. if (!ignoreParentClass) {
  71798. _super.prototype._updateCache.call(this);
  71799. }
  71800. };
  71801. WebVRFreeCamera.prototype.update = function () {
  71802. // Get current device position in babylon world
  71803. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  71804. // Get current device rotation in babylon world
  71805. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  71806. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  71807. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71808. _super.prototype.update.call(this);
  71809. };
  71810. WebVRFreeCamera.prototype._getViewMatrix = function () {
  71811. return BABYLON.Matrix.Identity();
  71812. };
  71813. /**
  71814. * This function is called by the two RIG cameras.
  71815. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  71816. */
  71817. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  71818. var _this = this;
  71819. //WebVR 1.1
  71820. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  71821. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  71822. if (!this.getScene().useRightHandedSystem) {
  71823. [2, 6, 8, 9, 14].forEach(function (num) {
  71824. _this._webvrViewMatrix.m[num] *= -1;
  71825. });
  71826. }
  71827. // update the camera rotation matrix
  71828. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  71829. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  71830. // Computing target and final matrix
  71831. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  71832. var parentCamera = this._cameraRigParams["parentCamera"];
  71833. // should the view matrix be updated with scale and position offset?
  71834. if (parentCamera.deviceScaleFactor !== 1) {
  71835. this._webvrViewMatrix.invert();
  71836. // scale the position, if set
  71837. if (parentCamera.deviceScaleFactor) {
  71838. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  71839. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  71840. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  71841. }
  71842. this._webvrViewMatrix.invert();
  71843. }
  71844. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  71845. return this._webvrViewMatrix;
  71846. };
  71847. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  71848. var _this = this;
  71849. var parentCamera = this.parent;
  71850. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  71851. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  71852. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  71853. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  71854. //babylon compatible matrix
  71855. if (!this.getScene().useRightHandedSystem) {
  71856. [8, 9, 10, 11].forEach(function (num) {
  71857. _this._projectionMatrix.m[num] *= -1;
  71858. });
  71859. }
  71860. return this._projectionMatrix;
  71861. };
  71862. WebVRFreeCamera.prototype.initControllers = function () {
  71863. var _this = this;
  71864. this.controllers = [];
  71865. var manager = this.getScene().gamepadManager;
  71866. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  71867. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  71868. var webVrController = gamepad;
  71869. if (webVrController.defaultModel) {
  71870. webVrController.defaultModel.setEnabled(false);
  71871. }
  71872. if (webVrController.hand === "right") {
  71873. _this._rightController = null;
  71874. }
  71875. if (webVrController.hand === "left") {
  71876. _this._rightController = null;
  71877. }
  71878. var controllerIndex = _this.controllers.indexOf(webVrController);
  71879. if (controllerIndex !== -1) {
  71880. _this.controllers.splice(controllerIndex, 1);
  71881. }
  71882. }
  71883. });
  71884. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  71885. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  71886. var webVrController_1 = gamepad;
  71887. webVrController_1._deviceToWorld = _this._deviceToWorld;
  71888. if (_this.webVROptions.controllerMeshes) {
  71889. if (webVrController_1.defaultModel) {
  71890. webVrController_1.defaultModel.setEnabled(true);
  71891. }
  71892. else {
  71893. // Load the meshes
  71894. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  71895. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  71896. if (_this.webVROptions.defaultLightingOnControllers) {
  71897. if (!_this._lightOnControllers) {
  71898. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  71899. }
  71900. var activateLightOnSubMeshes_1 = function (mesh, light) {
  71901. var children = mesh.getChildren();
  71902. if (children.length !== 0) {
  71903. children.forEach(function (mesh) {
  71904. light.includedOnlyMeshes.push(mesh);
  71905. activateLightOnSubMeshes_1(mesh, light);
  71906. });
  71907. }
  71908. };
  71909. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  71910. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  71911. }
  71912. });
  71913. }
  71914. }
  71915. webVrController_1.attachToPoseControlledCamera(_this);
  71916. // since this is async - sanity check. Is the controller already stored?
  71917. if (_this.controllers.indexOf(webVrController_1) === -1) {
  71918. //add to the controllers array
  71919. _this.controllers.push(webVrController_1);
  71920. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  71921. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  71922. // So we're overriding setting left & right manually to be sure
  71923. var firstViveWandDetected = false;
  71924. for (var i = 0; i < _this.controllers.length; i++) {
  71925. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  71926. if (!firstViveWandDetected) {
  71927. firstViveWandDetected = true;
  71928. _this.controllers[i].hand = "left";
  71929. }
  71930. else {
  71931. _this.controllers[i].hand = "right";
  71932. }
  71933. }
  71934. }
  71935. //did we find enough controllers? Great! let the developer know.
  71936. if (_this.controllers.length >= 2) {
  71937. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  71938. }
  71939. }
  71940. }
  71941. });
  71942. };
  71943. return WebVRFreeCamera;
  71944. }(BABYLON.FreeCamera));
  71945. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  71946. })(BABYLON || (BABYLON = {}));
  71947. //# sourceMappingURL=babylon.webVRCamera.js.map
  71948. var BABYLON;
  71949. (function (BABYLON) {
  71950. // We're mainly based on the logic defined into the FreeCamera code
  71951. var DeviceOrientationCamera = /** @class */ (function (_super) {
  71952. __extends(DeviceOrientationCamera, _super);
  71953. function DeviceOrientationCamera(name, position, scene) {
  71954. var _this = _super.call(this, name, position, scene) || this;
  71955. _this._quaternionCache = new BABYLON.Quaternion();
  71956. _this.inputs.addDeviceOrientation();
  71957. return _this;
  71958. }
  71959. DeviceOrientationCamera.prototype.getClassName = function () {
  71960. return "DeviceOrientationCamera";
  71961. };
  71962. DeviceOrientationCamera.prototype._checkInputs = function () {
  71963. _super.prototype._checkInputs.call(this);
  71964. this._quaternionCache.copyFrom(this.rotationQuaternion);
  71965. if (this._initialQuaternion) {
  71966. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  71967. }
  71968. };
  71969. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  71970. var _this = this;
  71971. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  71972. //can only work if this camera has a rotation quaternion already.
  71973. if (!this.rotationQuaternion)
  71974. return;
  71975. if (!this._initialQuaternion) {
  71976. this._initialQuaternion = new BABYLON.Quaternion();
  71977. }
  71978. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  71979. ['x', 'y', 'z'].forEach(function (axisName) {
  71980. if (!axis[axisName]) {
  71981. _this._initialQuaternion[axisName] = 0;
  71982. }
  71983. else {
  71984. _this._initialQuaternion[axisName] *= -1;
  71985. }
  71986. });
  71987. this._initialQuaternion.normalize();
  71988. //force rotation update
  71989. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  71990. };
  71991. return DeviceOrientationCamera;
  71992. }(BABYLON.FreeCamera));
  71993. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  71994. })(BABYLON || (BABYLON = {}));
  71995. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  71996. var BABYLON;
  71997. (function (BABYLON) {
  71998. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  71999. __extends(VRDeviceOrientationFreeCamera, _super);
  72000. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  72001. if (compensateDistortion === void 0) { compensateDistortion = true; }
  72002. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  72003. var _this = _super.call(this, name, position, scene) || this;
  72004. vrCameraMetrics.compensateDistortion = compensateDistortion;
  72005. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  72006. return _this;
  72007. }
  72008. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  72009. return "VRDeviceOrientationFreeCamera";
  72010. };
  72011. return VRDeviceOrientationFreeCamera;
  72012. }(BABYLON.DeviceOrientationCamera));
  72013. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  72014. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  72015. __extends(VRDeviceOrientationGamepadCamera, _super);
  72016. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  72017. if (compensateDistortion === void 0) { compensateDistortion = true; }
  72018. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  72019. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  72020. _this.inputs.addGamepad();
  72021. return _this;
  72022. }
  72023. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  72024. return "VRDeviceOrientationGamepadCamera";
  72025. };
  72026. return VRDeviceOrientationGamepadCamera;
  72027. }(VRDeviceOrientationFreeCamera));
  72028. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  72029. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  72030. __extends(VRDeviceOrientationArcRotateCamera, _super);
  72031. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  72032. if (compensateDistortion === void 0) { compensateDistortion = true; }
  72033. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  72034. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  72035. vrCameraMetrics.compensateDistortion = compensateDistortion;
  72036. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  72037. _this.inputs.addVRDeviceOrientation();
  72038. return _this;
  72039. }
  72040. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  72041. return "VRDeviceOrientationArcRotateCamera";
  72042. };
  72043. return VRDeviceOrientationArcRotateCamera;
  72044. }(BABYLON.ArcRotateCamera));
  72045. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  72046. })(BABYLON || (BABYLON = {}));
  72047. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  72048. var BABYLON;
  72049. (function (BABYLON) {
  72050. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  72051. __extends(AnaglyphFreeCamera, _super);
  72052. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  72053. var _this = _super.call(this, name, position, scene) || this;
  72054. _this.interaxialDistance = interaxialDistance;
  72055. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  72056. return _this;
  72057. }
  72058. AnaglyphFreeCamera.prototype.getClassName = function () {
  72059. return "AnaglyphFreeCamera";
  72060. };
  72061. return AnaglyphFreeCamera;
  72062. }(BABYLON.FreeCamera));
  72063. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  72064. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  72065. __extends(AnaglyphArcRotateCamera, _super);
  72066. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  72067. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  72068. _this.interaxialDistance = interaxialDistance;
  72069. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  72070. return _this;
  72071. }
  72072. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  72073. return "AnaglyphArcRotateCamera";
  72074. };
  72075. return AnaglyphArcRotateCamera;
  72076. }(BABYLON.ArcRotateCamera));
  72077. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  72078. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  72079. __extends(AnaglyphGamepadCamera, _super);
  72080. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  72081. var _this = _super.call(this, name, position, scene) || this;
  72082. _this.interaxialDistance = interaxialDistance;
  72083. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  72084. return _this;
  72085. }
  72086. AnaglyphGamepadCamera.prototype.getClassName = function () {
  72087. return "AnaglyphGamepadCamera";
  72088. };
  72089. return AnaglyphGamepadCamera;
  72090. }(BABYLON.GamepadCamera));
  72091. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  72092. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  72093. __extends(AnaglyphUniversalCamera, _super);
  72094. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  72095. var _this = _super.call(this, name, position, scene) || this;
  72096. _this.interaxialDistance = interaxialDistance;
  72097. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  72098. return _this;
  72099. }
  72100. AnaglyphUniversalCamera.prototype.getClassName = function () {
  72101. return "AnaglyphUniversalCamera";
  72102. };
  72103. return AnaglyphUniversalCamera;
  72104. }(BABYLON.UniversalCamera));
  72105. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  72106. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  72107. __extends(StereoscopicFreeCamera, _super);
  72108. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  72109. var _this = _super.call(this, name, position, scene) || this;
  72110. _this.interaxialDistance = interaxialDistance;
  72111. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  72112. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  72113. return _this;
  72114. }
  72115. StereoscopicFreeCamera.prototype.getClassName = function () {
  72116. return "StereoscopicFreeCamera";
  72117. };
  72118. return StereoscopicFreeCamera;
  72119. }(BABYLON.FreeCamera));
  72120. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  72121. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  72122. __extends(StereoscopicArcRotateCamera, _super);
  72123. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  72124. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  72125. _this.interaxialDistance = interaxialDistance;
  72126. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  72127. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  72128. return _this;
  72129. }
  72130. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  72131. return "StereoscopicArcRotateCamera";
  72132. };
  72133. return StereoscopicArcRotateCamera;
  72134. }(BABYLON.ArcRotateCamera));
  72135. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  72136. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  72137. __extends(StereoscopicGamepadCamera, _super);
  72138. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  72139. var _this = _super.call(this, name, position, scene) || this;
  72140. _this.interaxialDistance = interaxialDistance;
  72141. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  72142. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  72143. return _this;
  72144. }
  72145. StereoscopicGamepadCamera.prototype.getClassName = function () {
  72146. return "StereoscopicGamepadCamera";
  72147. };
  72148. return StereoscopicGamepadCamera;
  72149. }(BABYLON.GamepadCamera));
  72150. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  72151. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  72152. __extends(StereoscopicUniversalCamera, _super);
  72153. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  72154. var _this = _super.call(this, name, position, scene) || this;
  72155. _this.interaxialDistance = interaxialDistance;
  72156. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  72157. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  72158. return _this;
  72159. }
  72160. StereoscopicUniversalCamera.prototype.getClassName = function () {
  72161. return "StereoscopicUniversalCamera";
  72162. };
  72163. return StereoscopicUniversalCamera;
  72164. }(BABYLON.UniversalCamera));
  72165. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  72166. })(BABYLON || (BABYLON = {}));
  72167. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  72168. var BABYLON;
  72169. (function (BABYLON) {
  72170. var VRExperienceHelper = /** @class */ (function () {
  72171. function VRExperienceHelper(scene, webVROptions) {
  72172. if (webVROptions === void 0) { webVROptions = {}; }
  72173. var _this = this;
  72174. this.webVROptions = webVROptions;
  72175. // Can the system support WebVR, even if a headset isn't plugged in?
  72176. this._webVRsupported = false;
  72177. // If WebVR is supported, is a headset plugged in and are we ready to present?
  72178. this._webVRready = false;
  72179. // Are we waiting for the requestPresent callback to complete?
  72180. this._webVRrequesting = false;
  72181. // Are we presenting to the headset right now?
  72182. this._webVRpresenting = false;
  72183. // Are we presenting in the fullscreen fallback?
  72184. this._fullscreenVRpresenting = false;
  72185. /**
  72186. * Observable raised when entering VR.
  72187. */
  72188. this.onEnteringVRObservable = new BABYLON.Observable();
  72189. /**
  72190. * Observable raised when exiting VR.
  72191. */
  72192. this.onExitingVRObservable = new BABYLON.Observable();
  72193. /**
  72194. * Observable raised when controller mesh is loaded.
  72195. */
  72196. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  72197. this._useCustomVRButton = false;
  72198. this._teleportationRequested = false;
  72199. this._teleportationEnabledOnLeftController = false;
  72200. this._teleportationEnabledOnRightController = false;
  72201. this._interactionsEnabledOnLeftController = false;
  72202. this._interactionsEnabledOnRightController = false;
  72203. this._leftControllerReady = false;
  72204. this._rightControllerReady = false;
  72205. this._floorMeshesCollection = [];
  72206. this._teleportationAllowed = false;
  72207. this._rotationAllowed = true;
  72208. this._teleportationRequestInitiated = false;
  72209. this._teleportationBackRequestInitiated = false;
  72210. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  72211. this._rotationRightAsked = false;
  72212. this._rotationLeftAsked = false;
  72213. this._isDefaultTeleportationTarget = true;
  72214. this._teleportationFillColor = "#444444";
  72215. this._teleportationBorderColor = "#FFFFFF";
  72216. this._rotationAngle = 0;
  72217. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  72218. this._padSensibilityUp = 0.65;
  72219. this._padSensibilityDown = 0.35;
  72220. this.onNewMeshSelected = new BABYLON.Observable();
  72221. this._pointerDownOnMeshAsked = false;
  72222. this._isActionableMesh = false;
  72223. this._teleportationEnabled = false;
  72224. this._interactionsEnabled = false;
  72225. this._interactionsRequested = false;
  72226. this._displayGaze = true;
  72227. this._displayLaserPointer = true;
  72228. this._dpadPressed = true;
  72229. this._onResize = function () {
  72230. _this.moveButtonToBottomRight();
  72231. if (_this._fullscreenVRpresenting && _this._webVRready) {
  72232. _this.exitVR();
  72233. }
  72234. };
  72235. this._onFullscreenChange = function () {
  72236. if (document.fullscreen !== undefined) {
  72237. _this._fullscreenVRpresenting = document.fullscreen;
  72238. }
  72239. else if (document.mozFullScreen !== undefined) {
  72240. _this._fullscreenVRpresenting = document.mozFullScreen;
  72241. }
  72242. else if (document.webkitIsFullScreen !== undefined) {
  72243. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  72244. }
  72245. else if (document.msIsFullScreen !== undefined) {
  72246. _this._fullscreenVRpresenting = document.msIsFullScreen;
  72247. }
  72248. if (!_this._fullscreenVRpresenting && _this._canvas) {
  72249. _this.exitVR();
  72250. if (!_this._useCustomVRButton) {
  72251. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  72252. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  72253. }
  72254. }
  72255. };
  72256. this.beforeRender = function () {
  72257. _this._castRayAndSelectObject();
  72258. };
  72259. this._onNewGamepadConnected = function (gamepad) {
  72260. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  72261. if (gamepad.leftStick) {
  72262. gamepad.onleftstickchanged(function (stickValues) {
  72263. if (_this._teleportationEnabled) {
  72264. // Listening to classic/xbox gamepad only if no VR controller is active
  72265. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  72266. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  72267. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  72268. _this._checkTeleportWithRay(stickValues);
  72269. _this._checkTeleportBackwards(stickValues);
  72270. }
  72271. }
  72272. });
  72273. }
  72274. if (gamepad.rightStick) {
  72275. gamepad.onrightstickchanged(function (stickValues) {
  72276. if (_this._teleportationEnabled) {
  72277. _this._checkRotate(stickValues);
  72278. }
  72279. });
  72280. }
  72281. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  72282. gamepad.onbuttondown(function (buttonPressed) {
  72283. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  72284. _this._selectionPointerDown();
  72285. }
  72286. });
  72287. gamepad.onbuttonup(function (buttonPressed) {
  72288. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  72289. _this._selectionPointerUp();
  72290. }
  72291. });
  72292. }
  72293. }
  72294. else {
  72295. var webVRController = gamepad;
  72296. _this._tryEnableInteractionOnController(webVRController);
  72297. }
  72298. };
  72299. // This only succeeds if the controller's mesh exists for the controller so this must be called whenever new controller is connected or when mesh is loaded
  72300. this._tryEnableInteractionOnController = function (webVRController) {
  72301. if (webVRController.hand === "left") {
  72302. _this._leftControllerReady = true;
  72303. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  72304. _this._enableInteractionOnController(webVRController);
  72305. }
  72306. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  72307. _this._enableTeleportationOnController(webVRController);
  72308. }
  72309. }
  72310. if (webVRController.hand === "right") {
  72311. _this._rightControllerReady = true;
  72312. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  72313. _this._enableInteractionOnController(webVRController);
  72314. }
  72315. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  72316. _this._enableTeleportationOnController(webVRController);
  72317. }
  72318. }
  72319. };
  72320. this._onNewGamepadDisconnected = function (gamepad) {
  72321. if (gamepad instanceof BABYLON.WebVRController) {
  72322. if (gamepad.hand === "left") {
  72323. _this._interactionsEnabledOnLeftController = false;
  72324. _this._teleportationEnabledOnLeftController = false;
  72325. _this._leftControllerReady = false;
  72326. if (_this._leftLaserPointer) {
  72327. _this._leftLaserPointer.dispose();
  72328. }
  72329. }
  72330. if (gamepad.hand === "right") {
  72331. _this._interactionsEnabledOnRightController = false;
  72332. _this._teleportationEnabledOnRightController = false;
  72333. _this._rightControllerReady = false;
  72334. if (_this._rightLaserPointer) {
  72335. _this._rightLaserPointer.dispose();
  72336. }
  72337. }
  72338. }
  72339. };
  72340. this._workingVector = BABYLON.Vector3.Zero();
  72341. this._workingQuaternion = BABYLON.Quaternion.Identity();
  72342. this._workingMatrix = BABYLON.Matrix.Identity();
  72343. this._scene = scene;
  72344. this._canvas = scene.getEngine().getRenderingCanvas();
  72345. // Parse options
  72346. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  72347. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  72348. }
  72349. if (webVROptions.createDeviceOrientationCamera === undefined) {
  72350. webVROptions.createDeviceOrientationCamera = true;
  72351. }
  72352. if (webVROptions.defaultHeight === undefined) {
  72353. webVROptions.defaultHeight = 1.7;
  72354. }
  72355. if (webVROptions.useCustomVRButton) {
  72356. this._useCustomVRButton = true;
  72357. if (webVROptions.customVRButton) {
  72358. this._btnVR = webVROptions.customVRButton;
  72359. }
  72360. }
  72361. if (webVROptions.rayLength) {
  72362. this._rayLength = webVROptions.rayLength;
  72363. }
  72364. this._defaultHeight = webVROptions.defaultHeight;
  72365. // Set position
  72366. if (this._scene.activeCamera) {
  72367. this._position = this._scene.activeCamera.position.clone();
  72368. }
  72369. else {
  72370. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  72371. }
  72372. // Set non-vr camera
  72373. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  72374. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  72375. // Copy data from existing camera
  72376. if (this._scene.activeCamera) {
  72377. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  72378. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  72379. // Set rotation from previous camera
  72380. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  72381. var targetCamera = this._scene.activeCamera;
  72382. if (targetCamera.rotationQuaternion) {
  72383. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  72384. }
  72385. else {
  72386. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  72387. }
  72388. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  72389. }
  72390. }
  72391. this._scene.activeCamera = this._deviceOrientationCamera;
  72392. if (this._canvas) {
  72393. this._scene.activeCamera.attachControl(this._canvas);
  72394. }
  72395. }
  72396. else {
  72397. this._existingCamera = this._scene.activeCamera;
  72398. }
  72399. // Create VR cameras
  72400. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  72401. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  72402. }
  72403. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  72404. this._webVRCamera.useStandingMatrix();
  72405. // Create default button
  72406. if (!this._useCustomVRButton) {
  72407. this._btnVR = document.createElement("BUTTON");
  72408. this._btnVR.className = "babylonVRicon";
  72409. this._btnVR.id = "babylonVRiconbtn";
  72410. this._btnVR.title = "Click to switch to VR";
  72411. 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) }";
  72412. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  72413. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  72414. // css += ".babylonVRicon.vrdisplaysupported { }";
  72415. // css += ".babylonVRicon.vrdisplayready { }";
  72416. // css += ".babylonVRicon.vrdisplayrequesting { }";
  72417. var style = document.createElement('style');
  72418. style.appendChild(document.createTextNode(css));
  72419. document.getElementsByTagName('head')[0].appendChild(style);
  72420. this.moveButtonToBottomRight();
  72421. }
  72422. // VR button click event
  72423. if (this._btnVR) {
  72424. this._btnVR.addEventListener("click", function () {
  72425. if (!_this.isInVRMode) {
  72426. _this.enterVR();
  72427. }
  72428. else {
  72429. _this.exitVR();
  72430. }
  72431. });
  72432. }
  72433. // Window events
  72434. window.addEventListener("resize", this._onResize);
  72435. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  72436. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  72437. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  72438. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  72439. // Display vr button when headset is connected
  72440. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  72441. this.displayVRButton();
  72442. }
  72443. else {
  72444. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  72445. if (e.vrDisplay) {
  72446. _this.displayVRButton();
  72447. }
  72448. });
  72449. }
  72450. // Exiting VR mode using 'ESC' key on desktop
  72451. this._onKeyDown = function (event) {
  72452. if (event.keyCode === 27 && _this.isInVRMode) {
  72453. _this.exitVR();
  72454. }
  72455. };
  72456. document.addEventListener("keydown", this._onKeyDown);
  72457. // Exiting VR mode double tapping the touch screen
  72458. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  72459. if (_this.isInVRMode) {
  72460. _this.exitVR();
  72461. if (_this._fullscreenVRpresenting) {
  72462. _this._scene.getEngine().switchFullscreen(true);
  72463. }
  72464. }
  72465. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  72466. // Listen for WebVR display changes
  72467. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  72468. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  72469. this._onVRRequestPresentStart = function () {
  72470. _this._webVRrequesting = true;
  72471. _this.updateButtonVisibility();
  72472. };
  72473. this._onVRRequestPresentComplete = function (success) {
  72474. _this._webVRrequesting = false;
  72475. _this.updateButtonVisibility();
  72476. };
  72477. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  72478. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  72479. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  72480. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  72481. scene.onDisposeObservable.add(function () {
  72482. _this.dispose();
  72483. });
  72484. // Gamepad connection events
  72485. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  72486. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  72487. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  72488. this.updateButtonVisibility();
  72489. //create easing functions
  72490. this._circleEase = new BABYLON.CircleEase();
  72491. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  72492. }
  72493. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  72494. /** Return this.onEnteringVRObservable
  72495. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  72496. */
  72497. get: function () {
  72498. return this.onEnteringVRObservable;
  72499. },
  72500. enumerable: true,
  72501. configurable: true
  72502. });
  72503. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  72504. /** Return this.onExitingVRObservable
  72505. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  72506. */
  72507. get: function () {
  72508. return this.onExitingVRObservable;
  72509. },
  72510. enumerable: true,
  72511. configurable: true
  72512. });
  72513. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  72514. /** Return this.onControllerMeshLoadedObservable
  72515. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  72516. */
  72517. get: function () {
  72518. return this.onControllerMeshLoadedObservable;
  72519. },
  72520. enumerable: true,
  72521. configurable: true
  72522. });
  72523. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  72524. get: function () {
  72525. return this._teleportationTarget;
  72526. },
  72527. set: function (value) {
  72528. if (value) {
  72529. value.name = "teleportationTarget";
  72530. this._isDefaultTeleportationTarget = false;
  72531. this._teleportationTarget = value;
  72532. }
  72533. },
  72534. enumerable: true,
  72535. configurable: true
  72536. });
  72537. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  72538. get: function () {
  72539. return this._displayGaze;
  72540. },
  72541. set: function (value) {
  72542. this._displayGaze = value;
  72543. if (!value) {
  72544. this._gazeTracker.isVisible = false;
  72545. }
  72546. },
  72547. enumerable: true,
  72548. configurable: true
  72549. });
  72550. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  72551. get: function () {
  72552. return this._displayLaserPointer;
  72553. },
  72554. set: function (value) {
  72555. this._displayLaserPointer = value;
  72556. if (!value) {
  72557. if (this._rightLaserPointer) {
  72558. this._rightLaserPointer.isVisible = false;
  72559. }
  72560. if (this._leftLaserPointer) {
  72561. this._leftLaserPointer.isVisible = false;
  72562. }
  72563. }
  72564. else {
  72565. if (this._rightLaserPointer) {
  72566. this._rightLaserPointer.isVisible = true;
  72567. }
  72568. else if (this._leftLaserPointer) {
  72569. this._leftLaserPointer.isVisible = true;
  72570. }
  72571. }
  72572. },
  72573. enumerable: true,
  72574. configurable: true
  72575. });
  72576. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  72577. get: function () {
  72578. return this._deviceOrientationCamera;
  72579. },
  72580. enumerable: true,
  72581. configurable: true
  72582. });
  72583. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  72584. // Based on the current WebVR support, returns the current VR camera used
  72585. get: function () {
  72586. if (this._webVRready) {
  72587. return this._webVRCamera;
  72588. }
  72589. else {
  72590. return this._scene.activeCamera;
  72591. }
  72592. },
  72593. enumerable: true,
  72594. configurable: true
  72595. });
  72596. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  72597. get: function () {
  72598. return this._webVRCamera;
  72599. },
  72600. enumerable: true,
  72601. configurable: true
  72602. });
  72603. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  72604. get: function () {
  72605. return this._vrDeviceOrientationCamera;
  72606. },
  72607. enumerable: true,
  72608. configurable: true
  72609. });
  72610. // Raised when one of the controller has loaded successfully its associated default mesh
  72611. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  72612. this._tryEnableInteractionOnController(webVRController);
  72613. try {
  72614. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  72615. }
  72616. catch (err) {
  72617. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  72618. }
  72619. };
  72620. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  72621. /**
  72622. * Gets a value indicating if we are currently in VR mode.
  72623. */
  72624. get: function () {
  72625. return this._webVRpresenting || this._fullscreenVRpresenting;
  72626. },
  72627. enumerable: true,
  72628. configurable: true
  72629. });
  72630. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  72631. var vrDisplay = this._scene.getEngine().getVRDevice();
  72632. if (vrDisplay) {
  72633. var wasPresenting = this._webVRpresenting;
  72634. // A VR display is connected
  72635. this._webVRpresenting = vrDisplay.isPresenting;
  72636. if (wasPresenting && !this._webVRpresenting)
  72637. this.exitVR();
  72638. }
  72639. else {
  72640. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  72641. }
  72642. this.updateButtonVisibility();
  72643. };
  72644. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  72645. this._webVRsupported = eventArgs.vrSupported;
  72646. this._webVRready = !!eventArgs.vrDisplay;
  72647. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  72648. this.updateButtonVisibility();
  72649. };
  72650. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  72651. if (this._canvas && !this._useCustomVRButton) {
  72652. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  72653. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  72654. }
  72655. };
  72656. VRExperienceHelper.prototype.displayVRButton = function () {
  72657. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  72658. document.body.appendChild(this._btnVR);
  72659. this._btnVRDisplayed = true;
  72660. }
  72661. };
  72662. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  72663. if (!this._btnVR || this._useCustomVRButton) {
  72664. return;
  72665. }
  72666. this._btnVR.className = "babylonVRicon";
  72667. if (this.isInVRMode) {
  72668. this._btnVR.className += " vrdisplaypresenting";
  72669. }
  72670. else {
  72671. if (this._webVRready)
  72672. this._btnVR.className += " vrdisplayready";
  72673. if (this._webVRsupported)
  72674. this._btnVR.className += " vrdisplaysupported";
  72675. if (this._webVRrequesting)
  72676. this._btnVR.className += " vrdisplayrequesting";
  72677. }
  72678. };
  72679. /**
  72680. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  72681. * Otherwise, will use the fullscreen API.
  72682. */
  72683. VRExperienceHelper.prototype.enterVR = function () {
  72684. if (this.onEnteringVRObservable) {
  72685. try {
  72686. this.onEnteringVRObservable.notifyObservers(this);
  72687. }
  72688. catch (err) {
  72689. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  72690. }
  72691. }
  72692. if (this._scene.activeCamera) {
  72693. this._position = this._scene.activeCamera.position.clone();
  72694. // make sure that we return to the last active camera
  72695. this._existingCamera = this._scene.activeCamera;
  72696. }
  72697. if (this._webVRrequesting)
  72698. return;
  72699. // If WebVR is supported and a headset is connected
  72700. if (this._webVRready) {
  72701. if (!this._webVRpresenting) {
  72702. this._webVRCamera.position = this._position;
  72703. this._scene.activeCamera = this._webVRCamera;
  72704. }
  72705. }
  72706. else if (this._vrDeviceOrientationCamera) {
  72707. this._vrDeviceOrientationCamera.position = this._position;
  72708. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  72709. this._scene.getEngine().switchFullscreen(true);
  72710. this.updateButtonVisibility();
  72711. }
  72712. if (this._scene.activeCamera && this._canvas) {
  72713. this._scene.activeCamera.attachControl(this._canvas);
  72714. }
  72715. };
  72716. /**
  72717. * Attempt to exit VR, or fullscreen.
  72718. */
  72719. VRExperienceHelper.prototype.exitVR = function () {
  72720. if (this.onExitingVRObservable) {
  72721. try {
  72722. this.onExitingVRObservable.notifyObservers(this);
  72723. }
  72724. catch (err) {
  72725. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  72726. }
  72727. }
  72728. if (this._webVRpresenting) {
  72729. this._scene.getEngine().disableVR();
  72730. }
  72731. if (this._scene.activeCamera) {
  72732. this._position = this._scene.activeCamera.position.clone();
  72733. }
  72734. if (this._deviceOrientationCamera) {
  72735. this._deviceOrientationCamera.position = this._position;
  72736. this._scene.activeCamera = this._deviceOrientationCamera;
  72737. if (this._canvas) {
  72738. this._scene.activeCamera.attachControl(this._canvas);
  72739. }
  72740. }
  72741. else if (this._existingCamera) {
  72742. this._existingCamera.position = this._position;
  72743. this._scene.activeCamera = this._existingCamera;
  72744. }
  72745. this.updateButtonVisibility();
  72746. };
  72747. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  72748. get: function () {
  72749. return this._position;
  72750. },
  72751. set: function (value) {
  72752. this._position = value;
  72753. if (this._scene.activeCamera) {
  72754. this._scene.activeCamera.position = value;
  72755. }
  72756. },
  72757. enumerable: true,
  72758. configurable: true
  72759. });
  72760. VRExperienceHelper.prototype.enableInteractions = function () {
  72761. var _this = this;
  72762. if (!this._interactionsEnabled) {
  72763. this._interactionsRequested = true;
  72764. if (this._leftControllerReady && this._webVRCamera.leftController) {
  72765. this._enableInteractionOnController(this._webVRCamera.leftController);
  72766. }
  72767. if (this._rightControllerReady && this._webVRCamera.rightController) {
  72768. this._enableInteractionOnController(this._webVRCamera.rightController);
  72769. }
  72770. this._createGazeTracker();
  72771. this.raySelectionPredicate = function (mesh) {
  72772. return true;
  72773. };
  72774. this.meshSelectionPredicate = function (mesh) {
  72775. return true;
  72776. };
  72777. this._raySelectionPredicate = function (mesh) {
  72778. if (_this._isTeleportationFloor(mesh) || (mesh.isVisible && mesh.name.indexOf("gazeTracker") === -1
  72779. && mesh.name.indexOf("teleportationTarget") === -1
  72780. && mesh.name.indexOf("torusTeleportation") === -1
  72781. && mesh.name.indexOf("laserPointer") === -1)) {
  72782. return _this.raySelectionPredicate(mesh);
  72783. }
  72784. return false;
  72785. };
  72786. this._scene.registerBeforeRender(this.beforeRender);
  72787. this._interactionsEnabled = true;
  72788. }
  72789. };
  72790. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  72791. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  72792. if (this._floorMeshesCollection[i].id === mesh.id) {
  72793. return true;
  72794. }
  72795. }
  72796. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  72797. return true;
  72798. }
  72799. return false;
  72800. };
  72801. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  72802. if (!this._floorMeshesCollection) {
  72803. return;
  72804. }
  72805. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  72806. return;
  72807. }
  72808. this._floorMeshesCollection.push(floorMesh);
  72809. };
  72810. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  72811. if (!this._floorMeshesCollection) {
  72812. return;
  72813. }
  72814. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  72815. if (meshIndex !== -1) {
  72816. this._floorMeshesCollection.splice(meshIndex, 1);
  72817. }
  72818. };
  72819. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  72820. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  72821. if (!this._teleportationEnabled) {
  72822. this._teleportationRequested = true;
  72823. if (!vrTeleportationOptions.disableInteractions) {
  72824. this.enableInteractions();
  72825. }
  72826. if (vrTeleportationOptions.floorMeshName) {
  72827. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  72828. }
  72829. if (vrTeleportationOptions.floorMeshes) {
  72830. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  72831. }
  72832. if (this._leftControllerReady && this._webVRCamera.leftController) {
  72833. this._enableTeleportationOnController(this._webVRCamera.leftController);
  72834. }
  72835. if (this._rightControllerReady && this._webVRCamera.rightController) {
  72836. this._enableTeleportationOnController(this._webVRCamera.rightController);
  72837. }
  72838. // Creates an image processing post process for the vignette not relying
  72839. // on the main scene configuration for image processing to reduce setup and spaces
  72840. // (gamma/linear) conflicts.
  72841. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  72842. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  72843. imageProcessingConfiguration.vignetteEnabled = true;
  72844. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  72845. this._webVRCamera.detachPostProcess(this._postProcessMove);
  72846. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  72847. this._teleportationEnabled = true;
  72848. if (this._isDefaultTeleportationTarget) {
  72849. this._createTeleportationCircles();
  72850. }
  72851. }
  72852. };
  72853. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  72854. var _this = this;
  72855. var controllerMesh = webVRController.mesh;
  72856. if (controllerMesh) {
  72857. var makeNotPick = function (root) {
  72858. root.name += " laserPointer";
  72859. root.getChildMeshes().forEach(function (c) {
  72860. makeNotPick(c);
  72861. });
  72862. };
  72863. makeNotPick(controllerMesh);
  72864. var childMeshes = controllerMesh.getChildMeshes();
  72865. for (var i = 0; i < childMeshes.length; i++) {
  72866. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  72867. controllerMesh = childMeshes[i];
  72868. break;
  72869. }
  72870. }
  72871. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  72872. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  72873. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  72874. laserPointerMaterial.alpha = 0.6;
  72875. laserPointer.material = laserPointerMaterial;
  72876. laserPointer.rotation.x = Math.PI / 2;
  72877. laserPointer.parent = controllerMesh;
  72878. laserPointer.position.z = -0.5;
  72879. laserPointer.isVisible = false;
  72880. if (webVRController.hand === "left") {
  72881. this._leftLaserPointer = laserPointer;
  72882. this._interactionsEnabledOnLeftController = true;
  72883. if (!this._rightLaserPointer) {
  72884. this._leftLaserPointer.isVisible = true;
  72885. }
  72886. }
  72887. else {
  72888. this._rightLaserPointer = laserPointer;
  72889. this._interactionsEnabledOnRightController = true;
  72890. if (!this._leftLaserPointer) {
  72891. this._rightLaserPointer.isVisible = true;
  72892. }
  72893. }
  72894. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  72895. // Enabling / disabling laserPointer
  72896. if (_this._displayLaserPointer && stateObject.value === 1) {
  72897. laserPointer.isVisible = !laserPointer.isVisible;
  72898. // Laser pointer can only be active on left or right, not both at the same time
  72899. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  72900. _this._rightLaserPointer.isVisible = false;
  72901. }
  72902. else if (_this._leftLaserPointer) {
  72903. _this._leftLaserPointer.isVisible = false;
  72904. }
  72905. }
  72906. });
  72907. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  72908. if (!_this._pointerDownOnMeshAsked) {
  72909. if (stateObject.value > _this._padSensibilityUp) {
  72910. _this._selectionPointerDown();
  72911. }
  72912. }
  72913. else if (stateObject.value < _this._padSensibilityDown) {
  72914. _this._selectionPointerUp();
  72915. }
  72916. });
  72917. }
  72918. };
  72919. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  72920. if (webVRController === void 0) { webVRController = null; }
  72921. if (!this._teleportationRequestInitiated) {
  72922. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  72923. if (webVRController) {
  72924. // If laser pointer wasn't enabled yet
  72925. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  72926. this._leftLaserPointer.isVisible = true;
  72927. if (this._rightLaserPointer) {
  72928. this._rightLaserPointer.isVisible = false;
  72929. }
  72930. }
  72931. else if (this._displayLaserPointer && this._rightLaserPointer) {
  72932. this._rightLaserPointer.isVisible = true;
  72933. if (this._leftLaserPointer) {
  72934. this._leftLaserPointer.isVisible = false;
  72935. }
  72936. }
  72937. }
  72938. this._teleportationRequestInitiated = true;
  72939. }
  72940. }
  72941. else {
  72942. // Listening to the proper controller values changes to confirm teleportation
  72943. if (webVRController == null
  72944. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  72945. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  72946. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  72947. if (this._teleportationAllowed) {
  72948. this._teleportationAllowed = false;
  72949. this._teleportCamera();
  72950. }
  72951. this._teleportationRequestInitiated = false;
  72952. }
  72953. }
  72954. }
  72955. };
  72956. VRExperienceHelper.prototype._selectionPointerDown = function () {
  72957. this._pointerDownOnMeshAsked = true;
  72958. if (this._currentMeshSelected && this._currentHit) {
  72959. this._scene.simulatePointerDown(this._currentHit);
  72960. }
  72961. };
  72962. VRExperienceHelper.prototype._selectionPointerUp = function () {
  72963. if (this._currentMeshSelected && this._currentHit) {
  72964. this._scene.simulatePointerUp(this._currentHit);
  72965. }
  72966. this._pointerDownOnMeshAsked = false;
  72967. };
  72968. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  72969. // Only rotate when user is not currently selecting a teleportation location
  72970. if (this._teleportationRequestInitiated) {
  72971. return;
  72972. }
  72973. if (!this._rotationLeftAsked) {
  72974. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  72975. this._rotationLeftAsked = true;
  72976. if (this._rotationAllowed) {
  72977. this._rotateCamera(false);
  72978. }
  72979. }
  72980. }
  72981. else {
  72982. if (stateObject.x > -this._padSensibilityDown) {
  72983. this._rotationLeftAsked = false;
  72984. }
  72985. }
  72986. if (!this._rotationRightAsked) {
  72987. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  72988. this._rotationRightAsked = true;
  72989. if (this._rotationAllowed) {
  72990. this._rotateCamera(true);
  72991. }
  72992. }
  72993. }
  72994. else {
  72995. if (stateObject.x < this._padSensibilityDown) {
  72996. this._rotationRightAsked = false;
  72997. }
  72998. }
  72999. };
  73000. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  73001. // Only teleport backwards when user is not currently selecting a teleportation location
  73002. if (this._teleportationRequestInitiated) {
  73003. return;
  73004. }
  73005. // Teleport backwards
  73006. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  73007. if (!this._teleportationBackRequestInitiated) {
  73008. if (!this.currentVRCamera) {
  73009. return;
  73010. }
  73011. // Get rotation and position of the current camera
  73012. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  73013. var position = this.currentVRCamera.position;
  73014. // If the camera has device position, use that instead
  73015. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  73016. rotation = this.currentVRCamera.deviceRotationQuaternion;
  73017. position = this.currentVRCamera.devicePosition;
  73018. }
  73019. // Get matrix with only the y rotation of the device rotation
  73020. rotation.toEulerAnglesToRef(this._workingVector);
  73021. this._workingVector.z = 0;
  73022. this._workingVector.x = 0;
  73023. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  73024. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  73025. // Rotate backwards ray by device rotation to cast at the ground behind the user
  73026. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  73027. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  73028. var ray = new BABYLON.Ray(position, this._workingVector);
  73029. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  73030. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  73031. this._teleportCamera(hit.pickedPoint);
  73032. }
  73033. this._teleportationBackRequestInitiated = true;
  73034. }
  73035. }
  73036. else {
  73037. this._teleportationBackRequestInitiated = false;
  73038. }
  73039. };
  73040. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  73041. var _this = this;
  73042. var controllerMesh = webVRController.mesh;
  73043. if (controllerMesh) {
  73044. if (webVRController.hand === "left") {
  73045. if (!this._interactionsEnabledOnLeftController) {
  73046. this._enableInteractionOnController(webVRController);
  73047. }
  73048. this._teleportationEnabledOnLeftController = true;
  73049. }
  73050. else {
  73051. if (!this._interactionsEnabledOnRightController) {
  73052. this._enableInteractionOnController(webVRController);
  73053. }
  73054. this._teleportationEnabledOnRightController = true;
  73055. }
  73056. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  73057. this._dpadPressed = false;
  73058. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  73059. _this._dpadPressed = stateObject.pressed;
  73060. if (!_this._dpadPressed) {
  73061. _this._rotationLeftAsked = false;
  73062. _this._rotationRightAsked = false;
  73063. _this._teleportationBackRequestInitiated = false;
  73064. }
  73065. });
  73066. }
  73067. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  73068. _this._checkTeleportBackwards(stateObject);
  73069. _this._checkTeleportWithRay(stateObject, webVRController);
  73070. _this._checkRotate(stateObject);
  73071. });
  73072. }
  73073. };
  73074. // Gaze support used to point to teleport or to interact with an object
  73075. VRExperienceHelper.prototype._createGazeTracker = function () {
  73076. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  73077. this._gazeTracker.bakeCurrentTransformIntoVertices();
  73078. this._gazeTracker.isPickable = false;
  73079. this._gazeTracker.isVisible = false;
  73080. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  73081. targetMat.specularColor = BABYLON.Color3.Black();
  73082. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  73083. targetMat.backFaceCulling = false;
  73084. this._gazeTracker.material = targetMat;
  73085. };
  73086. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  73087. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  73088. this._teleportationTarget.isPickable = false;
  73089. var length = 512;
  73090. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  73091. dynamicTexture.hasAlpha = true;
  73092. var context = dynamicTexture.getContext();
  73093. var centerX = length / 2;
  73094. var centerY = length / 2;
  73095. var radius = 200;
  73096. context.beginPath();
  73097. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  73098. context.fillStyle = this._teleportationFillColor;
  73099. context.fill();
  73100. context.lineWidth = 10;
  73101. context.strokeStyle = this._teleportationBorderColor;
  73102. context.stroke();
  73103. context.closePath();
  73104. dynamicTexture.update();
  73105. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  73106. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  73107. this._teleportationTarget.material = teleportationCircleMaterial;
  73108. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  73109. torus.isPickable = false;
  73110. torus.parent = this._teleportationTarget;
  73111. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  73112. var keys = [];
  73113. keys.push({
  73114. frame: 0,
  73115. value: 0
  73116. });
  73117. keys.push({
  73118. frame: 30,
  73119. value: 0.4
  73120. });
  73121. keys.push({
  73122. frame: 60,
  73123. value: 0
  73124. });
  73125. animationInnerCircle.setKeys(keys);
  73126. var easingFunction = new BABYLON.SineEase();
  73127. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  73128. animationInnerCircle.setEasingFunction(easingFunction);
  73129. torus.animations = [];
  73130. torus.animations.push(animationInnerCircle);
  73131. this._scene.beginAnimation(torus, 0, 60, true);
  73132. this._hideTeleportationTarget();
  73133. };
  73134. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  73135. if (this._teleportationEnabled) {
  73136. this._teleportationTarget.isVisible = true;
  73137. if (this._isDefaultTeleportationTarget) {
  73138. this._teleportationTarget.getChildren()[0].isVisible = true;
  73139. }
  73140. }
  73141. };
  73142. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  73143. if (this._teleportationEnabled) {
  73144. this._teleportationTarget.isVisible = false;
  73145. if (this._isDefaultTeleportationTarget) {
  73146. this._teleportationTarget.getChildren()[0].isVisible = false;
  73147. }
  73148. }
  73149. };
  73150. VRExperienceHelper.prototype._rotateCamera = function (right) {
  73151. var _this = this;
  73152. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  73153. return;
  73154. }
  73155. if (right) {
  73156. this._rotationAngle++;
  73157. }
  73158. else {
  73159. this._rotationAngle--;
  73160. }
  73161. this.currentVRCamera.animations = [];
  73162. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  73163. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  73164. var animationRotationKeys = [];
  73165. animationRotationKeys.push({
  73166. frame: 0,
  73167. value: this.currentVRCamera.rotationQuaternion
  73168. });
  73169. animationRotationKeys.push({
  73170. frame: 6,
  73171. value: target
  73172. });
  73173. animationRotation.setKeys(animationRotationKeys);
  73174. animationRotation.setEasingFunction(this._circleEase);
  73175. this.currentVRCamera.animations.push(animationRotation);
  73176. this._postProcessMove.animations = [];
  73177. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  73178. var vignetteWeightKeys = [];
  73179. vignetteWeightKeys.push({
  73180. frame: 0,
  73181. value: 0
  73182. });
  73183. vignetteWeightKeys.push({
  73184. frame: 3,
  73185. value: 4
  73186. });
  73187. vignetteWeightKeys.push({
  73188. frame: 6,
  73189. value: 0
  73190. });
  73191. animationPP.setKeys(vignetteWeightKeys);
  73192. animationPP.setEasingFunction(this._circleEase);
  73193. this._postProcessMove.animations.push(animationPP);
  73194. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  73195. var vignetteStretchKeys = [];
  73196. vignetteStretchKeys.push({
  73197. frame: 0,
  73198. value: 0
  73199. });
  73200. vignetteStretchKeys.push({
  73201. frame: 3,
  73202. value: 10
  73203. });
  73204. vignetteStretchKeys.push({
  73205. frame: 6,
  73206. value: 0
  73207. });
  73208. animationPP2.setKeys(vignetteStretchKeys);
  73209. animationPP2.setEasingFunction(this._circleEase);
  73210. this._postProcessMove.animations.push(animationPP2);
  73211. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  73212. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  73213. this._webVRCamera.attachPostProcess(this._postProcessMove);
  73214. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  73215. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  73216. });
  73217. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  73218. };
  73219. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  73220. if (hit.pickedPoint) {
  73221. this._teleportationAllowed = true;
  73222. if (this._teleportationRequestInitiated) {
  73223. this._displayTeleportationTarget();
  73224. }
  73225. else {
  73226. this._hideTeleportationTarget();
  73227. }
  73228. this._haloCenter.copyFrom(hit.pickedPoint);
  73229. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  73230. var pickNormal = hit.getNormal(true, false);
  73231. if (pickNormal) {
  73232. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  73233. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  73234. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  73235. }
  73236. this._teleportationTarget.position.y += 0.1;
  73237. }
  73238. };
  73239. VRExperienceHelper.prototype._teleportCamera = function (location) {
  73240. var _this = this;
  73241. if (location === void 0) { location = null; }
  73242. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  73243. return;
  73244. }
  73245. if (!location) {
  73246. location = this._haloCenter;
  73247. }
  73248. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  73249. // offset of the headset from the anchor.
  73250. if (this.webVRCamera.leftCamera) {
  73251. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  73252. this._workingVector.subtractInPlace(this.webVRCamera.position);
  73253. location.subtractToRef(this._workingVector, this._workingVector);
  73254. }
  73255. else {
  73256. this._workingVector.copyFrom(location);
  73257. }
  73258. // Add height to account for user's height offset
  73259. if (this.isInVRMode) {
  73260. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  73261. }
  73262. else {
  73263. this._workingVector.y += this._defaultHeight;
  73264. }
  73265. // Create animation from the camera's position to the new location
  73266. this.currentVRCamera.animations = [];
  73267. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  73268. var animationCameraTeleportationKeys = [{
  73269. frame: 0,
  73270. value: this.currentVRCamera.position
  73271. },
  73272. {
  73273. frame: 11,
  73274. value: this._workingVector
  73275. }
  73276. ];
  73277. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  73278. animationCameraTeleportation.setEasingFunction(this._circleEase);
  73279. this.currentVRCamera.animations.push(animationCameraTeleportation);
  73280. this._postProcessMove.animations = [];
  73281. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  73282. var vignetteWeightKeys = [];
  73283. vignetteWeightKeys.push({
  73284. frame: 0,
  73285. value: 0
  73286. });
  73287. vignetteWeightKeys.push({
  73288. frame: 5,
  73289. value: 8
  73290. });
  73291. vignetteWeightKeys.push({
  73292. frame: 11,
  73293. value: 0
  73294. });
  73295. animationPP.setKeys(vignetteWeightKeys);
  73296. this._postProcessMove.animations.push(animationPP);
  73297. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  73298. var vignetteStretchKeys = [];
  73299. vignetteStretchKeys.push({
  73300. frame: 0,
  73301. value: 0
  73302. });
  73303. vignetteStretchKeys.push({
  73304. frame: 5,
  73305. value: 10
  73306. });
  73307. vignetteStretchKeys.push({
  73308. frame: 11,
  73309. value: 0
  73310. });
  73311. animationPP2.setKeys(vignetteStretchKeys);
  73312. this._postProcessMove.animations.push(animationPP2);
  73313. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  73314. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  73315. this._webVRCamera.attachPostProcess(this._postProcessMove);
  73316. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  73317. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  73318. });
  73319. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1);
  73320. };
  73321. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  73322. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  73323. return;
  73324. }
  73325. var ray;
  73326. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  73327. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  73328. }
  73329. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  73330. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  73331. }
  73332. else {
  73333. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  73334. }
  73335. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  73336. // Moving the gazeTracker on the mesh face targetted
  73337. if (hit && hit.pickedPoint) {
  73338. if (this._displayGaze) {
  73339. var multiplier = 1;
  73340. this._gazeTracker.isVisible = true;
  73341. if (this._isActionableMesh) {
  73342. multiplier = 3;
  73343. }
  73344. this._gazeTracker.scaling.x = hit.distance * multiplier;
  73345. this._gazeTracker.scaling.y = hit.distance * multiplier;
  73346. this._gazeTracker.scaling.z = hit.distance * multiplier;
  73347. var pickNormal = hit.getNormal();
  73348. // To avoid z-fighting
  73349. var deltaFighting = 0.002;
  73350. if (pickNormal) {
  73351. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  73352. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  73353. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  73354. }
  73355. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  73356. if (this._gazeTracker.position.x < 0) {
  73357. this._gazeTracker.position.x += deltaFighting;
  73358. }
  73359. else {
  73360. this._gazeTracker.position.x -= deltaFighting;
  73361. }
  73362. if (this._gazeTracker.position.y < 0) {
  73363. this._gazeTracker.position.y += deltaFighting;
  73364. }
  73365. else {
  73366. this._gazeTracker.position.y -= deltaFighting;
  73367. }
  73368. if (this._gazeTracker.position.z < 0) {
  73369. this._gazeTracker.position.z += deltaFighting;
  73370. }
  73371. else {
  73372. this._gazeTracker.position.z -= deltaFighting;
  73373. }
  73374. }
  73375. // Changing the size of the laser pointer based on the distance from the targetted point
  73376. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  73377. this._rightLaserPointer.scaling.y = hit.distance;
  73378. this._rightLaserPointer.position.z = -hit.distance / 2;
  73379. }
  73380. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  73381. this._leftLaserPointer.scaling.y = hit.distance;
  73382. this._leftLaserPointer.position.z = -hit.distance / 2;
  73383. }
  73384. }
  73385. else {
  73386. this._gazeTracker.isVisible = false;
  73387. }
  73388. if (hit && hit.pickedMesh) {
  73389. this._currentHit = hit;
  73390. if (this._pointerDownOnMeshAsked) {
  73391. this._scene.simulatePointerMove(this._currentHit);
  73392. }
  73393. // The object selected is the floor, we're in a teleportation scenario
  73394. if (this._teleportationEnabled && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  73395. // Moving the teleportation area to this targetted point
  73396. this._moveTeleportationSelectorTo(hit);
  73397. return;
  73398. }
  73399. // If not, we're in a selection scenario
  73400. this._hideTeleportationTarget();
  73401. this._teleportationAllowed = false;
  73402. if (hit.pickedMesh !== this._currentMeshSelected) {
  73403. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  73404. this._currentMeshSelected = hit.pickedMesh;
  73405. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  73406. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  73407. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  73408. this._isActionableMesh = true;
  73409. }
  73410. else {
  73411. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  73412. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  73413. this._isActionableMesh = false;
  73414. }
  73415. try {
  73416. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  73417. }
  73418. catch (err) {
  73419. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  73420. }
  73421. }
  73422. else {
  73423. this._currentMeshSelected = null;
  73424. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  73425. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  73426. }
  73427. }
  73428. }
  73429. else {
  73430. this._currentHit = null;
  73431. this._currentMeshSelected = null;
  73432. this._teleportationAllowed = false;
  73433. this._hideTeleportationTarget();
  73434. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  73435. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  73436. }
  73437. };
  73438. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  73439. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  73440. this._leftLaserPointer.material.emissiveColor = color;
  73441. }
  73442. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  73443. this._rightLaserPointer.material.emissiveColor = color;
  73444. }
  73445. };
  73446. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  73447. if (this._gazeTracker.material) {
  73448. this._gazeTracker.material.emissiveColor = color;
  73449. }
  73450. };
  73451. VRExperienceHelper.prototype.dispose = function () {
  73452. if (this.isInVRMode) {
  73453. this.exitVR();
  73454. }
  73455. if (this._passProcessMove) {
  73456. this._passProcessMove.dispose();
  73457. }
  73458. if (this._postProcessMove) {
  73459. this._postProcessMove.dispose();
  73460. }
  73461. if (this._webVRCamera) {
  73462. this._webVRCamera.dispose();
  73463. }
  73464. if (this._vrDeviceOrientationCamera) {
  73465. this._vrDeviceOrientationCamera.dispose();
  73466. }
  73467. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  73468. document.body.removeChild(this._btnVR);
  73469. }
  73470. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  73471. this._deviceOrientationCamera.dispose();
  73472. }
  73473. if (this._gazeTracker) {
  73474. this._gazeTracker.dispose();
  73475. }
  73476. if (this._teleportationTarget) {
  73477. this._teleportationTarget.dispose();
  73478. }
  73479. this._floorMeshesCollection = [];
  73480. document.removeEventListener("keydown", this._onKeyDown);
  73481. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  73482. window.removeEventListener("resize", this._onResize);
  73483. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  73484. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  73485. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  73486. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  73487. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  73488. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  73489. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  73490. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  73491. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  73492. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  73493. this._scene.unregisterBeforeRender(this.beforeRender);
  73494. };
  73495. VRExperienceHelper.prototype.getClassName = function () {
  73496. return "VRExperienceHelper";
  73497. };
  73498. return VRExperienceHelper;
  73499. }());
  73500. BABYLON.VRExperienceHelper = VRExperienceHelper;
  73501. })(BABYLON || (BABYLON = {}));
  73502. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  73503. // Mainly based on these 2 articles :
  73504. // 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
  73505. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  73506. var BABYLON;
  73507. (function (BABYLON) {
  73508. var JoystickAxis;
  73509. (function (JoystickAxis) {
  73510. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  73511. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  73512. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  73513. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  73514. var VirtualJoystick = /** @class */ (function () {
  73515. function VirtualJoystick(leftJoystick) {
  73516. var _this = this;
  73517. if (leftJoystick) {
  73518. this._leftJoystick = true;
  73519. }
  73520. else {
  73521. this._leftJoystick = false;
  73522. }
  73523. VirtualJoystick._globalJoystickIndex++;
  73524. // By default left & right arrow keys are moving the X
  73525. // and up & down keys are moving the Y
  73526. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  73527. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  73528. this.reverseLeftRight = false;
  73529. this.reverseUpDown = false;
  73530. // collections of pointers
  73531. this._touches = new BABYLON.StringDictionary();
  73532. this.deltaPosition = BABYLON.Vector3.Zero();
  73533. this._joystickSensibility = 25;
  73534. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  73535. this._onResize = function (evt) {
  73536. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  73537. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  73538. if (VirtualJoystick.vjCanvas) {
  73539. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  73540. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  73541. }
  73542. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  73543. };
  73544. // injecting a canvas element on top of the canvas 3D game
  73545. if (!VirtualJoystick.vjCanvas) {
  73546. window.addEventListener("resize", this._onResize, false);
  73547. VirtualJoystick.vjCanvas = document.createElement("canvas");
  73548. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  73549. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  73550. VirtualJoystick.vjCanvas.width = window.innerWidth;
  73551. VirtualJoystick.vjCanvas.height = window.innerHeight;
  73552. VirtualJoystick.vjCanvas.style.width = "100%";
  73553. VirtualJoystick.vjCanvas.style.height = "100%";
  73554. VirtualJoystick.vjCanvas.style.position = "absolute";
  73555. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  73556. VirtualJoystick.vjCanvas.style.top = "0px";
  73557. VirtualJoystick.vjCanvas.style.left = "0px";
  73558. VirtualJoystick.vjCanvas.style.zIndex = "5";
  73559. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  73560. // Support for jQuery PEP polyfill
  73561. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  73562. var context = VirtualJoystick.vjCanvas.getContext('2d');
  73563. if (!context) {
  73564. throw new Error("Unable to create canvas for virtual joystick");
  73565. }
  73566. VirtualJoystick.vjCanvasContext = context;
  73567. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  73568. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  73569. document.body.appendChild(VirtualJoystick.vjCanvas);
  73570. }
  73571. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  73572. this.pressed = false;
  73573. // default joystick color
  73574. this._joystickColor = "cyan";
  73575. this._joystickPointerID = -1;
  73576. // current joystick position
  73577. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  73578. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  73579. // origin joystick position
  73580. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  73581. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  73582. this._onPointerDownHandlerRef = function (evt) {
  73583. _this._onPointerDown(evt);
  73584. };
  73585. this._onPointerMoveHandlerRef = function (evt) {
  73586. _this._onPointerMove(evt);
  73587. };
  73588. this._onPointerUpHandlerRef = function (evt) {
  73589. _this._onPointerUp(evt);
  73590. };
  73591. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  73592. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  73593. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  73594. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  73595. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  73596. evt.preventDefault(); // Disables system menu
  73597. }, false);
  73598. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  73599. }
  73600. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  73601. this._joystickSensibility = newJoystickSensibility;
  73602. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  73603. };
  73604. VirtualJoystick.prototype._onPointerDown = function (e) {
  73605. var positionOnScreenCondition;
  73606. e.preventDefault();
  73607. if (this._leftJoystick === true) {
  73608. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  73609. }
  73610. else {
  73611. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  73612. }
  73613. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  73614. // First contact will be dedicated to the virtual joystick
  73615. this._joystickPointerID = e.pointerId;
  73616. this._joystickPointerStartPos.x = e.clientX;
  73617. this._joystickPointerStartPos.y = e.clientY;
  73618. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  73619. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  73620. this._deltaJoystickVector.x = 0;
  73621. this._deltaJoystickVector.y = 0;
  73622. this.pressed = true;
  73623. this._touches.add(e.pointerId.toString(), e);
  73624. }
  73625. else {
  73626. // You can only trigger the action buttons with a joystick declared
  73627. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  73628. this._action();
  73629. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  73630. }
  73631. }
  73632. };
  73633. VirtualJoystick.prototype._onPointerMove = function (e) {
  73634. // If the current pointer is the one associated to the joystick (first touch contact)
  73635. if (this._joystickPointerID == e.pointerId) {
  73636. this._joystickPointerPos.x = e.clientX;
  73637. this._joystickPointerPos.y = e.clientY;
  73638. this._deltaJoystickVector = this._joystickPointerPos.clone();
  73639. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  73640. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  73641. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  73642. switch (this._axisTargetedByLeftAndRight) {
  73643. case JoystickAxis.X:
  73644. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  73645. break;
  73646. case JoystickAxis.Y:
  73647. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  73648. break;
  73649. case JoystickAxis.Z:
  73650. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  73651. break;
  73652. }
  73653. var directionUpDown = this.reverseUpDown ? 1 : -1;
  73654. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  73655. switch (this._axisTargetedByUpAndDown) {
  73656. case JoystickAxis.X:
  73657. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  73658. break;
  73659. case JoystickAxis.Y:
  73660. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  73661. break;
  73662. case JoystickAxis.Z:
  73663. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  73664. break;
  73665. }
  73666. }
  73667. else {
  73668. var data = this._touches.get(e.pointerId.toString());
  73669. if (data) {
  73670. data.x = e.clientX;
  73671. data.y = e.clientY;
  73672. }
  73673. }
  73674. };
  73675. VirtualJoystick.prototype._onPointerUp = function (e) {
  73676. if (this._joystickPointerID == e.pointerId) {
  73677. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  73678. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  73679. this._joystickPointerID = -1;
  73680. this.pressed = false;
  73681. }
  73682. else {
  73683. var touch = this._touches.get(e.pointerId.toString());
  73684. if (touch) {
  73685. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  73686. }
  73687. }
  73688. this._deltaJoystickVector.x = 0;
  73689. this._deltaJoystickVector.y = 0;
  73690. this._touches.remove(e.pointerId.toString());
  73691. };
  73692. /**
  73693. * Change the color of the virtual joystick
  73694. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  73695. */
  73696. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  73697. this._joystickColor = newColor;
  73698. };
  73699. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  73700. this._action = action;
  73701. };
  73702. // Define which axis you'd like to control for left & right
  73703. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  73704. switch (axis) {
  73705. case JoystickAxis.X:
  73706. case JoystickAxis.Y:
  73707. case JoystickAxis.Z:
  73708. this._axisTargetedByLeftAndRight = axis;
  73709. break;
  73710. default:
  73711. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  73712. break;
  73713. }
  73714. };
  73715. // Define which axis you'd like to control for up & down
  73716. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  73717. switch (axis) {
  73718. case JoystickAxis.X:
  73719. case JoystickAxis.Y:
  73720. case JoystickAxis.Z:
  73721. this._axisTargetedByUpAndDown = axis;
  73722. break;
  73723. default:
  73724. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  73725. break;
  73726. }
  73727. };
  73728. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  73729. var _this = this;
  73730. if (this.pressed) {
  73731. this._touches.forEach(function (key, touch) {
  73732. if (touch.pointerId === _this._joystickPointerID) {
  73733. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  73734. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  73735. VirtualJoystick.vjCanvasContext.beginPath();
  73736. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  73737. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  73738. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  73739. VirtualJoystick.vjCanvasContext.stroke();
  73740. VirtualJoystick.vjCanvasContext.closePath();
  73741. VirtualJoystick.vjCanvasContext.beginPath();
  73742. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  73743. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  73744. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  73745. VirtualJoystick.vjCanvasContext.stroke();
  73746. VirtualJoystick.vjCanvasContext.closePath();
  73747. VirtualJoystick.vjCanvasContext.beginPath();
  73748. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  73749. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  73750. VirtualJoystick.vjCanvasContext.stroke();
  73751. VirtualJoystick.vjCanvasContext.closePath();
  73752. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  73753. }
  73754. else {
  73755. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  73756. VirtualJoystick.vjCanvasContext.beginPath();
  73757. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  73758. VirtualJoystick.vjCanvasContext.beginPath();
  73759. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  73760. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  73761. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  73762. VirtualJoystick.vjCanvasContext.stroke();
  73763. VirtualJoystick.vjCanvasContext.closePath();
  73764. touch.prevX = touch.x;
  73765. touch.prevY = touch.y;
  73766. }
  73767. ;
  73768. });
  73769. }
  73770. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  73771. };
  73772. VirtualJoystick.prototype.releaseCanvas = function () {
  73773. if (VirtualJoystick.vjCanvas) {
  73774. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  73775. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  73776. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  73777. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  73778. window.removeEventListener("resize", this._onResize);
  73779. document.body.removeChild(VirtualJoystick.vjCanvas);
  73780. VirtualJoystick.vjCanvas = null;
  73781. }
  73782. };
  73783. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  73784. VirtualJoystick._globalJoystickIndex = 0;
  73785. return VirtualJoystick;
  73786. }());
  73787. BABYLON.VirtualJoystick = VirtualJoystick;
  73788. })(BABYLON || (BABYLON = {}));
  73789. //# sourceMappingURL=babylon.virtualJoystick.js.map
  73790. var BABYLON;
  73791. (function (BABYLON) {
  73792. // We're mainly based on the logic defined into the FreeCamera code
  73793. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  73794. __extends(VirtualJoysticksCamera, _super);
  73795. function VirtualJoysticksCamera(name, position, scene) {
  73796. var _this = _super.call(this, name, position, scene) || this;
  73797. _this.inputs.addVirtualJoystick();
  73798. return _this;
  73799. }
  73800. VirtualJoysticksCamera.prototype.getClassName = function () {
  73801. return "VirtualJoysticksCamera";
  73802. };
  73803. return VirtualJoysticksCamera;
  73804. }(BABYLON.FreeCamera));
  73805. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  73806. })(BABYLON || (BABYLON = {}));
  73807. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  73808. var BABYLON;
  73809. (function (BABYLON) {
  73810. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  73811. function FreeCameraVirtualJoystickInput() {
  73812. }
  73813. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  73814. return this._leftjoystick;
  73815. };
  73816. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  73817. return this._rightjoystick;
  73818. };
  73819. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  73820. if (this._leftjoystick) {
  73821. var camera = this.camera;
  73822. var speed = camera._computeLocalCameraSpeed() * 50;
  73823. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  73824. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  73825. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  73826. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  73827. if (!this._leftjoystick.pressed) {
  73828. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  73829. }
  73830. if (!this._rightjoystick.pressed) {
  73831. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  73832. }
  73833. }
  73834. };
  73835. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  73836. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  73837. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  73838. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  73839. this._leftjoystick.setJoystickSensibility(0.15);
  73840. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  73841. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  73842. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  73843. this._rightjoystick.reverseUpDown = true;
  73844. this._rightjoystick.setJoystickSensibility(0.05);
  73845. this._rightjoystick.setJoystickColor("yellow");
  73846. };
  73847. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  73848. this._leftjoystick.releaseCanvas();
  73849. this._rightjoystick.releaseCanvas();
  73850. };
  73851. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  73852. return "FreeCameraVirtualJoystickInput";
  73853. };
  73854. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  73855. return "virtualJoystick";
  73856. };
  73857. return FreeCameraVirtualJoystickInput;
  73858. }());
  73859. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  73860. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  73861. })(BABYLON || (BABYLON = {}));
  73862. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  73863. var BABYLON;
  73864. (function (BABYLON) {
  73865. var SimplificationSettings = /** @class */ (function () {
  73866. function SimplificationSettings(quality, distance, optimizeMesh) {
  73867. this.quality = quality;
  73868. this.distance = distance;
  73869. this.optimizeMesh = optimizeMesh;
  73870. }
  73871. return SimplificationSettings;
  73872. }());
  73873. BABYLON.SimplificationSettings = SimplificationSettings;
  73874. var SimplificationQueue = /** @class */ (function () {
  73875. function SimplificationQueue() {
  73876. this.running = false;
  73877. this._simplificationArray = [];
  73878. }
  73879. SimplificationQueue.prototype.addTask = function (task) {
  73880. this._simplificationArray.push(task);
  73881. };
  73882. SimplificationQueue.prototype.executeNext = function () {
  73883. var task = this._simplificationArray.pop();
  73884. if (task) {
  73885. this.running = true;
  73886. this.runSimplification(task);
  73887. }
  73888. else {
  73889. this.running = false;
  73890. }
  73891. };
  73892. SimplificationQueue.prototype.runSimplification = function (task) {
  73893. var _this = this;
  73894. if (task.parallelProcessing) {
  73895. //parallel simplifier
  73896. task.settings.forEach(function (setting) {
  73897. var simplifier = _this.getSimplifier(task);
  73898. simplifier.simplify(setting, function (newMesh) {
  73899. task.mesh.addLODLevel(setting.distance, newMesh);
  73900. newMesh.isVisible = true;
  73901. //check if it is the last
  73902. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  73903. //all done, run the success callback.
  73904. task.successCallback();
  73905. }
  73906. _this.executeNext();
  73907. });
  73908. });
  73909. }
  73910. else {
  73911. //single simplifier.
  73912. var simplifier = this.getSimplifier(task);
  73913. var runDecimation = function (setting, callback) {
  73914. simplifier.simplify(setting, function (newMesh) {
  73915. task.mesh.addLODLevel(setting.distance, newMesh);
  73916. newMesh.isVisible = true;
  73917. //run the next quality level
  73918. callback();
  73919. });
  73920. };
  73921. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  73922. runDecimation(task.settings[loop.index], function () {
  73923. loop.executeNext();
  73924. });
  73925. }, function () {
  73926. //execution ended, run the success callback.
  73927. if (task.successCallback) {
  73928. task.successCallback();
  73929. }
  73930. _this.executeNext();
  73931. });
  73932. }
  73933. };
  73934. SimplificationQueue.prototype.getSimplifier = function (task) {
  73935. switch (task.simplificationType) {
  73936. case SimplificationType.QUADRATIC:
  73937. default:
  73938. return new QuadraticErrorSimplification(task.mesh);
  73939. }
  73940. };
  73941. return SimplificationQueue;
  73942. }());
  73943. BABYLON.SimplificationQueue = SimplificationQueue;
  73944. /**
  73945. * The implemented types of simplification.
  73946. * At the moment only Quadratic Error Decimation is implemented.
  73947. */
  73948. var SimplificationType;
  73949. (function (SimplificationType) {
  73950. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  73951. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  73952. var DecimationTriangle = /** @class */ (function () {
  73953. function DecimationTriangle(vertices) {
  73954. this.vertices = vertices;
  73955. this.error = new Array(4);
  73956. this.deleted = false;
  73957. this.isDirty = false;
  73958. this.deletePending = false;
  73959. this.borderFactor = 0;
  73960. }
  73961. return DecimationTriangle;
  73962. }());
  73963. BABYLON.DecimationTriangle = DecimationTriangle;
  73964. var DecimationVertex = /** @class */ (function () {
  73965. function DecimationVertex(position, id) {
  73966. this.position = position;
  73967. this.id = id;
  73968. this.isBorder = true;
  73969. this.q = new QuadraticMatrix();
  73970. this.triangleCount = 0;
  73971. this.triangleStart = 0;
  73972. this.originalOffsets = [];
  73973. }
  73974. DecimationVertex.prototype.updatePosition = function (newPosition) {
  73975. this.position.copyFrom(newPosition);
  73976. };
  73977. return DecimationVertex;
  73978. }());
  73979. BABYLON.DecimationVertex = DecimationVertex;
  73980. var QuadraticMatrix = /** @class */ (function () {
  73981. function QuadraticMatrix(data) {
  73982. this.data = new Array(10);
  73983. for (var i = 0; i < 10; ++i) {
  73984. if (data && data[i]) {
  73985. this.data[i] = data[i];
  73986. }
  73987. else {
  73988. this.data[i] = 0;
  73989. }
  73990. }
  73991. }
  73992. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  73993. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  73994. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  73995. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  73996. return det;
  73997. };
  73998. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  73999. for (var i = 0; i < 10; ++i) {
  74000. this.data[i] += matrix.data[i];
  74001. }
  74002. };
  74003. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  74004. for (var i = 0; i < 10; ++i) {
  74005. this.data[i] += data[i];
  74006. }
  74007. };
  74008. QuadraticMatrix.prototype.add = function (matrix) {
  74009. var m = new QuadraticMatrix();
  74010. for (var i = 0; i < 10; ++i) {
  74011. m.data[i] = this.data[i] + matrix.data[i];
  74012. }
  74013. return m;
  74014. };
  74015. QuadraticMatrix.FromData = function (a, b, c, d) {
  74016. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  74017. };
  74018. //returning an array to avoid garbage collection
  74019. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  74020. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  74021. };
  74022. return QuadraticMatrix;
  74023. }());
  74024. BABYLON.QuadraticMatrix = QuadraticMatrix;
  74025. var Reference = /** @class */ (function () {
  74026. function Reference(vertexId, triangleId) {
  74027. this.vertexId = vertexId;
  74028. this.triangleId = triangleId;
  74029. }
  74030. return Reference;
  74031. }());
  74032. BABYLON.Reference = Reference;
  74033. /**
  74034. * An implementation of the Quadratic Error simplification algorithm.
  74035. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  74036. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  74037. * @author RaananW
  74038. */
  74039. var QuadraticErrorSimplification = /** @class */ (function () {
  74040. function QuadraticErrorSimplification(_mesh) {
  74041. this._mesh = _mesh;
  74042. this.syncIterations = 5000;
  74043. this.aggressiveness = 7;
  74044. this.decimationIterations = 100;
  74045. this.boundingBoxEpsilon = BABYLON.Epsilon;
  74046. }
  74047. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  74048. var _this = this;
  74049. this.initDecimatedMesh();
  74050. //iterating through the submeshes array, one after the other.
  74051. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  74052. _this.initWithMesh(loop.index, function () {
  74053. _this.runDecimation(settings, loop.index, function () {
  74054. loop.executeNext();
  74055. });
  74056. }, settings.optimizeMesh);
  74057. }, function () {
  74058. setTimeout(function () {
  74059. successCallback(_this._reconstructedMesh);
  74060. }, 0);
  74061. });
  74062. };
  74063. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  74064. var _this = this;
  74065. var targetCount = ~~(this.triangles.length * settings.quality);
  74066. var deletedTriangles = 0;
  74067. var triangleCount = this.triangles.length;
  74068. var iterationFunction = function (iteration, callback) {
  74069. setTimeout(function () {
  74070. if (iteration % 5 === 0) {
  74071. _this.updateMesh(iteration === 0);
  74072. }
  74073. for (var i = 0; i < _this.triangles.length; ++i) {
  74074. _this.triangles[i].isDirty = false;
  74075. }
  74076. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  74077. var trianglesIterator = function (i) {
  74078. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  74079. var t = _this.triangles[tIdx];
  74080. if (!t)
  74081. return;
  74082. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  74083. return;
  74084. }
  74085. for (var j = 0; j < 3; ++j) {
  74086. if (t.error[j] < threshold) {
  74087. var deleted0 = [];
  74088. var deleted1 = [];
  74089. var v0 = t.vertices[j];
  74090. var v1 = t.vertices[(j + 1) % 3];
  74091. if (v0.isBorder || v1.isBorder)
  74092. continue;
  74093. var p = BABYLON.Vector3.Zero();
  74094. var n = BABYLON.Vector3.Zero();
  74095. var uv = BABYLON.Vector2.Zero();
  74096. var color = new BABYLON.Color4(0, 0, 0, 1);
  74097. _this.calculateError(v0, v1, p, n, uv, color);
  74098. var delTr = new Array();
  74099. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  74100. continue;
  74101. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  74102. continue;
  74103. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  74104. continue;
  74105. var uniqueArray = new Array();
  74106. delTr.forEach(function (deletedT) {
  74107. if (uniqueArray.indexOf(deletedT) === -1) {
  74108. deletedT.deletePending = true;
  74109. uniqueArray.push(deletedT);
  74110. }
  74111. });
  74112. if (uniqueArray.length % 2 !== 0) {
  74113. continue;
  74114. }
  74115. v0.q = v1.q.add(v0.q);
  74116. v0.updatePosition(p);
  74117. var tStart = _this.references.length;
  74118. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  74119. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  74120. var tCount = _this.references.length - tStart;
  74121. if (tCount <= v0.triangleCount) {
  74122. if (tCount) {
  74123. for (var c = 0; c < tCount; c++) {
  74124. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  74125. }
  74126. }
  74127. }
  74128. else {
  74129. v0.triangleStart = tStart;
  74130. }
  74131. v0.triangleCount = tCount;
  74132. break;
  74133. }
  74134. }
  74135. };
  74136. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  74137. }, 0);
  74138. };
  74139. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  74140. if (triangleCount - deletedTriangles <= targetCount)
  74141. loop.breakLoop();
  74142. else {
  74143. iterationFunction(loop.index, function () {
  74144. loop.executeNext();
  74145. });
  74146. }
  74147. }, function () {
  74148. setTimeout(function () {
  74149. //reconstruct this part of the mesh
  74150. _this.reconstructMesh(submeshIndex);
  74151. successCallback();
  74152. }, 0);
  74153. });
  74154. };
  74155. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  74156. var _this = this;
  74157. this.vertices = [];
  74158. this.triangles = [];
  74159. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  74160. var indices = this._mesh.getIndices();
  74161. var submesh = this._mesh.subMeshes[submeshIndex];
  74162. var findInVertices = function (positionToSearch) {
  74163. if (optimizeMesh) {
  74164. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  74165. if (_this.vertices[ii].position.equals(positionToSearch)) {
  74166. return _this.vertices[ii];
  74167. }
  74168. }
  74169. }
  74170. return null;
  74171. };
  74172. var vertexReferences = [];
  74173. var vertexInit = function (i) {
  74174. if (!positionData) {
  74175. return;
  74176. }
  74177. var offset = i + submesh.verticesStart;
  74178. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  74179. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  74180. vertex.originalOffsets.push(offset);
  74181. if (vertex.id === _this.vertices.length) {
  74182. _this.vertices.push(vertex);
  74183. }
  74184. vertexReferences.push(vertex.id);
  74185. };
  74186. //var totalVertices = mesh.getTotalVertices();
  74187. var totalVertices = submesh.verticesCount;
  74188. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  74189. var indicesInit = function (i) {
  74190. if (!indices) {
  74191. return;
  74192. }
  74193. var offset = (submesh.indexStart / 3) + i;
  74194. var pos = (offset * 3);
  74195. var i0 = indices[pos + 0];
  74196. var i1 = indices[pos + 1];
  74197. var i2 = indices[pos + 2];
  74198. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  74199. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  74200. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  74201. var triangle = new DecimationTriangle([v0, v1, v2]);
  74202. triangle.originalOffset = pos;
  74203. _this.triangles.push(triangle);
  74204. };
  74205. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  74206. _this.init(callback);
  74207. });
  74208. });
  74209. };
  74210. QuadraticErrorSimplification.prototype.init = function (callback) {
  74211. var _this = this;
  74212. var triangleInit1 = function (i) {
  74213. var t = _this.triangles[i];
  74214. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  74215. for (var j = 0; j < 3; j++) {
  74216. 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))));
  74217. }
  74218. };
  74219. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  74220. var triangleInit2 = function (i) {
  74221. var t = _this.triangles[i];
  74222. for (var j = 0; j < 3; ++j) {
  74223. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  74224. }
  74225. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  74226. };
  74227. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  74228. callback();
  74229. });
  74230. });
  74231. };
  74232. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  74233. var newTriangles = [];
  74234. var i;
  74235. for (i = 0; i < this.vertices.length; ++i) {
  74236. this.vertices[i].triangleCount = 0;
  74237. }
  74238. var t;
  74239. var j;
  74240. for (i = 0; i < this.triangles.length; ++i) {
  74241. if (!this.triangles[i].deleted) {
  74242. t = this.triangles[i];
  74243. for (j = 0; j < 3; ++j) {
  74244. t.vertices[j].triangleCount = 1;
  74245. }
  74246. newTriangles.push(t);
  74247. }
  74248. }
  74249. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  74250. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  74251. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  74252. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  74253. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  74254. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  74255. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  74256. var vertexCount = 0;
  74257. for (i = 0; i < this.vertices.length; ++i) {
  74258. var vertex = this.vertices[i];
  74259. vertex.id = vertexCount;
  74260. if (vertex.triangleCount) {
  74261. vertex.originalOffsets.forEach(function (originalOffset) {
  74262. if (!normalData) {
  74263. return;
  74264. }
  74265. newPositionData.push(vertex.position.x);
  74266. newPositionData.push(vertex.position.y);
  74267. newPositionData.push(vertex.position.z);
  74268. newNormalData.push(normalData[originalOffset * 3]);
  74269. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  74270. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  74271. if (uvs && uvs.length) {
  74272. newUVsData.push(uvs[(originalOffset * 2)]);
  74273. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  74274. }
  74275. else if (colorsData && colorsData.length) {
  74276. newColorsData.push(colorsData[(originalOffset * 4)]);
  74277. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  74278. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  74279. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  74280. }
  74281. ++vertexCount;
  74282. });
  74283. }
  74284. }
  74285. var startingIndex = this._reconstructedMesh.getTotalIndices();
  74286. var startingVertex = this._reconstructedMesh.getTotalVertices();
  74287. var submeshesArray = this._reconstructedMesh.subMeshes;
  74288. this._reconstructedMesh.subMeshes = [];
  74289. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  74290. var originalIndices = this._mesh.getIndices();
  74291. for (i = 0; i < newTriangles.length; ++i) {
  74292. t = newTriangles[i]; //now get the new referencing point for each vertex
  74293. [0, 1, 2].forEach(function (idx) {
  74294. var id = originalIndices[t.originalOffset + idx];
  74295. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  74296. if (offset < 0)
  74297. offset = 0;
  74298. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  74299. });
  74300. }
  74301. //overwriting the old vertex buffers and indices.
  74302. this._reconstructedMesh.setIndices(newIndicesArray);
  74303. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  74304. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  74305. if (newUVsData.length > 0)
  74306. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  74307. if (newColorsData.length > 0)
  74308. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  74309. //create submesh
  74310. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  74311. if (submeshIndex > 0) {
  74312. this._reconstructedMesh.subMeshes = [];
  74313. submeshesArray.forEach(function (submesh) {
  74314. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  74315. });
  74316. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  74317. }
  74318. };
  74319. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  74320. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  74321. this._reconstructedMesh.material = this._mesh.material;
  74322. this._reconstructedMesh.parent = this._mesh.parent;
  74323. this._reconstructedMesh.isVisible = false;
  74324. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  74325. };
  74326. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  74327. for (var i = 0; i < vertex1.triangleCount; ++i) {
  74328. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  74329. if (t.deleted)
  74330. continue;
  74331. var s = this.references[vertex1.triangleStart + i].vertexId;
  74332. var v1 = t.vertices[(s + 1) % 3];
  74333. var v2 = t.vertices[(s + 2) % 3];
  74334. if ((v1 === vertex2 || v2 === vertex2)) {
  74335. deletedArray[i] = true;
  74336. delTr.push(t);
  74337. continue;
  74338. }
  74339. var d1 = v1.position.subtract(point);
  74340. d1 = d1.normalize();
  74341. var d2 = v2.position.subtract(point);
  74342. d2 = d2.normalize();
  74343. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  74344. return true;
  74345. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  74346. deletedArray[i] = false;
  74347. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  74348. return true;
  74349. }
  74350. return false;
  74351. };
  74352. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  74353. var newDeleted = deletedTriangles;
  74354. for (var i = 0; i < vertex.triangleCount; ++i) {
  74355. var ref = this.references[vertex.triangleStart + i];
  74356. var t = this.triangles[ref.triangleId];
  74357. if (t.deleted)
  74358. continue;
  74359. if (deletedArray[i] && t.deletePending) {
  74360. t.deleted = true;
  74361. newDeleted++;
  74362. continue;
  74363. }
  74364. t.vertices[ref.vertexId] = origVertex;
  74365. t.isDirty = true;
  74366. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  74367. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  74368. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  74369. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  74370. this.references.push(ref);
  74371. }
  74372. return newDeleted;
  74373. };
  74374. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  74375. for (var i = 0; i < this.vertices.length; ++i) {
  74376. var vCount = [];
  74377. var vId = [];
  74378. var v = this.vertices[i];
  74379. var j;
  74380. for (j = 0; j < v.triangleCount; ++j) {
  74381. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  74382. for (var ii = 0; ii < 3; ii++) {
  74383. var ofs = 0;
  74384. var vv = triangle.vertices[ii];
  74385. while (ofs < vCount.length) {
  74386. if (vId[ofs] === vv.id)
  74387. break;
  74388. ++ofs;
  74389. }
  74390. if (ofs === vCount.length) {
  74391. vCount.push(1);
  74392. vId.push(vv.id);
  74393. }
  74394. else {
  74395. vCount[ofs]++;
  74396. }
  74397. }
  74398. }
  74399. for (j = 0; j < vCount.length; ++j) {
  74400. if (vCount[j] === 1) {
  74401. this.vertices[vId[j]].isBorder = true;
  74402. }
  74403. else {
  74404. this.vertices[vId[j]].isBorder = false;
  74405. }
  74406. }
  74407. }
  74408. };
  74409. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  74410. if (identifyBorders === void 0) { identifyBorders = false; }
  74411. var i;
  74412. if (!identifyBorders) {
  74413. var newTrianglesVector = [];
  74414. for (i = 0; i < this.triangles.length; ++i) {
  74415. if (!this.triangles[i].deleted) {
  74416. newTrianglesVector.push(this.triangles[i]);
  74417. }
  74418. }
  74419. this.triangles = newTrianglesVector;
  74420. }
  74421. for (i = 0; i < this.vertices.length; ++i) {
  74422. this.vertices[i].triangleCount = 0;
  74423. this.vertices[i].triangleStart = 0;
  74424. }
  74425. var t;
  74426. var j;
  74427. var v;
  74428. for (i = 0; i < this.triangles.length; ++i) {
  74429. t = this.triangles[i];
  74430. for (j = 0; j < 3; ++j) {
  74431. v = t.vertices[j];
  74432. v.triangleCount++;
  74433. }
  74434. }
  74435. var tStart = 0;
  74436. for (i = 0; i < this.vertices.length; ++i) {
  74437. this.vertices[i].triangleStart = tStart;
  74438. tStart += this.vertices[i].triangleCount;
  74439. this.vertices[i].triangleCount = 0;
  74440. }
  74441. var newReferences = new Array(this.triangles.length * 3);
  74442. for (i = 0; i < this.triangles.length; ++i) {
  74443. t = this.triangles[i];
  74444. for (j = 0; j < 3; ++j) {
  74445. v = t.vertices[j];
  74446. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  74447. v.triangleCount++;
  74448. }
  74449. }
  74450. this.references = newReferences;
  74451. if (identifyBorders) {
  74452. this.identifyBorder();
  74453. }
  74454. };
  74455. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  74456. var x = point.x;
  74457. var y = point.y;
  74458. var z = point.z;
  74459. 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
  74460. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  74461. };
  74462. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  74463. var q = vertex1.q.add(vertex2.q);
  74464. var border = vertex1.isBorder && vertex2.isBorder;
  74465. var error = 0;
  74466. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  74467. if (qDet !== 0 && !border) {
  74468. if (!pointResult) {
  74469. pointResult = BABYLON.Vector3.Zero();
  74470. }
  74471. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  74472. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  74473. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  74474. error = this.vertexError(q, pointResult);
  74475. }
  74476. else {
  74477. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  74478. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  74479. var error1 = this.vertexError(q, vertex1.position);
  74480. var error2 = this.vertexError(q, vertex2.position);
  74481. var error3 = this.vertexError(q, p3);
  74482. error = Math.min(error1, error2, error3);
  74483. if (error === error1) {
  74484. if (pointResult) {
  74485. pointResult.copyFrom(vertex1.position);
  74486. }
  74487. }
  74488. else if (error === error2) {
  74489. if (pointResult) {
  74490. pointResult.copyFrom(vertex2.position);
  74491. }
  74492. }
  74493. else {
  74494. if (pointResult) {
  74495. pointResult.copyFrom(p3);
  74496. }
  74497. }
  74498. }
  74499. return error;
  74500. };
  74501. return QuadraticErrorSimplification;
  74502. }());
  74503. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  74504. })(BABYLON || (BABYLON = {}));
  74505. //# sourceMappingURL=babylon.meshSimplification.js.map
  74506. var BABYLON;
  74507. (function (BABYLON) {
  74508. var Internals;
  74509. (function (Internals) {
  74510. var MeshLODLevel = /** @class */ (function () {
  74511. function MeshLODLevel(distance, mesh) {
  74512. this.distance = distance;
  74513. this.mesh = mesh;
  74514. }
  74515. return MeshLODLevel;
  74516. }());
  74517. Internals.MeshLODLevel = MeshLODLevel;
  74518. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  74519. })(BABYLON || (BABYLON = {}));
  74520. //# sourceMappingURL=babylon.meshLODLevel.js.map
  74521. var BABYLON;
  74522. (function (BABYLON) {
  74523. // Standard optimizations
  74524. var SceneOptimization = /** @class */ (function () {
  74525. function SceneOptimization(priority) {
  74526. if (priority === void 0) { priority = 0; }
  74527. this.priority = priority;
  74528. this.apply = function (scene) {
  74529. return true; // Return true if everything that can be done was applied
  74530. };
  74531. }
  74532. return SceneOptimization;
  74533. }());
  74534. BABYLON.SceneOptimization = SceneOptimization;
  74535. var TextureOptimization = /** @class */ (function (_super) {
  74536. __extends(TextureOptimization, _super);
  74537. function TextureOptimization(priority, maximumSize) {
  74538. if (priority === void 0) { priority = 0; }
  74539. if (maximumSize === void 0) { maximumSize = 1024; }
  74540. var _this = _super.call(this, priority) || this;
  74541. _this.priority = priority;
  74542. _this.maximumSize = maximumSize;
  74543. _this.apply = function (scene) {
  74544. var allDone = true;
  74545. for (var index = 0; index < scene.textures.length; index++) {
  74546. var texture = scene.textures[index];
  74547. if (!texture.canRescale || texture.getContext) {
  74548. continue;
  74549. }
  74550. var currentSize = texture.getSize();
  74551. var maxDimension = Math.max(currentSize.width, currentSize.height);
  74552. if (maxDimension > _this.maximumSize) {
  74553. texture.scale(0.5);
  74554. allDone = false;
  74555. }
  74556. }
  74557. return allDone;
  74558. };
  74559. return _this;
  74560. }
  74561. return TextureOptimization;
  74562. }(SceneOptimization));
  74563. BABYLON.TextureOptimization = TextureOptimization;
  74564. var HardwareScalingOptimization = /** @class */ (function (_super) {
  74565. __extends(HardwareScalingOptimization, _super);
  74566. function HardwareScalingOptimization(priority, maximumScale) {
  74567. if (priority === void 0) { priority = 0; }
  74568. if (maximumScale === void 0) { maximumScale = 2; }
  74569. var _this = _super.call(this, priority) || this;
  74570. _this.priority = priority;
  74571. _this.maximumScale = maximumScale;
  74572. _this._currentScale = 1;
  74573. _this.apply = function (scene) {
  74574. _this._currentScale++;
  74575. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  74576. return _this._currentScale >= _this.maximumScale;
  74577. };
  74578. return _this;
  74579. }
  74580. return HardwareScalingOptimization;
  74581. }(SceneOptimization));
  74582. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  74583. var ShadowsOptimization = /** @class */ (function (_super) {
  74584. __extends(ShadowsOptimization, _super);
  74585. function ShadowsOptimization() {
  74586. var _this = _super !== null && _super.apply(this, arguments) || this;
  74587. _this.apply = function (scene) {
  74588. scene.shadowsEnabled = false;
  74589. return true;
  74590. };
  74591. return _this;
  74592. }
  74593. return ShadowsOptimization;
  74594. }(SceneOptimization));
  74595. BABYLON.ShadowsOptimization = ShadowsOptimization;
  74596. var PostProcessesOptimization = /** @class */ (function (_super) {
  74597. __extends(PostProcessesOptimization, _super);
  74598. function PostProcessesOptimization() {
  74599. var _this = _super !== null && _super.apply(this, arguments) || this;
  74600. _this.apply = function (scene) {
  74601. scene.postProcessesEnabled = false;
  74602. return true;
  74603. };
  74604. return _this;
  74605. }
  74606. return PostProcessesOptimization;
  74607. }(SceneOptimization));
  74608. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  74609. var LensFlaresOptimization = /** @class */ (function (_super) {
  74610. __extends(LensFlaresOptimization, _super);
  74611. function LensFlaresOptimization() {
  74612. var _this = _super !== null && _super.apply(this, arguments) || this;
  74613. _this.apply = function (scene) {
  74614. scene.lensFlaresEnabled = false;
  74615. return true;
  74616. };
  74617. return _this;
  74618. }
  74619. return LensFlaresOptimization;
  74620. }(SceneOptimization));
  74621. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  74622. var ParticlesOptimization = /** @class */ (function (_super) {
  74623. __extends(ParticlesOptimization, _super);
  74624. function ParticlesOptimization() {
  74625. var _this = _super !== null && _super.apply(this, arguments) || this;
  74626. _this.apply = function (scene) {
  74627. scene.particlesEnabled = false;
  74628. return true;
  74629. };
  74630. return _this;
  74631. }
  74632. return ParticlesOptimization;
  74633. }(SceneOptimization));
  74634. BABYLON.ParticlesOptimization = ParticlesOptimization;
  74635. var RenderTargetsOptimization = /** @class */ (function (_super) {
  74636. __extends(RenderTargetsOptimization, _super);
  74637. function RenderTargetsOptimization() {
  74638. var _this = _super !== null && _super.apply(this, arguments) || this;
  74639. _this.apply = function (scene) {
  74640. scene.renderTargetsEnabled = false;
  74641. return true;
  74642. };
  74643. return _this;
  74644. }
  74645. return RenderTargetsOptimization;
  74646. }(SceneOptimization));
  74647. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  74648. var MergeMeshesOptimization = /** @class */ (function (_super) {
  74649. __extends(MergeMeshesOptimization, _super);
  74650. function MergeMeshesOptimization() {
  74651. var _this = _super !== null && _super.apply(this, arguments) || this;
  74652. _this._canBeMerged = function (abstractMesh) {
  74653. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  74654. return false;
  74655. }
  74656. var mesh = abstractMesh;
  74657. if (!mesh.isVisible || !mesh.isEnabled()) {
  74658. return false;
  74659. }
  74660. if (mesh.instances.length > 0) {
  74661. return false;
  74662. }
  74663. if (mesh.skeleton || mesh.hasLODLevels) {
  74664. return false;
  74665. }
  74666. if (mesh.parent) {
  74667. return false;
  74668. }
  74669. return true;
  74670. };
  74671. _this.apply = function (scene, updateSelectionTree) {
  74672. var globalPool = scene.meshes.slice(0);
  74673. var globalLength = globalPool.length;
  74674. for (var index = 0; index < globalLength; index++) {
  74675. var currentPool = new Array();
  74676. var current = globalPool[index];
  74677. // Checks
  74678. if (!_this._canBeMerged(current)) {
  74679. continue;
  74680. }
  74681. currentPool.push(current);
  74682. // Find compatible meshes
  74683. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  74684. var otherMesh = globalPool[subIndex];
  74685. if (!_this._canBeMerged(otherMesh)) {
  74686. continue;
  74687. }
  74688. if (otherMesh.material !== current.material) {
  74689. continue;
  74690. }
  74691. if (otherMesh.checkCollisions !== current.checkCollisions) {
  74692. continue;
  74693. }
  74694. currentPool.push(otherMesh);
  74695. globalLength--;
  74696. globalPool.splice(subIndex, 1);
  74697. subIndex--;
  74698. }
  74699. if (currentPool.length < 2) {
  74700. continue;
  74701. }
  74702. // Merge meshes
  74703. BABYLON.Mesh.MergeMeshes(currentPool);
  74704. }
  74705. if (updateSelectionTree != undefined) {
  74706. if (updateSelectionTree) {
  74707. scene.createOrUpdateSelectionOctree();
  74708. }
  74709. }
  74710. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  74711. scene.createOrUpdateSelectionOctree();
  74712. }
  74713. return true;
  74714. };
  74715. return _this;
  74716. }
  74717. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  74718. get: function () {
  74719. return MergeMeshesOptimization._UpdateSelectionTree;
  74720. },
  74721. set: function (value) {
  74722. MergeMeshesOptimization._UpdateSelectionTree = value;
  74723. },
  74724. enumerable: true,
  74725. configurable: true
  74726. });
  74727. MergeMeshesOptimization._UpdateSelectionTree = false;
  74728. return MergeMeshesOptimization;
  74729. }(SceneOptimization));
  74730. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  74731. // Options
  74732. var SceneOptimizerOptions = /** @class */ (function () {
  74733. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  74734. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  74735. if (trackerDuration === void 0) { trackerDuration = 2000; }
  74736. this.targetFrameRate = targetFrameRate;
  74737. this.trackerDuration = trackerDuration;
  74738. this.optimizations = new Array();
  74739. }
  74740. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  74741. var result = new SceneOptimizerOptions(targetFrameRate);
  74742. var priority = 0;
  74743. result.optimizations.push(new MergeMeshesOptimization(priority));
  74744. result.optimizations.push(new ShadowsOptimization(priority));
  74745. result.optimizations.push(new LensFlaresOptimization(priority));
  74746. // Next priority
  74747. priority++;
  74748. result.optimizations.push(new PostProcessesOptimization(priority));
  74749. result.optimizations.push(new ParticlesOptimization(priority));
  74750. // Next priority
  74751. priority++;
  74752. result.optimizations.push(new TextureOptimization(priority, 1024));
  74753. return result;
  74754. };
  74755. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  74756. var result = new SceneOptimizerOptions(targetFrameRate);
  74757. var priority = 0;
  74758. result.optimizations.push(new MergeMeshesOptimization(priority));
  74759. result.optimizations.push(new ShadowsOptimization(priority));
  74760. result.optimizations.push(new LensFlaresOptimization(priority));
  74761. // Next priority
  74762. priority++;
  74763. result.optimizations.push(new PostProcessesOptimization(priority));
  74764. result.optimizations.push(new ParticlesOptimization(priority));
  74765. // Next priority
  74766. priority++;
  74767. result.optimizations.push(new TextureOptimization(priority, 512));
  74768. // Next priority
  74769. priority++;
  74770. result.optimizations.push(new RenderTargetsOptimization(priority));
  74771. // Next priority
  74772. priority++;
  74773. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  74774. return result;
  74775. };
  74776. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  74777. var result = new SceneOptimizerOptions(targetFrameRate);
  74778. var priority = 0;
  74779. result.optimizations.push(new MergeMeshesOptimization(priority));
  74780. result.optimizations.push(new ShadowsOptimization(priority));
  74781. result.optimizations.push(new LensFlaresOptimization(priority));
  74782. // Next priority
  74783. priority++;
  74784. result.optimizations.push(new PostProcessesOptimization(priority));
  74785. result.optimizations.push(new ParticlesOptimization(priority));
  74786. // Next priority
  74787. priority++;
  74788. result.optimizations.push(new TextureOptimization(priority, 256));
  74789. // Next priority
  74790. priority++;
  74791. result.optimizations.push(new RenderTargetsOptimization(priority));
  74792. // Next priority
  74793. priority++;
  74794. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  74795. return result;
  74796. };
  74797. return SceneOptimizerOptions;
  74798. }());
  74799. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  74800. // Scene optimizer tool
  74801. var SceneOptimizer = /** @class */ (function () {
  74802. function SceneOptimizer() {
  74803. }
  74804. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  74805. // TODO: add an epsilon
  74806. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  74807. if (onSuccess) {
  74808. onSuccess();
  74809. }
  74810. return;
  74811. }
  74812. // Apply current level of optimizations
  74813. var allDone = true;
  74814. var noOptimizationApplied = true;
  74815. for (var index = 0; index < options.optimizations.length; index++) {
  74816. var optimization = options.optimizations[index];
  74817. if (optimization.priority === currentPriorityLevel) {
  74818. noOptimizationApplied = false;
  74819. allDone = allDone && optimization.apply(scene);
  74820. }
  74821. }
  74822. // If no optimization was applied, this is a failure :(
  74823. if (noOptimizationApplied) {
  74824. if (onFailure) {
  74825. onFailure();
  74826. }
  74827. return;
  74828. }
  74829. // If all optimizations were done, move to next level
  74830. if (allDone) {
  74831. currentPriorityLevel++;
  74832. }
  74833. // Let's the system running for a specific amount of time before checking FPS
  74834. scene.executeWhenReady(function () {
  74835. setTimeout(function () {
  74836. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  74837. }, options.trackerDuration);
  74838. });
  74839. };
  74840. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  74841. if (!options) {
  74842. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  74843. }
  74844. // Let's the system running for a specific amount of time before checking FPS
  74845. scene.executeWhenReady(function () {
  74846. setTimeout(function () {
  74847. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  74848. }, options.trackerDuration);
  74849. });
  74850. };
  74851. return SceneOptimizer;
  74852. }());
  74853. BABYLON.SceneOptimizer = SceneOptimizer;
  74854. })(BABYLON || (BABYLON = {}));
  74855. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  74856. var BABYLON;
  74857. (function (BABYLON) {
  74858. var OutlineRenderer = /** @class */ (function () {
  74859. function OutlineRenderer(scene) {
  74860. this.zOffset = 1;
  74861. this._scene = scene;
  74862. }
  74863. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  74864. var _this = this;
  74865. if (useOverlay === void 0) { useOverlay = false; }
  74866. var scene = this._scene;
  74867. var engine = this._scene.getEngine();
  74868. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  74869. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  74870. return;
  74871. }
  74872. var mesh = subMesh.getRenderingMesh();
  74873. var material = subMesh.getMaterial();
  74874. if (!material || !scene.activeCamera) {
  74875. return;
  74876. }
  74877. engine.enableEffect(this._effect);
  74878. // Logarithmic depth
  74879. if (material.useLogarithmicDepth) {
  74880. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  74881. }
  74882. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  74883. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  74884. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  74885. // Bones
  74886. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  74887. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  74888. }
  74889. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  74890. // Alpha test
  74891. if (material && material.needAlphaTesting()) {
  74892. var alphaTexture = material.getAlphaTestTexture();
  74893. if (alphaTexture) {
  74894. this._effect.setTexture("diffuseSampler", alphaTexture);
  74895. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  74896. }
  74897. }
  74898. engine.setZOffset(-this.zOffset);
  74899. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  74900. engine.setZOffset(0);
  74901. };
  74902. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  74903. var defines = [];
  74904. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  74905. var mesh = subMesh.getMesh();
  74906. var material = subMesh.getMaterial();
  74907. if (material) {
  74908. // Alpha test
  74909. if (material.needAlphaTesting()) {
  74910. defines.push("#define ALPHATEST");
  74911. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  74912. attribs.push(BABYLON.VertexBuffer.UVKind);
  74913. defines.push("#define UV1");
  74914. }
  74915. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  74916. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  74917. defines.push("#define UV2");
  74918. }
  74919. }
  74920. //Logarithmic depth
  74921. if (material.useLogarithmicDepth) {
  74922. defines.push("#define LOGARITHMICDEPTH");
  74923. }
  74924. }
  74925. // Bones
  74926. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  74927. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  74928. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  74929. if (mesh.numBoneInfluencers > 4) {
  74930. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  74931. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  74932. }
  74933. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  74934. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  74935. }
  74936. else {
  74937. defines.push("#define NUM_BONE_INFLUENCERS 0");
  74938. }
  74939. // Instances
  74940. if (useInstances) {
  74941. defines.push("#define INSTANCES");
  74942. attribs.push("world0");
  74943. attribs.push("world1");
  74944. attribs.push("world2");
  74945. attribs.push("world3");
  74946. }
  74947. // Get correct effect
  74948. var join = defines.join("\n");
  74949. if (this._cachedDefines !== join) {
  74950. this._cachedDefines = join;
  74951. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  74952. }
  74953. return this._effect.isReady();
  74954. };
  74955. return OutlineRenderer;
  74956. }());
  74957. BABYLON.OutlineRenderer = OutlineRenderer;
  74958. })(BABYLON || (BABYLON = {}));
  74959. //# sourceMappingURL=babylon.outlineRenderer.js.map
  74960. var BABYLON;
  74961. (function (BABYLON) {
  74962. var FaceAdjacencies = /** @class */ (function () {
  74963. function FaceAdjacencies() {
  74964. this.edges = new Array();
  74965. this.edgesConnectedCount = 0;
  74966. }
  74967. return FaceAdjacencies;
  74968. }());
  74969. var EdgesRenderer = /** @class */ (function () {
  74970. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  74971. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  74972. if (epsilon === void 0) { epsilon = 0.95; }
  74973. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  74974. this.edgesWidthScalerForOrthographic = 1000.0;
  74975. this.edgesWidthScalerForPerspective = 50.0;
  74976. this._linesPositions = new Array();
  74977. this._linesNormals = new Array();
  74978. this._linesIndices = new Array();
  74979. this._buffers = {};
  74980. this._checkVerticesInsteadOfIndices = false;
  74981. this._source = source;
  74982. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  74983. this._epsilon = epsilon;
  74984. this._prepareRessources();
  74985. this._generateEdgesLines();
  74986. }
  74987. EdgesRenderer.prototype._prepareRessources = function () {
  74988. if (this._lineShader) {
  74989. return;
  74990. }
  74991. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  74992. attributes: ["position", "normal"],
  74993. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  74994. });
  74995. this._lineShader.disableDepthWrite = true;
  74996. this._lineShader.backFaceCulling = false;
  74997. };
  74998. EdgesRenderer.prototype._rebuild = function () {
  74999. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  75000. if (buffer) {
  75001. buffer._rebuild();
  75002. }
  75003. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  75004. if (buffer) {
  75005. buffer._rebuild();
  75006. }
  75007. var scene = this._source.getScene();
  75008. var engine = scene.getEngine();
  75009. this._ib = engine.createIndexBuffer(this._linesIndices);
  75010. };
  75011. EdgesRenderer.prototype.dispose = function () {
  75012. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  75013. if (buffer) {
  75014. buffer.dispose();
  75015. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  75016. }
  75017. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  75018. if (buffer) {
  75019. buffer.dispose();
  75020. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  75021. }
  75022. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  75023. this._lineShader.dispose();
  75024. };
  75025. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  75026. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  75027. return 0;
  75028. }
  75029. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  75030. return 1;
  75031. }
  75032. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  75033. return 2;
  75034. }
  75035. return -1;
  75036. };
  75037. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  75038. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  75039. return 0;
  75040. }
  75041. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  75042. return 1;
  75043. }
  75044. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  75045. return 2;
  75046. }
  75047. return -1;
  75048. };
  75049. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  75050. var needToCreateLine;
  75051. if (edge === undefined) {
  75052. needToCreateLine = true;
  75053. }
  75054. else {
  75055. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  75056. needToCreateLine = dotProduct < this._epsilon;
  75057. }
  75058. if (needToCreateLine) {
  75059. var offset = this._linesPositions.length / 3;
  75060. var normal = p0.subtract(p1);
  75061. normal.normalize();
  75062. // Positions
  75063. this._linesPositions.push(p0.x);
  75064. this._linesPositions.push(p0.y);
  75065. this._linesPositions.push(p0.z);
  75066. this._linesPositions.push(p0.x);
  75067. this._linesPositions.push(p0.y);
  75068. this._linesPositions.push(p0.z);
  75069. this._linesPositions.push(p1.x);
  75070. this._linesPositions.push(p1.y);
  75071. this._linesPositions.push(p1.z);
  75072. this._linesPositions.push(p1.x);
  75073. this._linesPositions.push(p1.y);
  75074. this._linesPositions.push(p1.z);
  75075. // Normals
  75076. this._linesNormals.push(p1.x);
  75077. this._linesNormals.push(p1.y);
  75078. this._linesNormals.push(p1.z);
  75079. this._linesNormals.push(-1);
  75080. this._linesNormals.push(p1.x);
  75081. this._linesNormals.push(p1.y);
  75082. this._linesNormals.push(p1.z);
  75083. this._linesNormals.push(1);
  75084. this._linesNormals.push(p0.x);
  75085. this._linesNormals.push(p0.y);
  75086. this._linesNormals.push(p0.z);
  75087. this._linesNormals.push(-1);
  75088. this._linesNormals.push(p0.x);
  75089. this._linesNormals.push(p0.y);
  75090. this._linesNormals.push(p0.z);
  75091. this._linesNormals.push(1);
  75092. // Indices
  75093. this._linesIndices.push(offset);
  75094. this._linesIndices.push(offset + 1);
  75095. this._linesIndices.push(offset + 2);
  75096. this._linesIndices.push(offset);
  75097. this._linesIndices.push(offset + 2);
  75098. this._linesIndices.push(offset + 3);
  75099. }
  75100. };
  75101. EdgesRenderer.prototype._generateEdgesLines = function () {
  75102. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  75103. var indices = this._source.getIndices();
  75104. if (!indices || !positions) {
  75105. return;
  75106. }
  75107. // First let's find adjacencies
  75108. var adjacencies = new Array();
  75109. var faceNormals = new Array();
  75110. var index;
  75111. var faceAdjacencies;
  75112. // Prepare faces
  75113. for (index = 0; index < indices.length; index += 3) {
  75114. faceAdjacencies = new FaceAdjacencies();
  75115. var p0Index = indices[index];
  75116. var p1Index = indices[index + 1];
  75117. var p2Index = indices[index + 2];
  75118. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  75119. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  75120. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  75121. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  75122. faceNormal.normalize();
  75123. faceNormals.push(faceNormal);
  75124. adjacencies.push(faceAdjacencies);
  75125. }
  75126. // Scan
  75127. for (index = 0; index < adjacencies.length; index++) {
  75128. faceAdjacencies = adjacencies[index];
  75129. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  75130. var otherFaceAdjacencies = adjacencies[otherIndex];
  75131. if (faceAdjacencies.edgesConnectedCount === 3) {
  75132. break;
  75133. }
  75134. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  75135. continue;
  75136. }
  75137. var otherP0 = indices[otherIndex * 3];
  75138. var otherP1 = indices[otherIndex * 3 + 1];
  75139. var otherP2 = indices[otherIndex * 3 + 2];
  75140. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  75141. var otherEdgeIndex = 0;
  75142. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  75143. continue;
  75144. }
  75145. switch (edgeIndex) {
  75146. case 0:
  75147. if (this._checkVerticesInsteadOfIndices) {
  75148. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  75149. }
  75150. else {
  75151. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  75152. }
  75153. break;
  75154. case 1:
  75155. if (this._checkVerticesInsteadOfIndices) {
  75156. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  75157. }
  75158. else {
  75159. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  75160. }
  75161. break;
  75162. case 2:
  75163. if (this._checkVerticesInsteadOfIndices) {
  75164. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  75165. }
  75166. else {
  75167. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  75168. }
  75169. break;
  75170. }
  75171. if (otherEdgeIndex === -1) {
  75172. continue;
  75173. }
  75174. faceAdjacencies.edges[edgeIndex] = otherIndex;
  75175. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  75176. faceAdjacencies.edgesConnectedCount++;
  75177. otherFaceAdjacencies.edgesConnectedCount++;
  75178. if (faceAdjacencies.edgesConnectedCount === 3) {
  75179. break;
  75180. }
  75181. }
  75182. }
  75183. }
  75184. // Create lines
  75185. for (index = 0; index < adjacencies.length; index++) {
  75186. // 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
  75187. var current = adjacencies[index];
  75188. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  75189. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  75190. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  75191. }
  75192. // Merge into a single mesh
  75193. var engine = this._source.getScene().getEngine();
  75194. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  75195. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  75196. this._ib = engine.createIndexBuffer(this._linesIndices);
  75197. this._indicesCount = this._linesIndices.length;
  75198. };
  75199. EdgesRenderer.prototype.render = function () {
  75200. var scene = this._source.getScene();
  75201. if (!this._lineShader.isReady() || !scene.activeCamera) {
  75202. return;
  75203. }
  75204. var engine = scene.getEngine();
  75205. this._lineShader._preBind();
  75206. // VBOs
  75207. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  75208. scene.resetCachedMaterial();
  75209. this._lineShader.setColor4("color", this._source.edgesColor);
  75210. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  75211. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  75212. }
  75213. else {
  75214. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  75215. }
  75216. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  75217. this._lineShader.bind(this._source.getWorldMatrix());
  75218. // Draw order
  75219. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  75220. this._lineShader.unbind();
  75221. engine.setDepthWrite(true);
  75222. };
  75223. return EdgesRenderer;
  75224. }());
  75225. BABYLON.EdgesRenderer = EdgesRenderer;
  75226. })(BABYLON || (BABYLON = {}));
  75227. //# sourceMappingURL=babylon.edgesRenderer.js.map
  75228. var BABYLON;
  75229. (function (BABYLON) {
  75230. /**
  75231. * Special Glow Blur post process only blurring the alpha channel
  75232. * It enforces keeping the most luminous color in the color channel.
  75233. */
  75234. var GlowBlurPostProcess = /** @class */ (function (_super) {
  75235. __extends(GlowBlurPostProcess, _super);
  75236. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  75237. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75238. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  75239. _this.direction = direction;
  75240. _this.kernel = kernel;
  75241. _this.onApplyObservable.add(function (effect) {
  75242. effect.setFloat2("screenSize", _this.width, _this.height);
  75243. effect.setVector2("direction", _this.direction);
  75244. effect.setFloat("blurWidth", _this.kernel);
  75245. });
  75246. return _this;
  75247. }
  75248. return GlowBlurPostProcess;
  75249. }(BABYLON.PostProcess));
  75250. /**
  75251. * The highlight layer Helps adding a glow effect around a mesh.
  75252. *
  75253. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  75254. * glowy meshes to your scene.
  75255. *
  75256. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  75257. */
  75258. var HighlightLayer = /** @class */ (function () {
  75259. /**
  75260. * Instantiates a new highlight Layer and references it to the scene..
  75261. * @param name The name of the layer
  75262. * @param scene The scene to use the layer in
  75263. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  75264. */
  75265. function HighlightLayer(name, scene, options) {
  75266. this.name = name;
  75267. this._vertexBuffers = {};
  75268. this._mainTextureDesiredSize = { width: 0, height: 0 };
  75269. this._meshes = {};
  75270. this._maxSize = 0;
  75271. this._shouldRender = false;
  75272. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  75273. this._excludedMeshes = {};
  75274. /**
  75275. * Specifies whether or not the inner glow is ACTIVE in the layer.
  75276. */
  75277. this.innerGlow = true;
  75278. /**
  75279. * Specifies whether or not the outer glow is ACTIVE in the layer.
  75280. */
  75281. this.outerGlow = true;
  75282. /**
  75283. * Specifies wether the highlight layer is enabled or not.
  75284. */
  75285. this.isEnabled = true;
  75286. /**
  75287. * An event triggered when the highlight layer has been disposed.
  75288. * @type {BABYLON.Observable}
  75289. */
  75290. this.onDisposeObservable = new BABYLON.Observable();
  75291. /**
  75292. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  75293. * @type {BABYLON.Observable}
  75294. */
  75295. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  75296. /**
  75297. * An event triggered when the highlight layer is being blurred.
  75298. * @type {BABYLON.Observable}
  75299. */
  75300. this.onBeforeBlurObservable = new BABYLON.Observable();
  75301. /**
  75302. * An event triggered when the highlight layer has been blurred.
  75303. * @type {BABYLON.Observable}
  75304. */
  75305. this.onAfterBlurObservable = new BABYLON.Observable();
  75306. /**
  75307. * An event triggered when the glowing blurred texture is being merged in the scene.
  75308. * @type {BABYLON.Observable}
  75309. */
  75310. this.onBeforeComposeObservable = new BABYLON.Observable();
  75311. /**
  75312. * An event triggered when the glowing blurred texture has been merged in the scene.
  75313. * @type {BABYLON.Observable}
  75314. */
  75315. this.onAfterComposeObservable = new BABYLON.Observable();
  75316. /**
  75317. * An event triggered when the highlight layer changes its size.
  75318. * @type {BABYLON.Observable}
  75319. */
  75320. this.onSizeChangedObservable = new BABYLON.Observable();
  75321. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  75322. var engine = scene.getEngine();
  75323. this._engine = engine;
  75324. this._maxSize = this._engine.getCaps().maxTextureSize;
  75325. this._scene.highlightLayers.push(this);
  75326. // Warn on stencil.
  75327. if (!this._engine.isStencilEnable) {
  75328. 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 }");
  75329. }
  75330. // Adapt options
  75331. this._options = options || {
  75332. mainTextureRatio: 0.5,
  75333. blurTextureSizeRatio: 0.5,
  75334. blurHorizontalSize: 1.0,
  75335. blurVerticalSize: 1.0,
  75336. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  75337. camera: null
  75338. };
  75339. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  75340. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  75341. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  75342. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  75343. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  75344. // VBO
  75345. var vertices = [];
  75346. vertices.push(1, 1);
  75347. vertices.push(-1, 1);
  75348. vertices.push(-1, -1);
  75349. vertices.push(1, -1);
  75350. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  75351. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  75352. this._createIndexBuffer();
  75353. // Effect
  75354. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  75355. // Render target
  75356. this.setMainTextureSize();
  75357. // Create Textures and post processes
  75358. this.createTextureAndPostProcesses();
  75359. }
  75360. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  75361. /**
  75362. * Gets the horizontal size of the blur.
  75363. */
  75364. get: function () {
  75365. return this._horizontalBlurPostprocess.kernel;
  75366. },
  75367. /**
  75368. * Specifies the horizontal size of the blur.
  75369. */
  75370. set: function (value) {
  75371. this._horizontalBlurPostprocess.kernel = value;
  75372. },
  75373. enumerable: true,
  75374. configurable: true
  75375. });
  75376. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  75377. /**
  75378. * Gets the vertical size of the blur.
  75379. */
  75380. get: function () {
  75381. return this._verticalBlurPostprocess.kernel;
  75382. },
  75383. /**
  75384. * Specifies the vertical size of the blur.
  75385. */
  75386. set: function (value) {
  75387. this._verticalBlurPostprocess.kernel = value;
  75388. },
  75389. enumerable: true,
  75390. configurable: true
  75391. });
  75392. Object.defineProperty(HighlightLayer.prototype, "camera", {
  75393. /**
  75394. * Gets the camera attached to the layer.
  75395. */
  75396. get: function () {
  75397. return this._options.camera;
  75398. },
  75399. enumerable: true,
  75400. configurable: true
  75401. });
  75402. HighlightLayer.prototype._createIndexBuffer = function () {
  75403. var engine = this._scene.getEngine();
  75404. // Indices
  75405. var indices = [];
  75406. indices.push(0);
  75407. indices.push(1);
  75408. indices.push(2);
  75409. indices.push(0);
  75410. indices.push(2);
  75411. indices.push(3);
  75412. this._indexBuffer = engine.createIndexBuffer(indices);
  75413. };
  75414. HighlightLayer.prototype._rebuild = function () {
  75415. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75416. if (vb) {
  75417. vb._rebuild();
  75418. }
  75419. this._createIndexBuffer();
  75420. };
  75421. /**
  75422. * Creates the render target textures and post processes used in the highlight layer.
  75423. */
  75424. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  75425. var _this = this;
  75426. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  75427. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  75428. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  75429. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  75430. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  75431. width: this._mainTextureDesiredSize.width,
  75432. height: this._mainTextureDesiredSize.height
  75433. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  75434. this._mainTexture.activeCamera = this._options.camera;
  75435. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75436. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75437. this._mainTexture.anisotropicFilteringLevel = 1;
  75438. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  75439. this._mainTexture.renderParticles = false;
  75440. this._mainTexture.renderList = null;
  75441. this._mainTexture.ignoreCameraViewport = true;
  75442. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  75443. width: blurTextureWidth,
  75444. height: blurTextureHeight
  75445. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  75446. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75447. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75448. this._blurTexture.anisotropicFilteringLevel = 16;
  75449. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  75450. this._blurTexture.renderParticles = false;
  75451. this._blurTexture.ignoreCameraViewport = true;
  75452. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  75453. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  75454. effect.setTexture("textureSampler", _this._mainTexture);
  75455. });
  75456. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  75457. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  75458. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  75459. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  75460. });
  75461. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  75462. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  75463. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  75464. });
  75465. }
  75466. else {
  75467. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  75468. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  75469. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  75470. });
  75471. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  75472. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  75473. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  75474. });
  75475. }
  75476. this._mainTexture.onAfterUnbindObservable.add(function () {
  75477. _this.onBeforeBlurObservable.notifyObservers(_this);
  75478. var internalTexture = _this._blurTexture.getInternalTexture();
  75479. if (internalTexture) {
  75480. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  75481. }
  75482. _this.onAfterBlurObservable.notifyObservers(_this);
  75483. });
  75484. // Custom render function
  75485. var renderSubMesh = function (subMesh) {
  75486. if (!_this._meshes) {
  75487. return;
  75488. }
  75489. var material = subMesh.getMaterial();
  75490. var mesh = subMesh.getRenderingMesh();
  75491. var scene = _this._scene;
  75492. var engine = scene.getEngine();
  75493. if (!material) {
  75494. return;
  75495. }
  75496. // Do not block in blend mode.
  75497. if (material.needAlphaBlendingForMesh(mesh)) {
  75498. return;
  75499. }
  75500. // Culling
  75501. engine.setState(material.backFaceCulling);
  75502. // Managing instances
  75503. var batch = mesh._getInstancesRenderList(subMesh._id);
  75504. if (batch.mustReturn) {
  75505. return;
  75506. }
  75507. // Excluded Mesh
  75508. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  75509. return;
  75510. }
  75511. ;
  75512. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  75513. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  75514. var emissiveTexture = null;
  75515. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  75516. emissiveTexture = material.emissiveTexture;
  75517. }
  75518. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  75519. engine.enableEffect(_this._glowMapGenerationEffect);
  75520. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  75521. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  75522. if (highlightLayerMesh) {
  75523. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  75524. }
  75525. else {
  75526. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  75527. }
  75528. // Alpha test
  75529. if (material && material.needAlphaTesting()) {
  75530. var alphaTexture = material.getAlphaTestTexture();
  75531. if (alphaTexture) {
  75532. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  75533. var textureMatrix = alphaTexture.getTextureMatrix();
  75534. if (textureMatrix) {
  75535. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  75536. }
  75537. }
  75538. }
  75539. // Glow emissive only
  75540. if (emissiveTexture) {
  75541. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  75542. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  75543. }
  75544. // Bones
  75545. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  75546. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  75547. }
  75548. // Draw
  75549. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  75550. }
  75551. else {
  75552. // Need to reset refresh rate of the shadowMap
  75553. _this._mainTexture.resetRefreshCounter();
  75554. }
  75555. };
  75556. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  75557. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  75558. var index;
  75559. var engine = _this._scene.getEngine();
  75560. if (depthOnlySubMeshes.length) {
  75561. engine.setColorWrite(false);
  75562. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  75563. renderSubMesh(depthOnlySubMeshes.data[index]);
  75564. }
  75565. engine.setColorWrite(true);
  75566. }
  75567. for (index = 0; index < opaqueSubMeshes.length; index++) {
  75568. renderSubMesh(opaqueSubMeshes.data[index]);
  75569. }
  75570. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  75571. renderSubMesh(alphaTestSubMeshes.data[index]);
  75572. }
  75573. for (index = 0; index < transparentSubMeshes.length; index++) {
  75574. renderSubMesh(transparentSubMeshes.data[index]);
  75575. }
  75576. };
  75577. this._mainTexture.onClearObservable.add(function (engine) {
  75578. engine.clear(HighlightLayer.neutralColor, true, true, true);
  75579. });
  75580. };
  75581. /**
  75582. * Checks for the readiness of the element composing the layer.
  75583. * @param subMesh the mesh to check for
  75584. * @param useInstances specify wether or not to use instances to render the mesh
  75585. * @param emissiveTexture the associated emissive texture used to generate the glow
  75586. * @return true if ready otherwise, false
  75587. */
  75588. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  75589. var material = subMesh.getMaterial();
  75590. if (!material) {
  75591. return false;
  75592. }
  75593. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  75594. return false;
  75595. }
  75596. var defines = [];
  75597. var attribs = [BABYLON.VertexBuffer.PositionKind];
  75598. var mesh = subMesh.getMesh();
  75599. var uv1 = false;
  75600. var uv2 = false;
  75601. // Alpha test
  75602. if (material && material.needAlphaTesting()) {
  75603. var alphaTexture = material.getAlphaTestTexture();
  75604. if (alphaTexture) {
  75605. defines.push("#define ALPHATEST");
  75606. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  75607. alphaTexture.coordinatesIndex === 1) {
  75608. defines.push("#define DIFFUSEUV2");
  75609. uv2 = true;
  75610. }
  75611. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75612. defines.push("#define DIFFUSEUV1");
  75613. uv1 = true;
  75614. }
  75615. }
  75616. }
  75617. // Emissive
  75618. if (emissiveTexture) {
  75619. defines.push("#define EMISSIVE");
  75620. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  75621. emissiveTexture.coordinatesIndex === 1) {
  75622. defines.push("#define EMISSIVEUV2");
  75623. uv2 = true;
  75624. }
  75625. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75626. defines.push("#define EMISSIVEUV1");
  75627. uv1 = true;
  75628. }
  75629. }
  75630. if (uv1) {
  75631. attribs.push(BABYLON.VertexBuffer.UVKind);
  75632. defines.push("#define UV1");
  75633. }
  75634. if (uv2) {
  75635. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75636. defines.push("#define UV2");
  75637. }
  75638. // Bones
  75639. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75640. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75641. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75642. if (mesh.numBoneInfluencers > 4) {
  75643. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  75644. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  75645. }
  75646. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75647. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  75648. }
  75649. else {
  75650. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75651. }
  75652. // Instances
  75653. if (useInstances) {
  75654. defines.push("#define INSTANCES");
  75655. attribs.push("world0");
  75656. attribs.push("world1");
  75657. attribs.push("world2");
  75658. attribs.push("world3");
  75659. }
  75660. // Get correct effect
  75661. var join = defines.join("\n");
  75662. if (this._cachedDefines !== join) {
  75663. this._cachedDefines = join;
  75664. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  75665. }
  75666. return this._glowMapGenerationEffect.isReady();
  75667. };
  75668. /**
  75669. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  75670. */
  75671. HighlightLayer.prototype.render = function () {
  75672. var currentEffect = this._glowMapMergeEffect;
  75673. // Check
  75674. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  75675. return;
  75676. var engine = this._scene.getEngine();
  75677. this.onBeforeComposeObservable.notifyObservers(this);
  75678. // Render
  75679. engine.enableEffect(currentEffect);
  75680. engine.setState(false);
  75681. // Cache
  75682. var previousStencilBuffer = engine.getStencilBuffer();
  75683. var previousStencilFunction = engine.getStencilFunction();
  75684. var previousStencilMask = engine.getStencilMask();
  75685. var previousStencilOperationPass = engine.getStencilOperationPass();
  75686. var previousStencilOperationFail = engine.getStencilOperationFail();
  75687. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  75688. var previousAlphaMode = engine.getAlphaMode();
  75689. // Texture
  75690. currentEffect.setTexture("textureSampler", this._blurTexture);
  75691. // VBOs
  75692. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  75693. // Stencil operations
  75694. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  75695. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  75696. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  75697. // Draw order
  75698. engine.setAlphaMode(this._options.alphaBlendingMode);
  75699. engine.setStencilMask(0x00);
  75700. engine.setStencilBuffer(true);
  75701. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  75702. if (this.outerGlow) {
  75703. currentEffect.setFloat("offset", 0);
  75704. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  75705. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  75706. }
  75707. if (this.innerGlow) {
  75708. currentEffect.setFloat("offset", 1);
  75709. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  75710. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  75711. }
  75712. // Restore Cache
  75713. engine.setStencilFunction(previousStencilFunction);
  75714. engine.setStencilMask(previousStencilMask);
  75715. engine.setAlphaMode(previousAlphaMode);
  75716. engine.setStencilBuffer(previousStencilBuffer);
  75717. engine.setStencilOperationPass(previousStencilOperationPass);
  75718. engine.setStencilOperationFail(previousStencilOperationFail);
  75719. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  75720. engine._stencilState.reset();
  75721. this.onAfterComposeObservable.notifyObservers(this);
  75722. // Handle size changes.
  75723. var size = this._mainTexture.getSize();
  75724. this.setMainTextureSize();
  75725. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  75726. // Recreate RTT and post processes on size change.
  75727. this.onSizeChangedObservable.notifyObservers(this);
  75728. this.disposeTextureAndPostProcesses();
  75729. this.createTextureAndPostProcesses();
  75730. }
  75731. };
  75732. /**
  75733. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  75734. * @param mesh The mesh to exclude from the highlight layer
  75735. */
  75736. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  75737. if (!this._excludedMeshes) {
  75738. return;
  75739. }
  75740. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  75741. if (!meshExcluded) {
  75742. this._excludedMeshes[mesh.uniqueId] = {
  75743. mesh: mesh,
  75744. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  75745. mesh.getEngine().setStencilBuffer(false);
  75746. }),
  75747. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  75748. mesh.getEngine().setStencilBuffer(true);
  75749. }),
  75750. };
  75751. }
  75752. };
  75753. /**
  75754. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  75755. * @param mesh The mesh to highlight
  75756. */
  75757. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  75758. if (!this._excludedMeshes) {
  75759. return;
  75760. }
  75761. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  75762. if (meshExcluded) {
  75763. if (meshExcluded.beforeRender) {
  75764. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  75765. }
  75766. if (meshExcluded.afterRender) {
  75767. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  75768. }
  75769. }
  75770. this._excludedMeshes[mesh.uniqueId] = null;
  75771. };
  75772. /**
  75773. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  75774. * @param mesh The mesh to highlight
  75775. * @param color The color of the highlight
  75776. * @param glowEmissiveOnly Extract the glow from the emissive texture
  75777. */
  75778. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  75779. var _this = this;
  75780. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  75781. if (!this._meshes) {
  75782. return;
  75783. }
  75784. var meshHighlight = this._meshes[mesh.uniqueId];
  75785. if (meshHighlight) {
  75786. meshHighlight.color = color;
  75787. }
  75788. else {
  75789. this._meshes[mesh.uniqueId] = {
  75790. mesh: mesh,
  75791. color: color,
  75792. // Lambda required for capture due to Observable this context
  75793. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  75794. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  75795. _this.defaultStencilReference(mesh);
  75796. }
  75797. else {
  75798. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  75799. }
  75800. }),
  75801. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  75802. glowEmissiveOnly: glowEmissiveOnly
  75803. };
  75804. }
  75805. this._shouldRender = true;
  75806. };
  75807. /**
  75808. * Remove a mesh from the highlight layer in order to make it stop glowing.
  75809. * @param mesh The mesh to highlight
  75810. */
  75811. HighlightLayer.prototype.removeMesh = function (mesh) {
  75812. if (!this._meshes) {
  75813. return;
  75814. }
  75815. var meshHighlight = this._meshes[mesh.uniqueId];
  75816. if (meshHighlight) {
  75817. if (meshHighlight.observerHighlight) {
  75818. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  75819. }
  75820. if (meshHighlight.observerDefault) {
  75821. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  75822. }
  75823. delete this._meshes[mesh.uniqueId];
  75824. }
  75825. this._shouldRender = false;
  75826. for (var meshHighlightToCheck in this._meshes) {
  75827. if (this._meshes[meshHighlightToCheck]) {
  75828. this._shouldRender = true;
  75829. break;
  75830. }
  75831. }
  75832. };
  75833. /**
  75834. * Returns true if the layer contains information to display, otherwise false.
  75835. */
  75836. HighlightLayer.prototype.shouldRender = function () {
  75837. return this.isEnabled && this._shouldRender;
  75838. };
  75839. /**
  75840. * Sets the main texture desired size which is the closest power of two
  75841. * of the engine canvas size.
  75842. */
  75843. HighlightLayer.prototype.setMainTextureSize = function () {
  75844. if (this._options.mainTextureFixedSize) {
  75845. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  75846. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  75847. }
  75848. else {
  75849. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  75850. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  75851. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  75852. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  75853. }
  75854. };
  75855. /**
  75856. * Force the stencil to the normal expected value for none glowing parts
  75857. */
  75858. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  75859. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  75860. };
  75861. /**
  75862. * Dispose only the render target textures and post process.
  75863. */
  75864. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  75865. this._blurTexture.dispose();
  75866. this._mainTexture.dispose();
  75867. this._downSamplePostprocess.dispose();
  75868. this._horizontalBlurPostprocess.dispose();
  75869. this._verticalBlurPostprocess.dispose();
  75870. };
  75871. /**
  75872. * Dispose the highlight layer and free resources.
  75873. */
  75874. HighlightLayer.prototype.dispose = function () {
  75875. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75876. if (vertexBuffer) {
  75877. vertexBuffer.dispose();
  75878. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  75879. }
  75880. if (this._indexBuffer) {
  75881. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  75882. this._indexBuffer = null;
  75883. }
  75884. // Clean textures and post processes
  75885. this.disposeTextureAndPostProcesses();
  75886. if (this._meshes) {
  75887. // Clean mesh references
  75888. for (var id in this._meshes) {
  75889. var meshHighlight = this._meshes[id];
  75890. if (meshHighlight && meshHighlight.mesh) {
  75891. if (meshHighlight.observerHighlight) {
  75892. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  75893. }
  75894. if (meshHighlight.observerDefault) {
  75895. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  75896. }
  75897. }
  75898. }
  75899. this._meshes = null;
  75900. }
  75901. if (this._excludedMeshes) {
  75902. for (var id in this._excludedMeshes) {
  75903. var meshHighlight = this._excludedMeshes[id];
  75904. if (meshHighlight) {
  75905. if (meshHighlight.beforeRender) {
  75906. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  75907. }
  75908. if (meshHighlight.afterRender) {
  75909. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  75910. }
  75911. }
  75912. }
  75913. this._excludedMeshes = null;
  75914. }
  75915. // Remove from scene
  75916. var index = this._scene.highlightLayers.indexOf(this, 0);
  75917. if (index > -1) {
  75918. this._scene.highlightLayers.splice(index, 1);
  75919. }
  75920. // Callback
  75921. this.onDisposeObservable.notifyObservers(this);
  75922. this.onDisposeObservable.clear();
  75923. this.onBeforeRenderMainTextureObservable.clear();
  75924. this.onBeforeBlurObservable.clear();
  75925. this.onBeforeComposeObservable.clear();
  75926. this.onAfterComposeObservable.clear();
  75927. this.onSizeChangedObservable.clear();
  75928. };
  75929. /**
  75930. * The neutral color used during the preparation of the glow effect.
  75931. * This is black by default as the blend operation is a blend operation.
  75932. */
  75933. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  75934. /**
  75935. * Stencil value used for glowing meshes.
  75936. */
  75937. HighlightLayer.glowingMeshStencilReference = 0x02;
  75938. /**
  75939. * Stencil value used for the other meshes in the scene.
  75940. */
  75941. HighlightLayer.normalMeshStencilReference = 0x01;
  75942. return HighlightLayer;
  75943. }());
  75944. BABYLON.HighlightLayer = HighlightLayer;
  75945. })(BABYLON || (BABYLON = {}));
  75946. //# sourceMappingURL=babylon.highlightlayer.js.map
  75947. var BABYLON;
  75948. (function (BABYLON) {
  75949. var AssetTaskState;
  75950. (function (AssetTaskState) {
  75951. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  75952. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  75953. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  75954. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  75955. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  75956. var AbstractAssetTask = /** @class */ (function () {
  75957. function AbstractAssetTask(name) {
  75958. this.name = name;
  75959. this.isCompleted = false;
  75960. this.taskState = AssetTaskState.INIT;
  75961. }
  75962. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  75963. var _this = this;
  75964. this.taskState = AssetTaskState.RUNNING;
  75965. this.runTask(scene, function () {
  75966. _this.onDoneCallback(onSuccess, onError);
  75967. }, function (msg, exception) {
  75968. _this.onErrorCallback(onError, msg, exception);
  75969. });
  75970. };
  75971. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  75972. throw new Error("runTask is not implemented");
  75973. };
  75974. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  75975. this.taskState = AssetTaskState.ERROR;
  75976. this.errorObject = {
  75977. message: message,
  75978. exception: exception
  75979. };
  75980. if (this.onError) {
  75981. this.onError(this, message, exception);
  75982. }
  75983. onError();
  75984. };
  75985. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  75986. try {
  75987. this.taskState = AssetTaskState.DONE;
  75988. this.isCompleted = true;
  75989. if (this.onSuccess) {
  75990. this.onSuccess(this);
  75991. }
  75992. onSuccess();
  75993. }
  75994. catch (e) {
  75995. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  75996. }
  75997. };
  75998. return AbstractAssetTask;
  75999. }());
  76000. BABYLON.AbstractAssetTask = AbstractAssetTask;
  76001. var AssetsProgressEvent = /** @class */ (function () {
  76002. function AssetsProgressEvent(remainingCount, totalCount, task) {
  76003. this.remainingCount = remainingCount;
  76004. this.totalCount = totalCount;
  76005. this.task = task;
  76006. }
  76007. return AssetsProgressEvent;
  76008. }());
  76009. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  76010. var MeshAssetTask = /** @class */ (function (_super) {
  76011. __extends(MeshAssetTask, _super);
  76012. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  76013. var _this = _super.call(this, name) || this;
  76014. _this.name = name;
  76015. _this.meshesNames = meshesNames;
  76016. _this.rootUrl = rootUrl;
  76017. _this.sceneFilename = sceneFilename;
  76018. return _this;
  76019. }
  76020. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  76021. var _this = this;
  76022. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  76023. _this.loadedMeshes = meshes;
  76024. _this.loadedParticleSystems = particleSystems;
  76025. _this.loadedSkeletons = skeletons;
  76026. onSuccess();
  76027. }, null, function (scene, message, exception) {
  76028. onError(message, exception);
  76029. });
  76030. };
  76031. return MeshAssetTask;
  76032. }(AbstractAssetTask));
  76033. BABYLON.MeshAssetTask = MeshAssetTask;
  76034. var TextFileAssetTask = /** @class */ (function (_super) {
  76035. __extends(TextFileAssetTask, _super);
  76036. function TextFileAssetTask(name, url) {
  76037. var _this = _super.call(this, name) || this;
  76038. _this.name = name;
  76039. _this.url = url;
  76040. return _this;
  76041. }
  76042. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  76043. var _this = this;
  76044. BABYLON.Tools.LoadFile(this.url, function (data) {
  76045. _this.text = data;
  76046. onSuccess();
  76047. }, undefined, scene.database, false, function (request, exception) {
  76048. if (request) {
  76049. onError(request.status + " " + request.statusText, exception);
  76050. }
  76051. });
  76052. };
  76053. return TextFileAssetTask;
  76054. }(AbstractAssetTask));
  76055. BABYLON.TextFileAssetTask = TextFileAssetTask;
  76056. var BinaryFileAssetTask = /** @class */ (function (_super) {
  76057. __extends(BinaryFileAssetTask, _super);
  76058. function BinaryFileAssetTask(name, url) {
  76059. var _this = _super.call(this, name) || this;
  76060. _this.name = name;
  76061. _this.url = url;
  76062. return _this;
  76063. }
  76064. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  76065. var _this = this;
  76066. BABYLON.Tools.LoadFile(this.url, function (data) {
  76067. _this.data = data;
  76068. onSuccess();
  76069. }, undefined, scene.database, true, function (request, exception) {
  76070. if (request) {
  76071. onError(request.status + " " + request.statusText, exception);
  76072. }
  76073. });
  76074. };
  76075. return BinaryFileAssetTask;
  76076. }(AbstractAssetTask));
  76077. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  76078. var ImageAssetTask = /** @class */ (function (_super) {
  76079. __extends(ImageAssetTask, _super);
  76080. function ImageAssetTask(name, url) {
  76081. var _this = _super.call(this, name) || this;
  76082. _this.name = name;
  76083. _this.url = url;
  76084. return _this;
  76085. }
  76086. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  76087. var _this = this;
  76088. var img = new Image();
  76089. BABYLON.Tools.SetCorsBehavior(this.url, img);
  76090. img.onload = function () {
  76091. _this.image = img;
  76092. onSuccess();
  76093. };
  76094. img.onerror = function (err) {
  76095. onError("Error loading image", err);
  76096. };
  76097. img.src = this.url;
  76098. };
  76099. return ImageAssetTask;
  76100. }(AbstractAssetTask));
  76101. BABYLON.ImageAssetTask = ImageAssetTask;
  76102. var TextureAssetTask = /** @class */ (function (_super) {
  76103. __extends(TextureAssetTask, _super);
  76104. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  76105. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  76106. var _this = _super.call(this, name) || this;
  76107. _this.name = name;
  76108. _this.url = url;
  76109. _this.noMipmap = noMipmap;
  76110. _this.invertY = invertY;
  76111. _this.samplingMode = samplingMode;
  76112. return _this;
  76113. }
  76114. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  76115. var onload = function () {
  76116. onSuccess();
  76117. };
  76118. var onerror = function (message, exception) {
  76119. onError(message, exception);
  76120. };
  76121. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  76122. };
  76123. return TextureAssetTask;
  76124. }(AbstractAssetTask));
  76125. BABYLON.TextureAssetTask = TextureAssetTask;
  76126. var CubeTextureAssetTask = /** @class */ (function (_super) {
  76127. __extends(CubeTextureAssetTask, _super);
  76128. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  76129. var _this = _super.call(this, name) || this;
  76130. _this.name = name;
  76131. _this.url = url;
  76132. _this.extensions = extensions;
  76133. _this.noMipmap = noMipmap;
  76134. _this.files = files;
  76135. return _this;
  76136. }
  76137. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  76138. var onload = function () {
  76139. onSuccess();
  76140. };
  76141. var onerror = function (message, exception) {
  76142. onError(message, exception);
  76143. };
  76144. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  76145. };
  76146. return CubeTextureAssetTask;
  76147. }(AbstractAssetTask));
  76148. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  76149. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  76150. __extends(HDRCubeTextureAssetTask, _super);
  76151. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  76152. if (noMipmap === void 0) { noMipmap = false; }
  76153. if (generateHarmonics === void 0) { generateHarmonics = true; }
  76154. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  76155. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  76156. var _this = _super.call(this, name) || this;
  76157. _this.name = name;
  76158. _this.url = url;
  76159. _this.size = size;
  76160. _this.noMipmap = noMipmap;
  76161. _this.generateHarmonics = generateHarmonics;
  76162. _this.useInGammaSpace = useInGammaSpace;
  76163. _this.usePMREMGenerator = usePMREMGenerator;
  76164. return _this;
  76165. }
  76166. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  76167. var onload = function () {
  76168. onSuccess();
  76169. };
  76170. var onerror = function (message, exception) {
  76171. onError(message, exception);
  76172. };
  76173. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  76174. };
  76175. return HDRCubeTextureAssetTask;
  76176. }(AbstractAssetTask));
  76177. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  76178. var AssetsManager = /** @class */ (function () {
  76179. function AssetsManager(scene) {
  76180. this.tasks = new Array();
  76181. this.waitingTasksCount = 0;
  76182. //Observables
  76183. this.onTaskSuccessObservable = new BABYLON.Observable();
  76184. this.onTaskErrorObservable = new BABYLON.Observable();
  76185. this.onTasksDoneObservable = new BABYLON.Observable();
  76186. this.onProgressObservable = new BABYLON.Observable();
  76187. this.useDefaultLoadingScreen = true;
  76188. this._scene = scene;
  76189. }
  76190. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  76191. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  76192. this.tasks.push(task);
  76193. return task;
  76194. };
  76195. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  76196. var task = new TextFileAssetTask(taskName, url);
  76197. this.tasks.push(task);
  76198. return task;
  76199. };
  76200. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  76201. var task = new BinaryFileAssetTask(taskName, url);
  76202. this.tasks.push(task);
  76203. return task;
  76204. };
  76205. AssetsManager.prototype.addImageTask = function (taskName, url) {
  76206. var task = new ImageAssetTask(taskName, url);
  76207. this.tasks.push(task);
  76208. return task;
  76209. };
  76210. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  76211. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  76212. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  76213. this.tasks.push(task);
  76214. return task;
  76215. };
  76216. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  76217. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  76218. this.tasks.push(task);
  76219. return task;
  76220. };
  76221. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  76222. if (noMipmap === void 0) { noMipmap = false; }
  76223. if (generateHarmonics === void 0) { generateHarmonics = true; }
  76224. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  76225. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  76226. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  76227. this.tasks.push(task);
  76228. return task;
  76229. };
  76230. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  76231. this.waitingTasksCount--;
  76232. try {
  76233. if (this.onProgress) {
  76234. this.onProgress(this.waitingTasksCount, this.tasks.length, task);
  76235. }
  76236. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this.waitingTasksCount, this.tasks.length, task));
  76237. }
  76238. catch (e) {
  76239. BABYLON.Tools.Error("Error running progress callbacks.");
  76240. console.log(e);
  76241. }
  76242. if (this.waitingTasksCount === 0) {
  76243. try {
  76244. if (this.onFinish) {
  76245. this.onFinish(this.tasks);
  76246. }
  76247. this.onTasksDoneObservable.notifyObservers(this.tasks);
  76248. }
  76249. catch (e) {
  76250. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  76251. console.log(e);
  76252. }
  76253. this._scene.getEngine().hideLoadingUI();
  76254. }
  76255. };
  76256. AssetsManager.prototype._runTask = function (task) {
  76257. var _this = this;
  76258. var done = function () {
  76259. try {
  76260. if (_this.onTaskSuccess) {
  76261. _this.onTaskSuccess(task);
  76262. }
  76263. _this.onTaskSuccessObservable.notifyObservers(task);
  76264. _this._decreaseWaitingTasksCount(task);
  76265. }
  76266. catch (e) {
  76267. error("Error executing task success callbacks", e);
  76268. }
  76269. };
  76270. var error = function (message, exception) {
  76271. task.errorObject = task.errorObject || {
  76272. message: message,
  76273. exception: exception
  76274. };
  76275. if (_this.onTaskError) {
  76276. _this.onTaskError(task);
  76277. }
  76278. _this.onTaskErrorObservable.notifyObservers(task);
  76279. _this._decreaseWaitingTasksCount(task);
  76280. };
  76281. task.run(this._scene, done, error);
  76282. };
  76283. AssetsManager.prototype.reset = function () {
  76284. this.tasks = new Array();
  76285. return this;
  76286. };
  76287. AssetsManager.prototype.load = function () {
  76288. this.waitingTasksCount = this.tasks.length;
  76289. if (this.waitingTasksCount === 0) {
  76290. if (this.onFinish) {
  76291. this.onFinish(this.tasks);
  76292. }
  76293. this.onTasksDoneObservable.notifyObservers(this.tasks);
  76294. return this;
  76295. }
  76296. if (this.useDefaultLoadingScreen) {
  76297. this._scene.getEngine().displayLoadingUI();
  76298. }
  76299. for (var index = 0; index < this.tasks.length; index++) {
  76300. var task = this.tasks[index];
  76301. this._runTask(task);
  76302. }
  76303. return this;
  76304. };
  76305. return AssetsManager;
  76306. }());
  76307. BABYLON.AssetsManager = AssetsManager;
  76308. })(BABYLON || (BABYLON = {}));
  76309. //# sourceMappingURL=babylon.assetsManager.js.map
  76310. var BABYLON;
  76311. (function (BABYLON) {
  76312. var serializedGeometries = [];
  76313. var serializeGeometry = function (geometry, serializationGeometries) {
  76314. if (serializedGeometries[geometry.id]) {
  76315. return;
  76316. }
  76317. if (geometry.doNotSerialize) {
  76318. return;
  76319. }
  76320. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  76321. serializationGeometries.boxes.push(geometry.serialize());
  76322. }
  76323. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  76324. serializationGeometries.spheres.push(geometry.serialize());
  76325. }
  76326. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  76327. serializationGeometries.cylinders.push(geometry.serialize());
  76328. }
  76329. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  76330. serializationGeometries.toruses.push(geometry.serialize());
  76331. }
  76332. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  76333. serializationGeometries.grounds.push(geometry.serialize());
  76334. }
  76335. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  76336. serializationGeometries.planes.push(geometry.serialize());
  76337. }
  76338. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  76339. serializationGeometries.torusKnots.push(geometry.serialize());
  76340. }
  76341. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  76342. throw new Error("Unknown primitive type");
  76343. }
  76344. else {
  76345. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  76346. }
  76347. serializedGeometries[geometry.id] = true;
  76348. };
  76349. var serializeMesh = function (mesh, serializationScene) {
  76350. var serializationObject = {};
  76351. // Geometry
  76352. var geometry = mesh._geometry;
  76353. if (geometry) {
  76354. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  76355. // 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
  76356. serializeGeometry(geometry, serializationScene.geometries);
  76357. }
  76358. }
  76359. // Custom
  76360. if (mesh.serialize) {
  76361. mesh.serialize(serializationObject);
  76362. }
  76363. return serializationObject;
  76364. };
  76365. var finalizeSingleMesh = function (mesh, serializationObject) {
  76366. //only works if the mesh is already loaded
  76367. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  76368. //serialize material
  76369. if (mesh.material) {
  76370. if (mesh.material instanceof BABYLON.StandardMaterial) {
  76371. serializationObject.materials = serializationObject.materials || [];
  76372. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  76373. serializationObject.materials.push(mesh.material.serialize());
  76374. }
  76375. }
  76376. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  76377. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  76378. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  76379. serializationObject.multiMaterials.push(mesh.material.serialize());
  76380. }
  76381. }
  76382. }
  76383. //serialize geometry
  76384. var geometry = mesh._geometry;
  76385. if (geometry) {
  76386. if (!serializationObject.geometries) {
  76387. serializationObject.geometries = {};
  76388. serializationObject.geometries.boxes = [];
  76389. serializationObject.geometries.spheres = [];
  76390. serializationObject.geometries.cylinders = [];
  76391. serializationObject.geometries.toruses = [];
  76392. serializationObject.geometries.grounds = [];
  76393. serializationObject.geometries.planes = [];
  76394. serializationObject.geometries.torusKnots = [];
  76395. serializationObject.geometries.vertexData = [];
  76396. }
  76397. serializeGeometry(geometry, serializationObject.geometries);
  76398. }
  76399. // Skeletons
  76400. if (mesh.skeleton) {
  76401. serializationObject.skeletons = serializationObject.skeletons || [];
  76402. serializationObject.skeletons.push(mesh.skeleton.serialize());
  76403. }
  76404. //serialize the actual mesh
  76405. serializationObject.meshes = serializationObject.meshes || [];
  76406. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  76407. }
  76408. };
  76409. var SceneSerializer = /** @class */ (function () {
  76410. function SceneSerializer() {
  76411. }
  76412. SceneSerializer.ClearCache = function () {
  76413. serializedGeometries = [];
  76414. };
  76415. SceneSerializer.Serialize = function (scene) {
  76416. var serializationObject = {};
  76417. SceneSerializer.ClearCache();
  76418. // Scene
  76419. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  76420. serializationObject.autoClear = scene.autoClear;
  76421. serializationObject.clearColor = scene.clearColor.asArray();
  76422. serializationObject.ambientColor = scene.ambientColor.asArray();
  76423. serializationObject.gravity = scene.gravity.asArray();
  76424. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  76425. serializationObject.workerCollisions = scene.workerCollisions;
  76426. // Fog
  76427. if (scene.fogMode && scene.fogMode !== 0) {
  76428. serializationObject.fogMode = scene.fogMode;
  76429. serializationObject.fogColor = scene.fogColor.asArray();
  76430. serializationObject.fogStart = scene.fogStart;
  76431. serializationObject.fogEnd = scene.fogEnd;
  76432. serializationObject.fogDensity = scene.fogDensity;
  76433. }
  76434. //Physics
  76435. if (scene.isPhysicsEnabled()) {
  76436. var physicEngine = scene.getPhysicsEngine();
  76437. if (physicEngine) {
  76438. serializationObject.physicsEnabled = true;
  76439. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  76440. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  76441. }
  76442. }
  76443. // Metadata
  76444. if (scene.metadata) {
  76445. serializationObject.metadata = scene.metadata;
  76446. }
  76447. // Morph targets
  76448. serializationObject.morphTargetManagers = [];
  76449. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  76450. var abstractMesh = _a[_i];
  76451. var manager = abstractMesh.morphTargetManager;
  76452. if (manager) {
  76453. serializationObject.morphTargetManagers.push(manager.serialize());
  76454. }
  76455. }
  76456. // Lights
  76457. serializationObject.lights = [];
  76458. var index;
  76459. var light;
  76460. for (index = 0; index < scene.lights.length; index++) {
  76461. light = scene.lights[index];
  76462. if (!light.doNotSerialize) {
  76463. serializationObject.lights.push(light.serialize());
  76464. }
  76465. }
  76466. // Cameras
  76467. serializationObject.cameras = [];
  76468. for (index = 0; index < scene.cameras.length; index++) {
  76469. var camera = scene.cameras[index];
  76470. if (!camera.doNotSerialize) {
  76471. serializationObject.cameras.push(camera.serialize());
  76472. }
  76473. }
  76474. if (scene.activeCamera) {
  76475. serializationObject.activeCameraID = scene.activeCamera.id;
  76476. }
  76477. // Animations
  76478. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  76479. // Materials
  76480. serializationObject.materials = [];
  76481. serializationObject.multiMaterials = [];
  76482. var material;
  76483. for (index = 0; index < scene.materials.length; index++) {
  76484. material = scene.materials[index];
  76485. if (!material.doNotSerialize) {
  76486. serializationObject.materials.push(material.serialize());
  76487. }
  76488. }
  76489. // MultiMaterials
  76490. serializationObject.multiMaterials = [];
  76491. for (index = 0; index < scene.multiMaterials.length; index++) {
  76492. var multiMaterial = scene.multiMaterials[index];
  76493. serializationObject.multiMaterials.push(multiMaterial.serialize());
  76494. }
  76495. // Skeletons
  76496. serializationObject.skeletons = [];
  76497. for (index = 0; index < scene.skeletons.length; index++) {
  76498. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  76499. }
  76500. // Transform nodes
  76501. serializationObject.transformNodes = [];
  76502. for (index = 0; index < scene.transformNodes.length; index++) {
  76503. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  76504. }
  76505. // Geometries
  76506. serializationObject.geometries = {};
  76507. serializationObject.geometries.boxes = [];
  76508. serializationObject.geometries.spheres = [];
  76509. serializationObject.geometries.cylinders = [];
  76510. serializationObject.geometries.toruses = [];
  76511. serializationObject.geometries.grounds = [];
  76512. serializationObject.geometries.planes = [];
  76513. serializationObject.geometries.torusKnots = [];
  76514. serializationObject.geometries.vertexData = [];
  76515. serializedGeometries = [];
  76516. var geometries = scene.getGeometries();
  76517. for (index = 0; index < geometries.length; index++) {
  76518. var geometry = geometries[index];
  76519. if (geometry.isReady()) {
  76520. serializeGeometry(geometry, serializationObject.geometries);
  76521. }
  76522. }
  76523. // Meshes
  76524. serializationObject.meshes = [];
  76525. for (index = 0; index < scene.meshes.length; index++) {
  76526. var abstractMesh = scene.meshes[index];
  76527. if (abstractMesh instanceof BABYLON.Mesh) {
  76528. var mesh = abstractMesh;
  76529. if (!mesh.doNotSerialize) {
  76530. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  76531. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  76532. }
  76533. }
  76534. }
  76535. }
  76536. // Particles Systems
  76537. serializationObject.particleSystems = [];
  76538. for (index = 0; index < scene.particleSystems.length; index++) {
  76539. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  76540. }
  76541. // Lens flares
  76542. serializationObject.lensFlareSystems = [];
  76543. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  76544. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  76545. }
  76546. // Shadows
  76547. serializationObject.shadowGenerators = [];
  76548. for (index = 0; index < scene.lights.length; index++) {
  76549. light = scene.lights[index];
  76550. var shadowGenerator = light.getShadowGenerator();
  76551. if (shadowGenerator) {
  76552. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  76553. }
  76554. }
  76555. // Action Manager
  76556. if (scene.actionManager) {
  76557. serializationObject.actions = scene.actionManager.serialize("scene");
  76558. }
  76559. // Audio
  76560. serializationObject.sounds = [];
  76561. for (index = 0; index < scene.soundTracks.length; index++) {
  76562. var soundtrack = scene.soundTracks[index];
  76563. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  76564. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  76565. }
  76566. }
  76567. return serializationObject;
  76568. };
  76569. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  76570. if (withParents === void 0) { withParents = false; }
  76571. if (withChildren === void 0) { withChildren = false; }
  76572. var serializationObject = {};
  76573. SceneSerializer.ClearCache();
  76574. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  76575. if (withParents || withChildren) {
  76576. //deliberate for loop! not for each, appended should be processed as well.
  76577. for (var i = 0; i < toSerialize.length; ++i) {
  76578. if (withChildren) {
  76579. toSerialize[i].getDescendants().forEach(function (node) {
  76580. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  76581. toSerialize.push(node);
  76582. }
  76583. });
  76584. }
  76585. //make sure the array doesn't contain the object already
  76586. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  76587. toSerialize.push(toSerialize[i].parent);
  76588. }
  76589. }
  76590. }
  76591. toSerialize.forEach(function (mesh) {
  76592. finalizeSingleMesh(mesh, serializationObject);
  76593. });
  76594. return serializationObject;
  76595. };
  76596. return SceneSerializer;
  76597. }());
  76598. BABYLON.SceneSerializer = SceneSerializer;
  76599. })(BABYLON || (BABYLON = {}));
  76600. //# sourceMappingURL=babylon.sceneSerializer.js.map
  76601. var BABYLON;
  76602. (function (BABYLON) {
  76603. var ReflectionProbe = /** @class */ (function () {
  76604. function ReflectionProbe(name, size, scene, generateMipMaps) {
  76605. if (generateMipMaps === void 0) { generateMipMaps = true; }
  76606. var _this = this;
  76607. this.name = name;
  76608. this._viewMatrix = BABYLON.Matrix.Identity();
  76609. this._target = BABYLON.Vector3.Zero();
  76610. this._add = BABYLON.Vector3.Zero();
  76611. this.invertYAxis = false;
  76612. this.position = BABYLON.Vector3.Zero();
  76613. this._scene = scene;
  76614. this._scene.reflectionProbes.push(this);
  76615. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  76616. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  76617. switch (faceIndex) {
  76618. case 0:
  76619. _this._add.copyFromFloats(1, 0, 0);
  76620. break;
  76621. case 1:
  76622. _this._add.copyFromFloats(-1, 0, 0);
  76623. break;
  76624. case 2:
  76625. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  76626. break;
  76627. case 3:
  76628. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  76629. break;
  76630. case 4:
  76631. _this._add.copyFromFloats(0, 0, 1);
  76632. break;
  76633. case 5:
  76634. _this._add.copyFromFloats(0, 0, -1);
  76635. break;
  76636. }
  76637. if (_this._attachedMesh) {
  76638. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  76639. }
  76640. _this.position.addToRef(_this._add, _this._target);
  76641. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  76642. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  76643. scene._forcedViewPosition = _this.position;
  76644. });
  76645. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  76646. scene._forcedViewPosition = null;
  76647. scene.updateTransformMatrix(true);
  76648. });
  76649. if (scene.activeCamera) {
  76650. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  76651. }
  76652. }
  76653. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  76654. get: function () {
  76655. return this._renderTargetTexture.samples;
  76656. },
  76657. set: function (value) {
  76658. this._renderTargetTexture.samples = value;
  76659. },
  76660. enumerable: true,
  76661. configurable: true
  76662. });
  76663. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  76664. get: function () {
  76665. return this._renderTargetTexture.refreshRate;
  76666. },
  76667. set: function (value) {
  76668. this._renderTargetTexture.refreshRate = value;
  76669. },
  76670. enumerable: true,
  76671. configurable: true
  76672. });
  76673. ReflectionProbe.prototype.getScene = function () {
  76674. return this._scene;
  76675. };
  76676. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  76677. get: function () {
  76678. return this._renderTargetTexture;
  76679. },
  76680. enumerable: true,
  76681. configurable: true
  76682. });
  76683. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  76684. get: function () {
  76685. return this._renderTargetTexture.renderList;
  76686. },
  76687. enumerable: true,
  76688. configurable: true
  76689. });
  76690. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  76691. this._attachedMesh = mesh;
  76692. };
  76693. /**
  76694. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  76695. *
  76696. * @param renderingGroupId The rendering group id corresponding to its index
  76697. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  76698. */
  76699. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  76700. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  76701. };
  76702. ReflectionProbe.prototype.dispose = function () {
  76703. var index = this._scene.reflectionProbes.indexOf(this);
  76704. if (index !== -1) {
  76705. // Remove from the scene if found
  76706. this._scene.reflectionProbes.splice(index, 1);
  76707. }
  76708. if (this._renderTargetTexture) {
  76709. this._renderTargetTexture.dispose();
  76710. this._renderTargetTexture = null;
  76711. }
  76712. };
  76713. return ReflectionProbe;
  76714. }());
  76715. BABYLON.ReflectionProbe = ReflectionProbe;
  76716. })(BABYLON || (BABYLON = {}));
  76717. //# sourceMappingURL=babylon.reflectionProbe.js.map
  76718. var BABYLON;
  76719. (function (BABYLON) {
  76720. var Layer = /** @class */ (function () {
  76721. function Layer(name, imgUrl, scene, isBackground, color) {
  76722. this.name = name;
  76723. this.scale = new BABYLON.Vector2(1, 1);
  76724. this.offset = new BABYLON.Vector2(0, 0);
  76725. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  76726. this.layerMask = 0x0FFFFFFF;
  76727. this._vertexBuffers = {};
  76728. // Events
  76729. /**
  76730. * An event triggered when the layer is disposed.
  76731. * @type {BABYLON.Observable}
  76732. */
  76733. this.onDisposeObservable = new BABYLON.Observable();
  76734. /**
  76735. * An event triggered before rendering the scene
  76736. * @type {BABYLON.Observable}
  76737. */
  76738. this.onBeforeRenderObservable = new BABYLON.Observable();
  76739. /**
  76740. * An event triggered after rendering the scene
  76741. * @type {BABYLON.Observable}
  76742. */
  76743. this.onAfterRenderObservable = new BABYLON.Observable();
  76744. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  76745. this.isBackground = isBackground === undefined ? true : isBackground;
  76746. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  76747. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  76748. this._scene.layers.push(this);
  76749. var engine = this._scene.getEngine();
  76750. // VBO
  76751. var vertices = [];
  76752. vertices.push(1, 1);
  76753. vertices.push(-1, 1);
  76754. vertices.push(-1, -1);
  76755. vertices.push(1, -1);
  76756. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  76757. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  76758. this._createIndexBuffer();
  76759. // Effects
  76760. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  76761. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  76762. }
  76763. Object.defineProperty(Layer.prototype, "onDispose", {
  76764. set: function (callback) {
  76765. if (this._onDisposeObserver) {
  76766. this.onDisposeObservable.remove(this._onDisposeObserver);
  76767. }
  76768. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  76769. },
  76770. enumerable: true,
  76771. configurable: true
  76772. });
  76773. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  76774. set: function (callback) {
  76775. if (this._onBeforeRenderObserver) {
  76776. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  76777. }
  76778. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  76779. },
  76780. enumerable: true,
  76781. configurable: true
  76782. });
  76783. Object.defineProperty(Layer.prototype, "onAfterRender", {
  76784. set: function (callback) {
  76785. if (this._onAfterRenderObserver) {
  76786. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  76787. }
  76788. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  76789. },
  76790. enumerable: true,
  76791. configurable: true
  76792. });
  76793. Layer.prototype._createIndexBuffer = function () {
  76794. var engine = this._scene.getEngine();
  76795. // Indices
  76796. var indices = [];
  76797. indices.push(0);
  76798. indices.push(1);
  76799. indices.push(2);
  76800. indices.push(0);
  76801. indices.push(2);
  76802. indices.push(3);
  76803. this._indexBuffer = engine.createIndexBuffer(indices);
  76804. };
  76805. Layer.prototype._rebuild = function () {
  76806. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76807. if (vb) {
  76808. vb._rebuild();
  76809. }
  76810. this._createIndexBuffer();
  76811. };
  76812. Layer.prototype.render = function () {
  76813. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  76814. // Check
  76815. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  76816. return;
  76817. var engine = this._scene.getEngine();
  76818. this.onBeforeRenderObservable.notifyObservers(this);
  76819. // Render
  76820. engine.enableEffect(currentEffect);
  76821. engine.setState(false);
  76822. // Texture
  76823. currentEffect.setTexture("textureSampler", this.texture);
  76824. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  76825. // Color
  76826. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  76827. // Scale / offset
  76828. currentEffect.setVector2("offset", this.offset);
  76829. currentEffect.setVector2("scale", this.scale);
  76830. // VBOs
  76831. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  76832. // Draw order
  76833. if (!this.alphaTest) {
  76834. engine.setAlphaMode(this.alphaBlendingMode);
  76835. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76836. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76837. }
  76838. else {
  76839. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76840. }
  76841. this.onAfterRenderObservable.notifyObservers(this);
  76842. };
  76843. Layer.prototype.dispose = function () {
  76844. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76845. if (vertexBuffer) {
  76846. vertexBuffer.dispose();
  76847. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  76848. }
  76849. if (this._indexBuffer) {
  76850. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  76851. this._indexBuffer = null;
  76852. }
  76853. if (this.texture) {
  76854. this.texture.dispose();
  76855. this.texture = null;
  76856. }
  76857. // Remove from scene
  76858. var index = this._scene.layers.indexOf(this);
  76859. this._scene.layers.splice(index, 1);
  76860. // Callback
  76861. this.onDisposeObservable.notifyObservers(this);
  76862. this.onDisposeObservable.clear();
  76863. this.onAfterRenderObservable.clear();
  76864. this.onBeforeRenderObservable.clear();
  76865. };
  76866. return Layer;
  76867. }());
  76868. BABYLON.Layer = Layer;
  76869. })(BABYLON || (BABYLON = {}));
  76870. //# sourceMappingURL=babylon.layer.js.map
  76871. var BABYLON;
  76872. (function (BABYLON) {
  76873. var TextureTools = /** @class */ (function () {
  76874. function TextureTools() {
  76875. }
  76876. /**
  76877. * Uses the GPU to create a copy texture rescaled at a given size
  76878. * @param texture Texture to copy from
  76879. * @param width Desired width
  76880. * @param height Desired height
  76881. * @return Generated texture
  76882. */
  76883. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  76884. if (useBilinearMode === void 0) { useBilinearMode = true; }
  76885. var scene = texture.getScene();
  76886. var engine = scene.getEngine();
  76887. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  76888. rtt.wrapU = texture.wrapU;
  76889. rtt.wrapV = texture.wrapV;
  76890. rtt.uOffset = texture.uOffset;
  76891. rtt.vOffset = texture.vOffset;
  76892. rtt.uScale = texture.uScale;
  76893. rtt.vScale = texture.vScale;
  76894. rtt.uAng = texture.uAng;
  76895. rtt.vAng = texture.vAng;
  76896. rtt.wAng = texture.wAng;
  76897. rtt.coordinatesIndex = texture.coordinatesIndex;
  76898. rtt.level = texture.level;
  76899. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  76900. rtt._texture.isReady = false;
  76901. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76902. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76903. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76904. passPostProcess.getEffect().executeWhenCompiled(function () {
  76905. passPostProcess.onApply = function (effect) {
  76906. effect.setTexture("textureSampler", texture);
  76907. };
  76908. var internalTexture = rtt.getInternalTexture();
  76909. if (internalTexture) {
  76910. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  76911. engine.unBindFramebuffer(internalTexture);
  76912. rtt.disposeFramebufferObjects();
  76913. passPostProcess.dispose();
  76914. internalTexture.isReady = true;
  76915. }
  76916. });
  76917. return rtt;
  76918. };
  76919. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  76920. if (!scene._environmentBRDFTexture) {
  76921. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76922. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76923. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76924. scene._environmentBRDFTexture = texture;
  76925. }
  76926. return scene._environmentBRDFTexture;
  76927. };
  76928. 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=";
  76929. return TextureTools;
  76930. }());
  76931. BABYLON.TextureTools = TextureTools;
  76932. })(BABYLON || (BABYLON = {}));
  76933. //# sourceMappingURL=babylon.textureTools.js.map
  76934. var BABYLON;
  76935. (function (BABYLON) {
  76936. var FramingBehavior = /** @class */ (function () {
  76937. function FramingBehavior() {
  76938. this._mode = FramingBehavior.FitFrustumSidesMode;
  76939. this._radiusScale = 1.0;
  76940. this._positionScale = 0.5;
  76941. this._defaultElevation = 0.3;
  76942. this._elevationReturnTime = 1500;
  76943. this._elevationReturnWaitTime = 1000;
  76944. this._zoomStopsAnimation = false;
  76945. this._framingTime = 1500;
  76946. this._isPointerDown = false;
  76947. this._lastInteractionTime = -Infinity;
  76948. // Framing control
  76949. this._animatables = new Array();
  76950. this._betaIsAnimating = false;
  76951. }
  76952. Object.defineProperty(FramingBehavior.prototype, "name", {
  76953. get: function () {
  76954. return "Framing";
  76955. },
  76956. enumerable: true,
  76957. configurable: true
  76958. });
  76959. Object.defineProperty(FramingBehavior.prototype, "mode", {
  76960. /**
  76961. * Gets current mode used by the behavior.
  76962. */
  76963. get: function () {
  76964. return this._mode;
  76965. },
  76966. /**
  76967. * Sets the current mode used by the behavior
  76968. */
  76969. set: function (mode) {
  76970. this._mode = mode;
  76971. },
  76972. enumerable: true,
  76973. configurable: true
  76974. });
  76975. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  76976. /**
  76977. * Gets the scale applied to the radius
  76978. */
  76979. get: function () {
  76980. return this._radiusScale;
  76981. },
  76982. /**
  76983. * Sets the scale applied to the radius (1 by default)
  76984. */
  76985. set: function (radius) {
  76986. this._radiusScale = radius;
  76987. },
  76988. enumerable: true,
  76989. configurable: true
  76990. });
  76991. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  76992. /**
  76993. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  76994. */
  76995. get: function () {
  76996. return this._positionScale;
  76997. },
  76998. /**
  76999. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  77000. */
  77001. set: function (scale) {
  77002. this._positionScale = scale;
  77003. },
  77004. enumerable: true,
  77005. configurable: true
  77006. });
  77007. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  77008. /**
  77009. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  77010. * behaviour is triggered, in radians.
  77011. */
  77012. get: function () {
  77013. return this._defaultElevation;
  77014. },
  77015. /**
  77016. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  77017. * behaviour is triggered, in radians.
  77018. */
  77019. set: function (elevation) {
  77020. this._defaultElevation = elevation;
  77021. },
  77022. enumerable: true,
  77023. configurable: true
  77024. });
  77025. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  77026. /**
  77027. * Gets the time (in milliseconds) taken to return to the default beta position.
  77028. * Negative value indicates camera should not return to default.
  77029. */
  77030. get: function () {
  77031. return this._elevationReturnTime;
  77032. },
  77033. /**
  77034. * Sets the time (in milliseconds) taken to return to the default beta position.
  77035. * Negative value indicates camera should not return to default.
  77036. */
  77037. set: function (speed) {
  77038. this._elevationReturnTime = speed;
  77039. },
  77040. enumerable: true,
  77041. configurable: true
  77042. });
  77043. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  77044. /**
  77045. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  77046. */
  77047. get: function () {
  77048. return this._elevationReturnWaitTime;
  77049. },
  77050. /**
  77051. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  77052. */
  77053. set: function (time) {
  77054. this._elevationReturnWaitTime = time;
  77055. },
  77056. enumerable: true,
  77057. configurable: true
  77058. });
  77059. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  77060. /**
  77061. * Gets the flag that indicates if user zooming should stop animation.
  77062. */
  77063. get: function () {
  77064. return this._zoomStopsAnimation;
  77065. },
  77066. /**
  77067. * Sets the flag that indicates if user zooming should stop animation.
  77068. */
  77069. set: function (flag) {
  77070. this._zoomStopsAnimation = flag;
  77071. },
  77072. enumerable: true,
  77073. configurable: true
  77074. });
  77075. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  77076. /**
  77077. * Gets the transition time when framing the mesh, in milliseconds
  77078. */
  77079. get: function () {
  77080. return this._framingTime;
  77081. },
  77082. /**
  77083. * Sets the transition time when framing the mesh, in milliseconds
  77084. */
  77085. set: function (time) {
  77086. this._framingTime = time;
  77087. },
  77088. enumerable: true,
  77089. configurable: true
  77090. });
  77091. FramingBehavior.prototype.init = function () {
  77092. // Do notihng
  77093. };
  77094. FramingBehavior.prototype.attach = function (camera) {
  77095. var _this = this;
  77096. this._attachedCamera = camera;
  77097. var scene = this._attachedCamera.getScene();
  77098. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  77099. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  77100. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  77101. _this._isPointerDown = true;
  77102. return;
  77103. }
  77104. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  77105. _this._isPointerDown = false;
  77106. }
  77107. });
  77108. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  77109. if (mesh) {
  77110. _this.zoomOnMesh(mesh);
  77111. }
  77112. });
  77113. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  77114. // Stop the animation if there is user interaction and the animation should stop for this interaction
  77115. _this._applyUserInteraction();
  77116. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  77117. // back to the default position after a given timeout
  77118. _this._maintainCameraAboveGround();
  77119. });
  77120. };
  77121. FramingBehavior.prototype.detach = function () {
  77122. if (!this._attachedCamera) {
  77123. return;
  77124. }
  77125. var scene = this._attachedCamera.getScene();
  77126. if (this._onPrePointerObservableObserver) {
  77127. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  77128. }
  77129. if (this._onAfterCheckInputsObserver) {
  77130. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  77131. }
  77132. if (this._onMeshTargetChangedObserver) {
  77133. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  77134. }
  77135. this._attachedCamera = null;
  77136. };
  77137. /**
  77138. * Targets the given mesh and updates zoom level accordingly.
  77139. * @param mesh The mesh to target.
  77140. * @param radius Optional. If a cached radius position already exists, overrides default.
  77141. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  77142. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  77143. * @param onAnimationEnd Callback triggered at the end of the framing animation
  77144. */
  77145. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  77146. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  77147. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  77148. mesh.computeWorldMatrix(true);
  77149. var boundingBox = mesh.getBoundingInfo().boundingBox;
  77150. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  77151. };
  77152. /**
  77153. * Targets the given mesh with its children and updates zoom level accordingly.
  77154. * @param mesh The mesh to target.
  77155. * @param radius Optional. If a cached radius position already exists, overrides default.
  77156. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  77157. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  77158. * @param onAnimationEnd Callback triggered at the end of the framing animation
  77159. */
  77160. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  77161. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  77162. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  77163. mesh.computeWorldMatrix(true);
  77164. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  77165. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  77166. };
  77167. /**
  77168. * Targets the given meshes with their children and updates zoom level accordingly.
  77169. * @param meshes The mesh to target.
  77170. * @param radius Optional. If a cached radius position already exists, overrides default.
  77171. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  77172. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  77173. * @param onAnimationEnd Callback triggered at the end of the framing animation
  77174. */
  77175. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  77176. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  77177. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  77178. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  77179. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  77180. for (var i = 0; i < meshes.length; i++) {
  77181. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  77182. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  77183. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  77184. }
  77185. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  77186. };
  77187. /**
  77188. * Targets the given mesh and updates zoom level accordingly.
  77189. * @param mesh The mesh to target.
  77190. * @param radius Optional. If a cached radius position already exists, overrides default.
  77191. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  77192. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  77193. * @param onAnimationEnd Callback triggered at the end of the framing animation
  77194. */
  77195. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  77196. var _this = this;
  77197. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  77198. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  77199. var zoomTarget;
  77200. if (!this._attachedCamera) {
  77201. return;
  77202. }
  77203. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  77204. var bottom = minimumWorld.y;
  77205. var top = maximumWorld.y;
  77206. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  77207. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  77208. if (focusOnOriginXZ) {
  77209. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  77210. }
  77211. else {
  77212. var centerWorld = minimumWorld.add(radiusWorld);
  77213. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  77214. }
  77215. if (!this._vectorTransition) {
  77216. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  77217. }
  77218. this._betaIsAnimating = true;
  77219. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  77220. if (animatable) {
  77221. this._animatables.push(animatable);
  77222. }
  77223. // sets the radius and lower radius bounds
  77224. // Small delta ensures camera is not always at lower zoom limit.
  77225. var radius = 0;
  77226. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  77227. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  77228. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  77229. radius = position;
  77230. }
  77231. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  77232. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  77233. if (this._attachedCamera.lowerRadiusLimit === null) {
  77234. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  77235. }
  77236. }
  77237. // Set sensibilities
  77238. var extend = maximumWorld.subtract(minimumWorld).length();
  77239. this._attachedCamera.panningSensibility = 5000 / extend;
  77240. this._attachedCamera.wheelPrecision = 100 / radius;
  77241. // transition to new radius
  77242. if (!this._radiusTransition) {
  77243. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  77244. }
  77245. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  77246. if (onAnimationEnd) {
  77247. onAnimationEnd();
  77248. }
  77249. if (_this._attachedCamera) {
  77250. _this._attachedCamera.storeState();
  77251. }
  77252. });
  77253. if (animatable) {
  77254. this._animatables.push(animatable);
  77255. }
  77256. };
  77257. /**
  77258. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  77259. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  77260. * frustum width.
  77261. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  77262. * to fully enclose the mesh in the viewing frustum.
  77263. */
  77264. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  77265. var size = maximumWorld.subtract(minimumWorld);
  77266. var boxVectorGlobalDiagonal = size.length();
  77267. var frustumSlope = this._getFrustumSlope();
  77268. // Formula for setting distance
  77269. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  77270. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  77271. // Horizon distance
  77272. var radius = radiusWithoutFraming * this._radiusScale;
  77273. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  77274. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  77275. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  77276. var camera = this._attachedCamera;
  77277. if (!camera) {
  77278. return 0;
  77279. }
  77280. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  77281. // Don't exceed the requested limit
  77282. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  77283. }
  77284. // Don't exceed the upper radius limit
  77285. if (camera.upperRadiusLimit) {
  77286. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  77287. }
  77288. return distance;
  77289. };
  77290. /**
  77291. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  77292. * is automatically returned to its default position (expected to be above ground plane).
  77293. */
  77294. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  77295. var _this = this;
  77296. if (this._elevationReturnTime < 0) {
  77297. return;
  77298. }
  77299. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  77300. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  77301. var limitBeta = Math.PI * 0.5;
  77302. // Bring the camera back up if below the ground plane
  77303. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  77304. this._betaIsAnimating = true;
  77305. //Transition to new position
  77306. this.stopAllAnimations();
  77307. if (!this._betaTransition) {
  77308. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  77309. }
  77310. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  77311. _this._clearAnimationLocks();
  77312. _this.stopAllAnimations();
  77313. });
  77314. if (animatabe) {
  77315. this._animatables.push(animatabe);
  77316. }
  77317. }
  77318. };
  77319. /**
  77320. * Returns the frustum slope based on the canvas ratio and camera FOV
  77321. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  77322. */
  77323. FramingBehavior.prototype._getFrustumSlope = function () {
  77324. // Calculate the viewport ratio
  77325. // Aspect Ratio is Height/Width.
  77326. var camera = this._attachedCamera;
  77327. if (!camera) {
  77328. return BABYLON.Vector2.Zero();
  77329. }
  77330. var engine = camera.getScene().getEngine();
  77331. var aspectRatio = engine.getAspectRatio(camera);
  77332. // Camera FOV is the vertical field of view (top-bottom) in radians.
  77333. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  77334. var frustumSlopeY = Math.tan(camera.fov / 2);
  77335. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  77336. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  77337. // along the forward vector.
  77338. var frustumSlopeX = frustumSlopeY * aspectRatio;
  77339. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  77340. };
  77341. /**
  77342. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  77343. */
  77344. FramingBehavior.prototype._clearAnimationLocks = function () {
  77345. this._betaIsAnimating = false;
  77346. };
  77347. /**
  77348. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  77349. */
  77350. FramingBehavior.prototype._applyUserInteraction = function () {
  77351. if (this.isUserIsMoving) {
  77352. this._lastInteractionTime = BABYLON.Tools.Now;
  77353. this.stopAllAnimations();
  77354. this._clearAnimationLocks();
  77355. }
  77356. };
  77357. /**
  77358. * Stops and removes all animations that have been applied to the camera
  77359. */
  77360. FramingBehavior.prototype.stopAllAnimations = function () {
  77361. if (this._attachedCamera) {
  77362. this._attachedCamera.animations = [];
  77363. }
  77364. while (this._animatables.length) {
  77365. if (this._animatables[0]) {
  77366. this._animatables[0].onAnimationEnd = null;
  77367. this._animatables[0].stop();
  77368. }
  77369. this._animatables.shift();
  77370. }
  77371. };
  77372. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  77373. /**
  77374. * Gets a value indicating if the user is moving the camera
  77375. */
  77376. get: function () {
  77377. if (!this._attachedCamera) {
  77378. return false;
  77379. }
  77380. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  77381. this._attachedCamera.inertialBetaOffset !== 0 ||
  77382. this._attachedCamera.inertialRadiusOffset !== 0 ||
  77383. this._attachedCamera.inertialPanningX !== 0 ||
  77384. this._attachedCamera.inertialPanningY !== 0 ||
  77385. this._isPointerDown;
  77386. },
  77387. enumerable: true,
  77388. configurable: true
  77389. });
  77390. /**
  77391. * The easing function used by animations
  77392. */
  77393. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  77394. /**
  77395. * The easing mode used by animations
  77396. */
  77397. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  77398. // Statics
  77399. /**
  77400. * The camera can move all the way towards the mesh.
  77401. */
  77402. FramingBehavior.IgnoreBoundsSizeMode = 0;
  77403. /**
  77404. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  77405. */
  77406. FramingBehavior.FitFrustumSidesMode = 1;
  77407. return FramingBehavior;
  77408. }());
  77409. BABYLON.FramingBehavior = FramingBehavior;
  77410. })(BABYLON || (BABYLON = {}));
  77411. //# sourceMappingURL=babylon.framingBehavior.js.map
  77412. var BABYLON;
  77413. (function (BABYLON) {
  77414. /**
  77415. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  77416. */
  77417. var BouncingBehavior = /** @class */ (function () {
  77418. function BouncingBehavior() {
  77419. /**
  77420. * The duration of the animation, in milliseconds
  77421. */
  77422. this.transitionDuration = 450;
  77423. /**
  77424. * Length of the distance animated by the transition when lower radius is reached
  77425. */
  77426. this.lowerRadiusTransitionRange = 2;
  77427. /**
  77428. * Length of the distance animated by the transition when upper radius is reached
  77429. */
  77430. this.upperRadiusTransitionRange = -2;
  77431. this._autoTransitionRange = false;
  77432. // Animations
  77433. this._radiusIsAnimating = false;
  77434. this._radiusBounceTransition = null;
  77435. this._animatables = new Array();
  77436. }
  77437. Object.defineProperty(BouncingBehavior.prototype, "name", {
  77438. get: function () {
  77439. return "Bouncing";
  77440. },
  77441. enumerable: true,
  77442. configurable: true
  77443. });
  77444. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  77445. /**
  77446. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  77447. */
  77448. get: function () {
  77449. return this._autoTransitionRange;
  77450. },
  77451. /**
  77452. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  77453. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  77454. */
  77455. set: function (value) {
  77456. var _this = this;
  77457. if (this._autoTransitionRange === value) {
  77458. return;
  77459. }
  77460. this._autoTransitionRange = value;
  77461. var camera = this._attachedCamera;
  77462. if (!camera) {
  77463. return;
  77464. }
  77465. if (value) {
  77466. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  77467. if (!mesh) {
  77468. return;
  77469. }
  77470. mesh.computeWorldMatrix(true);
  77471. var diagonal = mesh.getBoundingInfo().diagonalLength;
  77472. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  77473. _this.upperRadiusTransitionRange = diagonal * 0.05;
  77474. });
  77475. }
  77476. else if (this._onMeshTargetChangedObserver) {
  77477. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  77478. }
  77479. },
  77480. enumerable: true,
  77481. configurable: true
  77482. });
  77483. BouncingBehavior.prototype.init = function () {
  77484. // Do notihng
  77485. };
  77486. BouncingBehavior.prototype.attach = function (camera) {
  77487. var _this = this;
  77488. this._attachedCamera = camera;
  77489. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  77490. if (!_this._attachedCamera) {
  77491. return;
  77492. }
  77493. // Add the bounce animation to the lower radius limit
  77494. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  77495. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  77496. }
  77497. // Add the bounce animation to the upper radius limit
  77498. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  77499. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  77500. }
  77501. });
  77502. };
  77503. BouncingBehavior.prototype.detach = function () {
  77504. if (!this._attachedCamera) {
  77505. return;
  77506. }
  77507. if (this._onAfterCheckInputsObserver) {
  77508. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  77509. }
  77510. if (this._onMeshTargetChangedObserver) {
  77511. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  77512. }
  77513. this._attachedCamera = null;
  77514. };
  77515. /**
  77516. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  77517. * @param radiusLimit The limit to check against.
  77518. * @return Bool to indicate if at limit.
  77519. */
  77520. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  77521. if (!this._attachedCamera) {
  77522. return false;
  77523. }
  77524. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  77525. return true;
  77526. }
  77527. return false;
  77528. };
  77529. /**
  77530. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  77531. * @param radiusDelta The delta by which to animate to. Can be negative.
  77532. */
  77533. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  77534. var _this = this;
  77535. if (!this._attachedCamera) {
  77536. return;
  77537. }
  77538. if (!this._radiusBounceTransition) {
  77539. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  77540. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  77541. }
  77542. // Prevent zoom until bounce has completed
  77543. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  77544. this._attachedCamera.wheelPrecision = Infinity;
  77545. this._attachedCamera.inertialRadiusOffset = 0;
  77546. // Animate to the radius limit
  77547. this.stopAllAnimations();
  77548. this._radiusIsAnimating = true;
  77549. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  77550. if (animatable) {
  77551. this._animatables.push(animatable);
  77552. }
  77553. };
  77554. /**
  77555. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  77556. */
  77557. BouncingBehavior.prototype._clearAnimationLocks = function () {
  77558. this._radiusIsAnimating = false;
  77559. if (this._attachedCamera) {
  77560. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  77561. }
  77562. };
  77563. /**
  77564. * Stops and removes all animations that have been applied to the camera
  77565. */
  77566. BouncingBehavior.prototype.stopAllAnimations = function () {
  77567. if (this._attachedCamera) {
  77568. this._attachedCamera.animations = [];
  77569. }
  77570. while (this._animatables.length) {
  77571. this._animatables[0].onAnimationEnd = null;
  77572. this._animatables[0].stop();
  77573. this._animatables.shift();
  77574. }
  77575. };
  77576. /**
  77577. * The easing function used by animations
  77578. */
  77579. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  77580. /**
  77581. * The easing mode used by animations
  77582. */
  77583. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  77584. return BouncingBehavior;
  77585. }());
  77586. BABYLON.BouncingBehavior = BouncingBehavior;
  77587. })(BABYLON || (BABYLON = {}));
  77588. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  77589. var BABYLON;
  77590. (function (BABYLON) {
  77591. var AutoRotationBehavior = /** @class */ (function () {
  77592. function AutoRotationBehavior() {
  77593. this._zoomStopsAnimation = false;
  77594. this._idleRotationSpeed = 0.05;
  77595. this._idleRotationWaitTime = 2000;
  77596. this._idleRotationSpinupTime = 2000;
  77597. this._isPointerDown = false;
  77598. this._lastFrameTime = null;
  77599. this._lastInteractionTime = -Infinity;
  77600. this._cameraRotationSpeed = 0;
  77601. this._lastFrameRadius = 0;
  77602. }
  77603. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  77604. get: function () {
  77605. return "AutoRotation";
  77606. },
  77607. enumerable: true,
  77608. configurable: true
  77609. });
  77610. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  77611. /**
  77612. * Gets the flag that indicates if user zooming should stop animation.
  77613. */
  77614. get: function () {
  77615. return this._zoomStopsAnimation;
  77616. },
  77617. /**
  77618. * Sets the flag that indicates if user zooming should stop animation.
  77619. */
  77620. set: function (flag) {
  77621. this._zoomStopsAnimation = flag;
  77622. },
  77623. enumerable: true,
  77624. configurable: true
  77625. });
  77626. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  77627. /**
  77628. * Gets the default speed at which the camera rotates around the model.
  77629. */
  77630. get: function () {
  77631. return this._idleRotationSpeed;
  77632. },
  77633. /**
  77634. * Sets the default speed at which the camera rotates around the model.
  77635. */
  77636. set: function (speed) {
  77637. this._idleRotationSpeed = speed;
  77638. },
  77639. enumerable: true,
  77640. configurable: true
  77641. });
  77642. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  77643. /**
  77644. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  77645. */
  77646. get: function () {
  77647. return this._idleRotationWaitTime;
  77648. },
  77649. /**
  77650. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  77651. */
  77652. set: function (time) {
  77653. this._idleRotationWaitTime = time;
  77654. },
  77655. enumerable: true,
  77656. configurable: true
  77657. });
  77658. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  77659. /**
  77660. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  77661. */
  77662. get: function () {
  77663. return this._idleRotationSpinupTime;
  77664. },
  77665. /**
  77666. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  77667. */
  77668. set: function (time) {
  77669. this._idleRotationSpinupTime = time;
  77670. },
  77671. enumerable: true,
  77672. configurable: true
  77673. });
  77674. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  77675. /**
  77676. * Gets a value indicating if the camera is currently rotating because of this behavior
  77677. */
  77678. get: function () {
  77679. return Math.abs(this._cameraRotationSpeed) > 0;
  77680. },
  77681. enumerable: true,
  77682. configurable: true
  77683. });
  77684. AutoRotationBehavior.prototype.init = function () {
  77685. // Do notihng
  77686. };
  77687. AutoRotationBehavior.prototype.attach = function (camera) {
  77688. var _this = this;
  77689. this._attachedCamera = camera;
  77690. var scene = this._attachedCamera.getScene();
  77691. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  77692. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  77693. _this._isPointerDown = true;
  77694. return;
  77695. }
  77696. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  77697. _this._isPointerDown = false;
  77698. }
  77699. });
  77700. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  77701. var now = BABYLON.Tools.Now;
  77702. var dt = 0;
  77703. if (_this._lastFrameTime != null) {
  77704. dt = now - _this._lastFrameTime;
  77705. }
  77706. _this._lastFrameTime = now;
  77707. // Stop the animation if there is user interaction and the animation should stop for this interaction
  77708. _this._applyUserInteraction();
  77709. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  77710. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  77711. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  77712. // Step camera rotation by rotation speed
  77713. if (_this._attachedCamera) {
  77714. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  77715. }
  77716. });
  77717. };
  77718. AutoRotationBehavior.prototype.detach = function () {
  77719. if (!this._attachedCamera) {
  77720. return;
  77721. }
  77722. var scene = this._attachedCamera.getScene();
  77723. if (this._onPrePointerObservableObserver) {
  77724. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  77725. }
  77726. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  77727. this._attachedCamera = null;
  77728. };
  77729. /**
  77730. * Returns true if user is scrolling.
  77731. * @return true if user is scrolling.
  77732. */
  77733. AutoRotationBehavior.prototype._userIsZooming = function () {
  77734. if (!this._attachedCamera) {
  77735. return false;
  77736. }
  77737. return this._attachedCamera.inertialRadiusOffset !== 0;
  77738. };
  77739. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  77740. if (!this._attachedCamera) {
  77741. return false;
  77742. }
  77743. var zoomHasHitLimit = false;
  77744. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  77745. zoomHasHitLimit = true;
  77746. }
  77747. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  77748. this._lastFrameRadius = this._attachedCamera.radius;
  77749. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  77750. };
  77751. /**
  77752. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  77753. */
  77754. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  77755. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  77756. this._lastInteractionTime = BABYLON.Tools.Now;
  77757. }
  77758. };
  77759. // Tools
  77760. AutoRotationBehavior.prototype._userIsMoving = function () {
  77761. if (!this._attachedCamera) {
  77762. return false;
  77763. }
  77764. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  77765. this._attachedCamera.inertialBetaOffset !== 0 ||
  77766. this._attachedCamera.inertialRadiusOffset !== 0 ||
  77767. this._attachedCamera.inertialPanningX !== 0 ||
  77768. this._attachedCamera.inertialPanningY !== 0 ||
  77769. this._isPointerDown;
  77770. };
  77771. return AutoRotationBehavior;
  77772. }());
  77773. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  77774. })(BABYLON || (BABYLON = {}));
  77775. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  77776. var BABYLON;
  77777. (function (BABYLON) {
  77778. /**
  77779. * This class can be used to get instrumentation data from a Babylon engine
  77780. */
  77781. var EngineInstrumentation = /** @class */ (function () {
  77782. function EngineInstrumentation(engine) {
  77783. this.engine = engine;
  77784. this._captureGPUFrameTime = false;
  77785. this._gpuFrameTime = new BABYLON.PerfCounter();
  77786. this._captureShaderCompilationTime = false;
  77787. this._shaderCompilationTime = new BABYLON.PerfCounter();
  77788. // Observers
  77789. this._onBeginFrameObserver = null;
  77790. this._onEndFrameObserver = null;
  77791. this._onBeforeShaderCompilationObserver = null;
  77792. this._onAfterShaderCompilationObserver = null;
  77793. }
  77794. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  77795. // Properties
  77796. /**
  77797. * Gets the perf counter used for GPU frame time
  77798. */
  77799. get: function () {
  77800. return this._gpuFrameTime;
  77801. },
  77802. enumerable: true,
  77803. configurable: true
  77804. });
  77805. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  77806. /**
  77807. * Gets the GPU frame time capture status
  77808. */
  77809. get: function () {
  77810. return this._captureGPUFrameTime;
  77811. },
  77812. /**
  77813. * Enable or disable the GPU frame time capture
  77814. */
  77815. set: function (value) {
  77816. var _this = this;
  77817. if (value === this._captureGPUFrameTime) {
  77818. return;
  77819. }
  77820. this._captureGPUFrameTime = value;
  77821. if (value) {
  77822. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  77823. if (!_this._gpuFrameTimeToken) {
  77824. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  77825. }
  77826. });
  77827. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  77828. if (!_this._gpuFrameTimeToken) {
  77829. return;
  77830. }
  77831. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  77832. if (time > -1) {
  77833. _this._gpuFrameTimeToken = null;
  77834. _this._gpuFrameTime.fetchNewFrame();
  77835. _this._gpuFrameTime.addCount(time, true);
  77836. }
  77837. });
  77838. }
  77839. else {
  77840. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  77841. this._onBeginFrameObserver = null;
  77842. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  77843. this._onEndFrameObserver = null;
  77844. }
  77845. },
  77846. enumerable: true,
  77847. configurable: true
  77848. });
  77849. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  77850. /**
  77851. * Gets the perf counter used for shader compilation time
  77852. */
  77853. get: function () {
  77854. return this._shaderCompilationTime;
  77855. },
  77856. enumerable: true,
  77857. configurable: true
  77858. });
  77859. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  77860. /**
  77861. * Gets the shader compilation time capture status
  77862. */
  77863. get: function () {
  77864. return this._captureShaderCompilationTime;
  77865. },
  77866. /**
  77867. * Enable or disable the shader compilation time capture
  77868. */
  77869. set: function (value) {
  77870. var _this = this;
  77871. if (value === this._captureShaderCompilationTime) {
  77872. return;
  77873. }
  77874. this._captureShaderCompilationTime = value;
  77875. if (value) {
  77876. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  77877. _this._shaderCompilationTime.fetchNewFrame();
  77878. _this._shaderCompilationTime.beginMonitoring();
  77879. });
  77880. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  77881. _this._shaderCompilationTime.endMonitoring();
  77882. });
  77883. }
  77884. else {
  77885. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  77886. this._onBeforeShaderCompilationObserver = null;
  77887. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  77888. this._onAfterShaderCompilationObserver = null;
  77889. }
  77890. },
  77891. enumerable: true,
  77892. configurable: true
  77893. });
  77894. EngineInstrumentation.prototype.dispose = function () {
  77895. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  77896. this._onBeginFrameObserver = null;
  77897. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  77898. this._onEndFrameObserver = null;
  77899. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  77900. this._onBeforeShaderCompilationObserver = null;
  77901. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  77902. this._onAfterShaderCompilationObserver = null;
  77903. this.engine = null;
  77904. };
  77905. return EngineInstrumentation;
  77906. }());
  77907. BABYLON.EngineInstrumentation = EngineInstrumentation;
  77908. })(BABYLON || (BABYLON = {}));
  77909. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  77910. var BABYLON;
  77911. (function (BABYLON) {
  77912. /**
  77913. * This class can be used to get instrumentation data from a Babylon engine
  77914. */
  77915. var SceneInstrumentation = /** @class */ (function () {
  77916. function SceneInstrumentation(scene) {
  77917. var _this = this;
  77918. this.scene = scene;
  77919. this._captureActiveMeshesEvaluationTime = false;
  77920. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  77921. this._captureRenderTargetsRenderTime = false;
  77922. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  77923. this._captureFrameTime = false;
  77924. this._frameTime = new BABYLON.PerfCounter();
  77925. this._captureRenderTime = false;
  77926. this._renderTime = new BABYLON.PerfCounter();
  77927. this._captureInterFrameTime = false;
  77928. this._interFrameTime = new BABYLON.PerfCounter();
  77929. this._captureParticlesRenderTime = false;
  77930. this._particlesRenderTime = new BABYLON.PerfCounter();
  77931. this._captureSpritesRenderTime = false;
  77932. this._spritesRenderTime = new BABYLON.PerfCounter();
  77933. this._capturePhysicsTime = false;
  77934. this._physicsTime = new BABYLON.PerfCounter();
  77935. this._captureAnimationsTime = false;
  77936. this._animationsTime = new BABYLON.PerfCounter();
  77937. // Observers
  77938. this._onBeforeActiveMeshesEvaluationObserver = null;
  77939. this._onAfterActiveMeshesEvaluationObserver = null;
  77940. this._onBeforeRenderTargetsRenderObserver = null;
  77941. this._onAfterRenderTargetsRenderObserver = null;
  77942. this._onAfterRenderObserver = null;
  77943. this._onBeforeDrawPhaseObserver = null;
  77944. this._onAfterDrawPhaseObserver = null;
  77945. this._onBeforeAnimationsObserver = null;
  77946. this._onBeforeParticlesRenderingObserver = null;
  77947. this._onAfterParticlesRenderingObserver = null;
  77948. this._onBeforeSpritesRenderingObserver = null;
  77949. this._onAfterSpritesRenderingObserver = null;
  77950. this._onBeforePhysicsObserver = null;
  77951. this._onAfterPhysicsObserver = null;
  77952. this._onAfterAnimationsObserver = null;
  77953. // Before render
  77954. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  77955. if (_this._captureActiveMeshesEvaluationTime) {
  77956. _this._activeMeshesEvaluationTime.fetchNewFrame();
  77957. }
  77958. if (_this._captureRenderTargetsRenderTime) {
  77959. _this._renderTargetsRenderTime.fetchNewFrame();
  77960. }
  77961. if (_this._captureFrameTime) {
  77962. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  77963. _this._frameTime.beginMonitoring();
  77964. }
  77965. if (_this._captureInterFrameTime) {
  77966. _this._interFrameTime.endMonitoring();
  77967. }
  77968. if (_this._captureParticlesRenderTime) {
  77969. _this._particlesRenderTime.fetchNewFrame();
  77970. }
  77971. if (_this._captureSpritesRenderTime) {
  77972. _this._spritesRenderTime.fetchNewFrame();
  77973. }
  77974. if (_this._captureAnimationsTime) {
  77975. _this._animationsTime.beginMonitoring();
  77976. }
  77977. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  77978. });
  77979. // After render
  77980. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  77981. if (_this._captureFrameTime) {
  77982. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  77983. _this._frameTime.endMonitoring();
  77984. }
  77985. if (_this._captureRenderTime) {
  77986. _this._renderTime.endMonitoring(false);
  77987. }
  77988. if (_this._captureInterFrameTime) {
  77989. _this._interFrameTime.beginMonitoring();
  77990. }
  77991. });
  77992. }
  77993. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  77994. // Properties
  77995. /**
  77996. * Gets the perf counter used for active meshes evaluation time
  77997. */
  77998. get: function () {
  77999. return this._activeMeshesEvaluationTime;
  78000. },
  78001. enumerable: true,
  78002. configurable: true
  78003. });
  78004. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  78005. /**
  78006. * Gets the active meshes evaluation time capture status
  78007. */
  78008. get: function () {
  78009. return this._captureActiveMeshesEvaluationTime;
  78010. },
  78011. /**
  78012. * Enable or disable the active meshes evaluation time capture
  78013. */
  78014. set: function (value) {
  78015. var _this = this;
  78016. if (value === this._captureActiveMeshesEvaluationTime) {
  78017. return;
  78018. }
  78019. this._captureActiveMeshesEvaluationTime = value;
  78020. if (value) {
  78021. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  78022. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  78023. _this._activeMeshesEvaluationTime.beginMonitoring();
  78024. });
  78025. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  78026. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  78027. _this._activeMeshesEvaluationTime.endMonitoring();
  78028. });
  78029. }
  78030. else {
  78031. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  78032. this._onBeforeActiveMeshesEvaluationObserver = null;
  78033. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  78034. this._onAfterActiveMeshesEvaluationObserver = null;
  78035. }
  78036. },
  78037. enumerable: true,
  78038. configurable: true
  78039. });
  78040. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  78041. /**
  78042. * Gets the perf counter used for render targets render time
  78043. */
  78044. get: function () {
  78045. return this._renderTargetsRenderTime;
  78046. },
  78047. enumerable: true,
  78048. configurable: true
  78049. });
  78050. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  78051. /**
  78052. * Gets the render targets render time capture status
  78053. */
  78054. get: function () {
  78055. return this._captureRenderTargetsRenderTime;
  78056. },
  78057. /**
  78058. * Enable or disable the render targets render time capture
  78059. */
  78060. set: function (value) {
  78061. var _this = this;
  78062. if (value === this._captureRenderTargetsRenderTime) {
  78063. return;
  78064. }
  78065. this._captureRenderTargetsRenderTime = value;
  78066. if (value) {
  78067. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  78068. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  78069. _this._renderTargetsRenderTime.beginMonitoring();
  78070. });
  78071. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  78072. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  78073. _this._renderTargetsRenderTime.endMonitoring(false);
  78074. });
  78075. }
  78076. else {
  78077. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  78078. this._onBeforeRenderTargetsRenderObserver = null;
  78079. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  78080. this._onAfterRenderTargetsRenderObserver = null;
  78081. }
  78082. },
  78083. enumerable: true,
  78084. configurable: true
  78085. });
  78086. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  78087. /**
  78088. * Gets the perf counter used for particles render time
  78089. */
  78090. get: function () {
  78091. return this._particlesRenderTime;
  78092. },
  78093. enumerable: true,
  78094. configurable: true
  78095. });
  78096. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  78097. /**
  78098. * Gets the particles render time capture status
  78099. */
  78100. get: function () {
  78101. return this._captureParticlesRenderTime;
  78102. },
  78103. /**
  78104. * Enable or disable the particles render time capture
  78105. */
  78106. set: function (value) {
  78107. var _this = this;
  78108. if (value === this._captureParticlesRenderTime) {
  78109. return;
  78110. }
  78111. this._captureParticlesRenderTime = value;
  78112. if (value) {
  78113. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  78114. BABYLON.Tools.StartPerformanceCounter("Particles");
  78115. _this._particlesRenderTime.beginMonitoring();
  78116. });
  78117. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  78118. BABYLON.Tools.EndPerformanceCounter("Particles");
  78119. _this._particlesRenderTime.endMonitoring(false);
  78120. });
  78121. }
  78122. else {
  78123. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  78124. this._onBeforeParticlesRenderingObserver = null;
  78125. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  78126. this._onAfterParticlesRenderingObserver = null;
  78127. }
  78128. },
  78129. enumerable: true,
  78130. configurable: true
  78131. });
  78132. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  78133. /**
  78134. * Gets the perf counter used for sprites render time
  78135. */
  78136. get: function () {
  78137. return this._spritesRenderTime;
  78138. },
  78139. enumerable: true,
  78140. configurable: true
  78141. });
  78142. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  78143. /**
  78144. * Gets the sprites render time capture status
  78145. */
  78146. get: function () {
  78147. return this._captureSpritesRenderTime;
  78148. },
  78149. /**
  78150. * Enable or disable the sprites render time capture
  78151. */
  78152. set: function (value) {
  78153. var _this = this;
  78154. if (value === this._captureSpritesRenderTime) {
  78155. return;
  78156. }
  78157. this._captureSpritesRenderTime = value;
  78158. if (value) {
  78159. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  78160. BABYLON.Tools.StartPerformanceCounter("Sprites");
  78161. _this._spritesRenderTime.beginMonitoring();
  78162. });
  78163. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  78164. BABYLON.Tools.EndPerformanceCounter("Sprites");
  78165. _this._spritesRenderTime.endMonitoring(false);
  78166. });
  78167. }
  78168. else {
  78169. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  78170. this._onBeforeSpritesRenderingObserver = null;
  78171. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  78172. this._onAfterSpritesRenderingObserver = null;
  78173. }
  78174. },
  78175. enumerable: true,
  78176. configurable: true
  78177. });
  78178. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  78179. /**
  78180. * Gets the perf counter used for physics time
  78181. */
  78182. get: function () {
  78183. return this._physicsTime;
  78184. },
  78185. enumerable: true,
  78186. configurable: true
  78187. });
  78188. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  78189. /**
  78190. * Gets the physics time capture status
  78191. */
  78192. get: function () {
  78193. return this._capturePhysicsTime;
  78194. },
  78195. /**
  78196. * Enable or disable the physics time capture
  78197. */
  78198. set: function (value) {
  78199. var _this = this;
  78200. if (value === this._capturePhysicsTime) {
  78201. return;
  78202. }
  78203. this._capturePhysicsTime = value;
  78204. if (value) {
  78205. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  78206. BABYLON.Tools.StartPerformanceCounter("Physics");
  78207. _this._physicsTime.beginMonitoring();
  78208. });
  78209. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  78210. BABYLON.Tools.EndPerformanceCounter("Physics");
  78211. _this._physicsTime.endMonitoring();
  78212. });
  78213. }
  78214. else {
  78215. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  78216. this._onBeforePhysicsObserver = null;
  78217. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  78218. this._onAfterPhysicsObserver = null;
  78219. }
  78220. },
  78221. enumerable: true,
  78222. configurable: true
  78223. });
  78224. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  78225. /**
  78226. * Gets the perf counter used for animations time
  78227. */
  78228. get: function () {
  78229. return this._animationsTime;
  78230. },
  78231. enumerable: true,
  78232. configurable: true
  78233. });
  78234. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  78235. /**
  78236. * Gets the animations time capture status
  78237. */
  78238. get: function () {
  78239. return this._captureAnimationsTime;
  78240. },
  78241. /**
  78242. * Enable or disable the animations time capture
  78243. */
  78244. set: function (value) {
  78245. var _this = this;
  78246. if (value === this._captureAnimationsTime) {
  78247. return;
  78248. }
  78249. this._captureAnimationsTime = value;
  78250. if (value) {
  78251. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  78252. _this._animationsTime.endMonitoring();
  78253. });
  78254. }
  78255. else {
  78256. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  78257. this._onAfterAnimationsObserver = null;
  78258. }
  78259. },
  78260. enumerable: true,
  78261. configurable: true
  78262. });
  78263. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  78264. /**
  78265. * Gets the perf counter used for frame time capture
  78266. */
  78267. get: function () {
  78268. return this._frameTime;
  78269. },
  78270. enumerable: true,
  78271. configurable: true
  78272. });
  78273. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  78274. /**
  78275. * Gets the frame time capture status
  78276. */
  78277. get: function () {
  78278. return this._captureFrameTime;
  78279. },
  78280. /**
  78281. * Enable or disable the frame time capture
  78282. */
  78283. set: function (value) {
  78284. this._captureFrameTime = value;
  78285. },
  78286. enumerable: true,
  78287. configurable: true
  78288. });
  78289. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  78290. /**
  78291. * Gets the perf counter used for inter-frames time capture
  78292. */
  78293. get: function () {
  78294. return this._interFrameTime;
  78295. },
  78296. enumerable: true,
  78297. configurable: true
  78298. });
  78299. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  78300. /**
  78301. * Gets the inter-frames time capture status
  78302. */
  78303. get: function () {
  78304. return this._captureInterFrameTime;
  78305. },
  78306. /**
  78307. * Enable or disable the inter-frames time capture
  78308. */
  78309. set: function (value) {
  78310. this._captureInterFrameTime = value;
  78311. },
  78312. enumerable: true,
  78313. configurable: true
  78314. });
  78315. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  78316. /**
  78317. * Gets the perf counter used for render time capture
  78318. */
  78319. get: function () {
  78320. return this._renderTime;
  78321. },
  78322. enumerable: true,
  78323. configurable: true
  78324. });
  78325. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  78326. /**
  78327. * Gets the render time capture status
  78328. */
  78329. get: function () {
  78330. return this._captureRenderTime;
  78331. },
  78332. /**
  78333. * Enable or disable the render time capture
  78334. */
  78335. set: function (value) {
  78336. var _this = this;
  78337. if (value === this._captureRenderTime) {
  78338. return;
  78339. }
  78340. this._captureRenderTime = value;
  78341. if (value) {
  78342. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  78343. _this._renderTime.beginMonitoring();
  78344. BABYLON.Tools.StartPerformanceCounter("Main render");
  78345. });
  78346. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  78347. _this._renderTime.endMonitoring(false);
  78348. BABYLON.Tools.EndPerformanceCounter("Main render");
  78349. });
  78350. }
  78351. else {
  78352. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  78353. this._onBeforeDrawPhaseObserver = null;
  78354. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  78355. this._onAfterDrawPhaseObserver = null;
  78356. }
  78357. },
  78358. enumerable: true,
  78359. configurable: true
  78360. });
  78361. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  78362. /**
  78363. * Gets the perf counter used for frame time capture
  78364. */
  78365. get: function () {
  78366. return this.scene.getEngine()._drawCalls;
  78367. },
  78368. enumerable: true,
  78369. configurable: true
  78370. });
  78371. SceneInstrumentation.prototype.dispose = function () {
  78372. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  78373. this._onAfterRenderObserver = null;
  78374. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  78375. this._onBeforeActiveMeshesEvaluationObserver = null;
  78376. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  78377. this._onAfterActiveMeshesEvaluationObserver = null;
  78378. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  78379. this._onBeforeRenderTargetsRenderObserver = null;
  78380. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  78381. this._onAfterRenderTargetsRenderObserver = null;
  78382. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  78383. this._onBeforeAnimationsObserver = null;
  78384. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  78385. this._onBeforeParticlesRenderingObserver = null;
  78386. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  78387. this._onAfterParticlesRenderingObserver = null;
  78388. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  78389. this._onBeforeSpritesRenderingObserver = null;
  78390. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  78391. this._onAfterSpritesRenderingObserver = null;
  78392. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  78393. this._onBeforeDrawPhaseObserver = null;
  78394. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  78395. this._onAfterDrawPhaseObserver = null;
  78396. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  78397. this._onBeforePhysicsObserver = null;
  78398. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  78399. this._onAfterPhysicsObserver = null;
  78400. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  78401. this._onAfterAnimationsObserver = null;
  78402. this.scene = null;
  78403. };
  78404. return SceneInstrumentation;
  78405. }());
  78406. BABYLON.SceneInstrumentation = SceneInstrumentation;
  78407. })(BABYLON || (BABYLON = {}));
  78408. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  78409. var BABYLON;
  78410. (function (BABYLON) {
  78411. var _TimeToken = /** @class */ (function () {
  78412. function _TimeToken() {
  78413. this._timeElapsedQueryEnded = false;
  78414. }
  78415. return _TimeToken;
  78416. }());
  78417. BABYLON._TimeToken = _TimeToken;
  78418. })(BABYLON || (BABYLON = {}));
  78419. //# sourceMappingURL=babylon.timeToken.js.map
  78420. var BABYLON;
  78421. (function (BABYLON) {
  78422. /**
  78423. * Background material defines definition.
  78424. */
  78425. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  78426. __extends(BackgroundMaterialDefines, _super);
  78427. /**
  78428. * Constructor of the defines.
  78429. */
  78430. function BackgroundMaterialDefines() {
  78431. var _this = _super.call(this) || this;
  78432. /**
  78433. * True if the diffuse texture is in use.
  78434. */
  78435. _this.DIFFUSE = false;
  78436. /**
  78437. * The direct UV channel to use.
  78438. */
  78439. _this.DIFFUSEDIRECTUV = 0;
  78440. /**
  78441. * True if the diffuse texture is in gamma space.
  78442. */
  78443. _this.GAMMADIFFUSE = false;
  78444. /**
  78445. * True if the diffuse texture has opacity in the alpha channel.
  78446. */
  78447. _this.DIFFUSEHASALPHA = false;
  78448. /**
  78449. * True if you want the material to fade to transparent at grazing angle.
  78450. */
  78451. _this.OPACITYFRESNEL = false;
  78452. /**
  78453. * True if an extra blur needs to be added in the reflection.
  78454. */
  78455. _this.REFLECTIONBLUR = false;
  78456. /**
  78457. * True if you want the material to fade to reflection at grazing angle.
  78458. */
  78459. _this.REFLECTIONFRESNEL = false;
  78460. /**
  78461. * True if you want the material to falloff as far as you move away from the scene center.
  78462. */
  78463. _this.REFLECTIONFALLOFF = false;
  78464. /**
  78465. * False if the current Webgl implementation does not support the texture lod extension.
  78466. */
  78467. _this.TEXTURELODSUPPORT = false;
  78468. /**
  78469. * True to ensure the data are premultiplied.
  78470. */
  78471. _this.PREMULTIPLYALPHA = false;
  78472. /**
  78473. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  78474. */
  78475. _this.USERGBCOLOR = false;
  78476. /**
  78477. * True to add noise in order to reduce the banding effect.
  78478. */
  78479. _this.NOISE = false;
  78480. // Image Processing Configuration.
  78481. _this.IMAGEPROCESSING = false;
  78482. _this.VIGNETTE = false;
  78483. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  78484. _this.VIGNETTEBLENDMODEOPAQUE = false;
  78485. _this.TONEMAPPING = false;
  78486. _this.CONTRAST = false;
  78487. _this.COLORCURVES = false;
  78488. _this.COLORGRADING = false;
  78489. _this.COLORGRADING3D = false;
  78490. _this.SAMPLER3DGREENDEPTH = false;
  78491. _this.SAMPLER3DBGRMAP = false;
  78492. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  78493. _this.EXPOSURE = false;
  78494. // Reflection.
  78495. _this.REFLECTION = false;
  78496. _this.REFLECTIONMAP_3D = false;
  78497. _this.REFLECTIONMAP_SPHERICAL = false;
  78498. _this.REFLECTIONMAP_PLANAR = false;
  78499. _this.REFLECTIONMAP_CUBIC = false;
  78500. _this.REFLECTIONMAP_PROJECTION = false;
  78501. _this.REFLECTIONMAP_SKYBOX = false;
  78502. _this.REFLECTIONMAP_EXPLICIT = false;
  78503. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  78504. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  78505. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  78506. _this.INVERTCUBICMAP = false;
  78507. _this.REFLECTIONMAP_OPPOSITEZ = false;
  78508. _this.LODINREFLECTIONALPHA = false;
  78509. _this.GAMMAREFLECTION = false;
  78510. // Default BJS.
  78511. _this.MAINUV1 = false;
  78512. _this.MAINUV2 = false;
  78513. _this.UV1 = false;
  78514. _this.UV2 = false;
  78515. _this.CLIPPLANE = false;
  78516. _this.POINTSIZE = false;
  78517. _this.FOG = false;
  78518. _this.NORMAL = false;
  78519. _this.NUM_BONE_INFLUENCERS = 0;
  78520. _this.BonesPerMesh = 0;
  78521. _this.INSTANCES = false;
  78522. _this.SHADOWFLOAT = false;
  78523. _this.rebuild();
  78524. return _this;
  78525. }
  78526. return BackgroundMaterialDefines;
  78527. }(BABYLON.MaterialDefines));
  78528. /**
  78529. * Background material used to create an efficient environement around your scene.
  78530. */
  78531. var BackgroundMaterial = /** @class */ (function (_super) {
  78532. __extends(BackgroundMaterial, _super);
  78533. /**
  78534. * constructor
  78535. * @param name The name of the material
  78536. * @param scene The scene to add the material to
  78537. */
  78538. function BackgroundMaterial(name, scene) {
  78539. var _this = _super.call(this, name, scene) || this;
  78540. _this.primaryColor = BABYLON.Color3.White();
  78541. _this.primaryLevel = 1;
  78542. _this.secondaryColor = BABYLON.Color3.Gray();
  78543. _this.secondaryLevel = 1;
  78544. _this.tertiaryColor = BABYLON.Color3.Black();
  78545. _this.tertiaryLevel = 1;
  78546. _this.reflectionTexture = null;
  78547. _this.reflectionBlur = 0;
  78548. _this.diffuseTexture = null;
  78549. /**
  78550. * Specify the list of lights casting shadow on the material.
  78551. * All scene shadow lights will be included if null.
  78552. */
  78553. _this._shadowLights = null;
  78554. _this.shadowLights = null;
  78555. _this.shadowBlurScale = 1;
  78556. _this.shadowLevel = 0;
  78557. _this.sceneCenter = BABYLON.Vector3.Zero();
  78558. _this.opacityFresnel = true;
  78559. _this.reflectionFresnel = false;
  78560. _this.reflectionFalloffDistance = 0.0;
  78561. _this.reflectionAmount = 1.0;
  78562. _this.reflectionReflectance0 = 0.05;
  78563. _this.reflectionReflectance90 = 0.5;
  78564. _this.useRGBColor = true;
  78565. _this.enableNoise = false;
  78566. /**
  78567. * Number of Simultaneous lights allowed on the material.
  78568. */
  78569. _this._maxSimultaneousLights = 4;
  78570. _this.maxSimultaneousLights = 4;
  78571. /**
  78572. * Keep track of the image processing observer to allow dispose and replace.
  78573. */
  78574. _this._imageProcessingObserver = null;
  78575. // Temp values kept as cache in the material.
  78576. _this._renderTargets = new BABYLON.SmartArray(16);
  78577. _this._reflectionControls = BABYLON.Vector4.Zero();
  78578. // Setup the default processing configuration to the scene.
  78579. _this._attachImageProcessingConfiguration(null);
  78580. _this.getRenderTargetTextures = function () {
  78581. _this._renderTargets.reset();
  78582. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  78583. _this._renderTargets.push(_this._diffuseTexture);
  78584. }
  78585. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  78586. _this._renderTargets.push(_this._reflectionTexture);
  78587. }
  78588. return _this._renderTargets;
  78589. };
  78590. return _this;
  78591. }
  78592. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  78593. /**
  78594. * Sets the reflection reflectance fresnel values according to the default standard
  78595. * empirically know to work well :-)
  78596. */
  78597. set: function (value) {
  78598. var reflectionWeight = value;
  78599. if (reflectionWeight < 0.5) {
  78600. reflectionWeight = reflectionWeight * 2.0;
  78601. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 * reflectionWeight;
  78602. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 * reflectionWeight;
  78603. }
  78604. else {
  78605. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  78606. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 + (1.0 - BackgroundMaterial.standardReflectance0) * reflectionWeight;
  78607. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 + (1.0 - BackgroundMaterial.standardReflectance90) * reflectionWeight;
  78608. }
  78609. },
  78610. enumerable: true,
  78611. configurable: true
  78612. });
  78613. /**
  78614. * Attaches a new image processing configuration to the PBR Material.
  78615. * @param configuration (if null the scene configuration will be use)
  78616. */
  78617. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  78618. var _this = this;
  78619. if (configuration === this._imageProcessingConfiguration) {
  78620. return;
  78621. }
  78622. // Detaches observer.
  78623. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  78624. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  78625. }
  78626. // Pick the scene configuration if needed.
  78627. if (!configuration) {
  78628. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  78629. }
  78630. else {
  78631. this._imageProcessingConfiguration = configuration;
  78632. }
  78633. // Attaches observer.
  78634. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  78635. _this._markAllSubMeshesAsImageProcessingDirty();
  78636. });
  78637. };
  78638. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  78639. /**
  78640. * Gets the image processing configuration used either in this material.
  78641. */
  78642. get: function () {
  78643. return this._imageProcessingConfiguration;
  78644. },
  78645. /**
  78646. * Sets the Default image processing configuration used either in the this material.
  78647. *
  78648. * If sets to null, the scene one is in use.
  78649. */
  78650. set: function (value) {
  78651. this._attachImageProcessingConfiguration(value);
  78652. // Ensure the effect will be rebuilt.
  78653. this._markAllSubMeshesAsTexturesDirty();
  78654. },
  78655. enumerable: true,
  78656. configurable: true
  78657. });
  78658. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  78659. /**
  78660. * Gets wether the color curves effect is enabled.
  78661. */
  78662. get: function () {
  78663. return this.imageProcessingConfiguration.colorCurvesEnabled;
  78664. },
  78665. /**
  78666. * Sets wether the color curves effect is enabled.
  78667. */
  78668. set: function (value) {
  78669. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  78670. },
  78671. enumerable: true,
  78672. configurable: true
  78673. });
  78674. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  78675. /**
  78676. * Gets wether the color grading effect is enabled.
  78677. */
  78678. get: function () {
  78679. return this.imageProcessingConfiguration.colorGradingEnabled;
  78680. },
  78681. /**
  78682. * Gets wether the color grading effect is enabled.
  78683. */
  78684. set: function (value) {
  78685. this.imageProcessingConfiguration.colorGradingEnabled = value;
  78686. },
  78687. enumerable: true,
  78688. configurable: true
  78689. });
  78690. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  78691. /**
  78692. * Gets wether tonemapping is enabled or not.
  78693. */
  78694. get: function () {
  78695. return this._imageProcessingConfiguration.toneMappingEnabled;
  78696. },
  78697. /**
  78698. * Sets wether tonemapping is enabled or not
  78699. */
  78700. set: function (value) {
  78701. this._imageProcessingConfiguration.toneMappingEnabled = value;
  78702. },
  78703. enumerable: true,
  78704. configurable: true
  78705. });
  78706. ;
  78707. ;
  78708. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  78709. /**
  78710. * The camera exposure used on this material.
  78711. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  78712. * This corresponds to a photographic exposure.
  78713. */
  78714. get: function () {
  78715. return this._imageProcessingConfiguration.exposure;
  78716. },
  78717. /**
  78718. * The camera exposure used on this material.
  78719. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  78720. * This corresponds to a photographic exposure.
  78721. */
  78722. set: function (value) {
  78723. this._imageProcessingConfiguration.exposure = value;
  78724. },
  78725. enumerable: true,
  78726. configurable: true
  78727. });
  78728. ;
  78729. ;
  78730. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  78731. /**
  78732. * Gets The camera contrast used on this material.
  78733. */
  78734. get: function () {
  78735. return this._imageProcessingConfiguration.contrast;
  78736. },
  78737. /**
  78738. * Sets The camera contrast used on this material.
  78739. */
  78740. set: function (value) {
  78741. this._imageProcessingConfiguration.contrast = value;
  78742. },
  78743. enumerable: true,
  78744. configurable: true
  78745. });
  78746. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  78747. /**
  78748. * Gets the Color Grading 2D Lookup Texture.
  78749. */
  78750. get: function () {
  78751. return this._imageProcessingConfiguration.colorGradingTexture;
  78752. },
  78753. /**
  78754. * Sets the Color Grading 2D Lookup Texture.
  78755. */
  78756. set: function (value) {
  78757. this.imageProcessingConfiguration.colorGradingTexture = value;
  78758. },
  78759. enumerable: true,
  78760. configurable: true
  78761. });
  78762. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  78763. /**
  78764. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  78765. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  78766. * 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;
  78767. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  78768. */
  78769. get: function () {
  78770. return this.imageProcessingConfiguration.colorCurves;
  78771. },
  78772. /**
  78773. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  78774. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  78775. * 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;
  78776. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  78777. */
  78778. set: function (value) {
  78779. this.imageProcessingConfiguration.colorCurves = value;
  78780. },
  78781. enumerable: true,
  78782. configurable: true
  78783. });
  78784. /**
  78785. * The entire material has been created in order to prevent overdraw.
  78786. * @returns false
  78787. */
  78788. BackgroundMaterial.prototype.needAlphaTesting = function () {
  78789. return true;
  78790. };
  78791. /**
  78792. * The entire material has been created in order to prevent overdraw.
  78793. * @returns true if blending is enable
  78794. */
  78795. BackgroundMaterial.prototype.needAlphaBlending = function () {
  78796. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  78797. };
  78798. /**
  78799. * Checks wether the material is ready to be rendered for a given mesh.
  78800. * @param mesh The mesh to render
  78801. * @param subMesh The submesh to check against
  78802. * @param useInstances Specify wether or not the material is used with instances
  78803. */
  78804. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  78805. var _this = this;
  78806. if (useInstances === void 0) { useInstances = false; }
  78807. if (subMesh.effect && this.isFrozen) {
  78808. if (this._wasPreviouslyReady) {
  78809. return true;
  78810. }
  78811. }
  78812. if (!subMesh._materialDefines) {
  78813. subMesh._materialDefines = new BackgroundMaterialDefines();
  78814. }
  78815. var scene = this.getScene();
  78816. var defines = subMesh._materialDefines;
  78817. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  78818. if (defines._renderId === scene.getRenderId()) {
  78819. return true;
  78820. }
  78821. }
  78822. var engine = scene.getEngine();
  78823. // Lights
  78824. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  78825. defines._needNormals = true;
  78826. // Textures
  78827. if (defines._areTexturesDirty) {
  78828. defines._needUVs = false;
  78829. if (scene.texturesEnabled) {
  78830. if (scene.getEngine().getCaps().textureLOD) {
  78831. defines.TEXTURELODSUPPORT = true;
  78832. }
  78833. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  78834. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  78835. return false;
  78836. }
  78837. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  78838. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  78839. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  78840. defines.OPACITYFRESNEL = this._opacityFresnel;
  78841. }
  78842. else {
  78843. defines.DIFFUSE = false;
  78844. defines.DIFFUSEHASALPHA = false;
  78845. defines.GAMMADIFFUSE = false;
  78846. defines.OPACITYFRESNEL = false;
  78847. }
  78848. var reflectionTexture = this._reflectionTexture;
  78849. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  78850. if (!reflectionTexture.isReadyOrNotBlocking()) {
  78851. return false;
  78852. }
  78853. defines.REFLECTION = true;
  78854. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  78855. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  78856. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  78857. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  78858. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  78859. defines.INVERTCUBICMAP = true;
  78860. }
  78861. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  78862. switch (reflectionTexture.coordinatesMode) {
  78863. case BABYLON.Texture.CUBIC_MODE:
  78864. case BABYLON.Texture.INVCUBIC_MODE:
  78865. defines.REFLECTIONMAP_CUBIC = true;
  78866. break;
  78867. case BABYLON.Texture.EXPLICIT_MODE:
  78868. defines.REFLECTIONMAP_EXPLICIT = true;
  78869. break;
  78870. case BABYLON.Texture.PLANAR_MODE:
  78871. defines.REFLECTIONMAP_PLANAR = true;
  78872. break;
  78873. case BABYLON.Texture.PROJECTION_MODE:
  78874. defines.REFLECTIONMAP_PROJECTION = true;
  78875. break;
  78876. case BABYLON.Texture.SKYBOX_MODE:
  78877. defines.REFLECTIONMAP_SKYBOX = true;
  78878. break;
  78879. case BABYLON.Texture.SPHERICAL_MODE:
  78880. defines.REFLECTIONMAP_SPHERICAL = true;
  78881. break;
  78882. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  78883. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  78884. break;
  78885. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  78886. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  78887. break;
  78888. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  78889. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  78890. break;
  78891. }
  78892. if (this.reflectionFresnel) {
  78893. defines.REFLECTIONFRESNEL = true;
  78894. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  78895. this._reflectionControls.x = this.reflectionAmount;
  78896. this._reflectionControls.y = this.reflectionReflectance0;
  78897. this._reflectionControls.z = this.reflectionReflectance90;
  78898. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  78899. }
  78900. else {
  78901. defines.REFLECTIONFRESNEL = false;
  78902. defines.REFLECTIONFALLOFF = false;
  78903. }
  78904. }
  78905. else {
  78906. defines.REFLECTION = false;
  78907. defines.REFLECTIONFALLOFF = false;
  78908. defines.REFLECTIONBLUR = false;
  78909. defines.REFLECTIONMAP_3D = false;
  78910. defines.REFLECTIONMAP_SPHERICAL = false;
  78911. defines.REFLECTIONMAP_PLANAR = false;
  78912. defines.REFLECTIONMAP_CUBIC = false;
  78913. defines.REFLECTIONMAP_PROJECTION = false;
  78914. defines.REFLECTIONMAP_SKYBOX = false;
  78915. defines.REFLECTIONMAP_EXPLICIT = false;
  78916. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  78917. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  78918. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  78919. defines.INVERTCUBICMAP = false;
  78920. defines.REFLECTIONMAP_OPPOSITEZ = false;
  78921. defines.LODINREFLECTIONALPHA = false;
  78922. defines.GAMMAREFLECTION = false;
  78923. }
  78924. }
  78925. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  78926. defines.USERGBCOLOR = this._useRGBColor;
  78927. defines.NOISE = this._enableNoise;
  78928. }
  78929. if (defines._areImageProcessingDirty) {
  78930. if (!this._imageProcessingConfiguration.isReady()) {
  78931. return false;
  78932. }
  78933. this._imageProcessingConfiguration.prepareDefines(defines);
  78934. }
  78935. // Misc.
  78936. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  78937. // Values that need to be evaluated on every frame
  78938. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, false);
  78939. // Attribs
  78940. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  78941. if (mesh) {
  78942. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  78943. mesh.createNormals(true);
  78944. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  78945. }
  78946. }
  78947. }
  78948. // Get correct effect
  78949. if (defines.isDirty) {
  78950. defines.markAsProcessed();
  78951. scene.resetCachedMaterial();
  78952. // Fallbacks
  78953. var fallbacks = new BABYLON.EffectFallbacks();
  78954. if (defines.FOG) {
  78955. fallbacks.addFallback(0, "FOG");
  78956. }
  78957. if (defines.POINTSIZE) {
  78958. fallbacks.addFallback(1, "POINTSIZE");
  78959. }
  78960. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  78961. if (defines.NUM_BONE_INFLUENCERS > 0) {
  78962. fallbacks.addCPUSkinningFallback(0, mesh);
  78963. }
  78964. //Attributes
  78965. var attribs = [BABYLON.VertexBuffer.PositionKind];
  78966. if (defines.NORMAL) {
  78967. attribs.push(BABYLON.VertexBuffer.NormalKind);
  78968. }
  78969. if (defines.UV1) {
  78970. attribs.push(BABYLON.VertexBuffer.UVKind);
  78971. }
  78972. if (defines.UV2) {
  78973. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78974. }
  78975. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  78976. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  78977. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  78978. "vFogInfos", "vFogColor", "pointSize",
  78979. "vClipPlane", "mBones",
  78980. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  78981. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  78982. "shadowLevel", "alpha",
  78983. "vBackgroundCenter", "vReflectionControl",
  78984. "vDiffuseInfos", "diffuseMatrix",
  78985. ];
  78986. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  78987. var uniformBuffers = ["Material", "Scene"];
  78988. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  78989. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  78990. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  78991. uniformsNames: uniforms,
  78992. uniformBuffersNames: uniformBuffers,
  78993. samplers: samplers,
  78994. defines: defines,
  78995. maxSimultaneousLights: this._maxSimultaneousLights
  78996. });
  78997. var onCompiled = function (effect) {
  78998. if (_this.onCompiled) {
  78999. _this.onCompiled(effect);
  79000. }
  79001. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  79002. };
  79003. var join = defines.toString();
  79004. subMesh.setEffect(scene.getEngine().createEffect("background", {
  79005. attributes: attribs,
  79006. uniformsNames: uniforms,
  79007. uniformBuffersNames: uniformBuffers,
  79008. samplers: samplers,
  79009. defines: join,
  79010. fallbacks: fallbacks,
  79011. onCompiled: onCompiled,
  79012. onError: this.onError,
  79013. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  79014. }, engine), defines);
  79015. this.buildUniformLayout();
  79016. }
  79017. if (!subMesh.effect || !subMesh.effect.isReady()) {
  79018. return false;
  79019. }
  79020. defines._renderId = scene.getRenderId();
  79021. this._wasPreviouslyReady = true;
  79022. return true;
  79023. };
  79024. /**
  79025. * Build the uniform buffer used in the material.
  79026. */
  79027. BackgroundMaterial.prototype.buildUniformLayout = function () {
  79028. // Order is important !
  79029. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  79030. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  79031. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  79032. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  79033. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  79034. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  79035. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  79036. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  79037. this._uniformBuffer.addUniform("pointSize", 1);
  79038. this._uniformBuffer.addUniform("shadowLevel", 1);
  79039. this._uniformBuffer.addUniform("alpha", 1);
  79040. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  79041. this._uniformBuffer.addUniform("vReflectionControl", 4);
  79042. this._uniformBuffer.create();
  79043. };
  79044. /**
  79045. * Unbind the material.
  79046. */
  79047. BackgroundMaterial.prototype.unbind = function () {
  79048. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  79049. this._uniformBuffer.setTexture("diffuseSampler", null);
  79050. }
  79051. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  79052. this._uniformBuffer.setTexture("reflectionSampler", null);
  79053. }
  79054. _super.prototype.unbind.call(this);
  79055. };
  79056. /**
  79057. * Bind only the world matrix to the material.
  79058. * @param world The world matrix to bind.
  79059. */
  79060. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  79061. this._activeEffect.setMatrix("world", world);
  79062. };
  79063. /**
  79064. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  79065. * @param world The world matrix to bind.
  79066. * @param subMesh The submesh to bind for.
  79067. */
  79068. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  79069. var scene = this.getScene();
  79070. var defines = subMesh._materialDefines;
  79071. if (!defines) {
  79072. return;
  79073. }
  79074. var effect = subMesh.effect;
  79075. if (!effect) {
  79076. return;
  79077. }
  79078. this._activeEffect = effect;
  79079. // Matrices
  79080. this.bindOnlyWorldMatrix(world);
  79081. // Bones
  79082. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  79083. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  79084. if (mustRebind) {
  79085. this._uniformBuffer.bindToEffect(effect, "Material");
  79086. this.bindViewProjection(effect);
  79087. var reflectionTexture = this._reflectionTexture;
  79088. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  79089. // Texture uniforms
  79090. if (scene.texturesEnabled) {
  79091. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  79092. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  79093. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  79094. }
  79095. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  79096. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  79097. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  79098. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  79099. }
  79100. }
  79101. if (this.shadowLevel > 0) {
  79102. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  79103. }
  79104. this._uniformBuffer.updateFloat("alpha", this.alpha);
  79105. // Point size
  79106. if (this.pointsCloud) {
  79107. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  79108. }
  79109. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  79110. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  79111. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  79112. }
  79113. // Textures
  79114. if (scene.texturesEnabled) {
  79115. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  79116. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  79117. }
  79118. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  79119. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  79120. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  79121. }
  79122. else if (!defines.REFLECTIONBLUR) {
  79123. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  79124. }
  79125. else {
  79126. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  79127. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  79128. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  79129. }
  79130. if (defines.REFLECTIONFRESNEL) {
  79131. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  79132. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  79133. }
  79134. }
  79135. }
  79136. // Clip plane
  79137. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  79138. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  79139. }
  79140. if (mustRebind || !this.isFrozen) {
  79141. if (scene.lightsEnabled) {
  79142. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  79143. }
  79144. // View
  79145. this.bindView(effect);
  79146. // Fog
  79147. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  79148. // image processing
  79149. this._imageProcessingConfiguration.bind(this._activeEffect);
  79150. }
  79151. this._uniformBuffer.update();
  79152. this._afterBind(mesh);
  79153. };
  79154. /**
  79155. * Dispose the material.
  79156. * @forceDisposeEffect Force disposal of the associated effect.
  79157. * @forceDisposeTextures Force disposal of the associated textures.
  79158. */
  79159. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  79160. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  79161. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  79162. if (forceDisposeTextures) {
  79163. if (this.diffuseTexture) {
  79164. this.diffuseTexture.dispose();
  79165. }
  79166. if (this.reflectionTexture) {
  79167. this.reflectionTexture.dispose();
  79168. }
  79169. }
  79170. this._renderTargets.dispose();
  79171. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  79172. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  79173. }
  79174. _super.prototype.dispose.call(this, forceDisposeEffect);
  79175. };
  79176. /**
  79177. * Clones the material.
  79178. * @name The cloned name.
  79179. * @returns The cloned material.
  79180. */
  79181. BackgroundMaterial.prototype.clone = function (name) {
  79182. var _this = this;
  79183. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  79184. };
  79185. /**
  79186. * Serializes the current material to its JSON representation.
  79187. * @returns The JSON representation.
  79188. */
  79189. BackgroundMaterial.prototype.serialize = function () {
  79190. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  79191. serializationObject.customType = "BABYLON.BackgroundMaterial";
  79192. return serializationObject;
  79193. };
  79194. /**
  79195. * Gets the class name of the material
  79196. * @returns "BackgroundMaterial"
  79197. */
  79198. BackgroundMaterial.prototype.getClassName = function () {
  79199. return "BackgroundMaterial";
  79200. };
  79201. /**
  79202. * Parse a JSON input to create back a background material.
  79203. * @param source
  79204. * @param scene
  79205. * @param rootUrl
  79206. * @returns the instantiated BackgroundMaterial.
  79207. */
  79208. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  79209. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  79210. };
  79211. /**
  79212. * Standard reflectance value at parallel view angle.
  79213. */
  79214. BackgroundMaterial.standardReflectance0 = 0.05;
  79215. /**
  79216. * Standard reflectance value at grazing angle.
  79217. */
  79218. BackgroundMaterial.standardReflectance90 = 0.5;
  79219. __decorate([
  79220. BABYLON.serializeAsColor3()
  79221. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  79222. __decorate([
  79223. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  79224. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  79225. __decorate([
  79226. BABYLON.serialize()
  79227. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  79228. __decorate([
  79229. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  79230. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  79231. __decorate([
  79232. BABYLON.serializeAsColor3()
  79233. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  79234. __decorate([
  79235. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  79236. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  79237. __decorate([
  79238. BABYLON.serialize()
  79239. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  79240. __decorate([
  79241. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  79242. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  79243. __decorate([
  79244. BABYLON.serializeAsColor3()
  79245. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  79246. __decorate([
  79247. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  79248. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  79249. __decorate([
  79250. BABYLON.serialize()
  79251. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  79252. __decorate([
  79253. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  79254. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  79255. __decorate([
  79256. BABYLON.serializeAsTexture()
  79257. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  79258. __decorate([
  79259. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79260. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  79261. __decorate([
  79262. BABYLON.serialize()
  79263. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  79264. __decorate([
  79265. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79266. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  79267. __decorate([
  79268. BABYLON.serializeAsTexture()
  79269. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  79270. __decorate([
  79271. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79272. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  79273. __decorate([
  79274. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79275. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  79276. __decorate([
  79277. BABYLON.serialize()
  79278. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  79279. __decorate([
  79280. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79281. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  79282. __decorate([
  79283. BABYLON.serialize()
  79284. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  79285. __decorate([
  79286. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79287. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  79288. __decorate([
  79289. BABYLON.serializeAsVector3()
  79290. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  79291. __decorate([
  79292. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79293. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  79294. __decorate([
  79295. BABYLON.serialize()
  79296. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  79297. __decorate([
  79298. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79299. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  79300. __decorate([
  79301. BABYLON.serialize()
  79302. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  79303. __decorate([
  79304. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79305. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  79306. __decorate([
  79307. BABYLON.serialize()
  79308. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  79309. __decorate([
  79310. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79311. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  79312. __decorate([
  79313. BABYLON.serialize()
  79314. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  79315. __decorate([
  79316. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79317. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  79318. __decorate([
  79319. BABYLON.serialize()
  79320. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  79321. __decorate([
  79322. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79323. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  79324. __decorate([
  79325. BABYLON.serialize()
  79326. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  79327. __decorate([
  79328. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79329. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  79330. __decorate([
  79331. BABYLON.serialize()
  79332. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  79333. __decorate([
  79334. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79335. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  79336. __decorate([
  79337. BABYLON.serialize()
  79338. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  79339. __decorate([
  79340. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79341. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  79342. __decorate([
  79343. BABYLON.serialize()
  79344. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  79345. __decorate([
  79346. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  79347. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  79348. __decorate([
  79349. BABYLON.serializeAsImageProcessingConfiguration()
  79350. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  79351. return BackgroundMaterial;
  79352. }(BABYLON.PushMaterial));
  79353. BABYLON.BackgroundMaterial = BackgroundMaterial;
  79354. })(BABYLON || (BABYLON = {}));
  79355. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  79356. var __assign = (this && this.__assign) || Object.assign || function(t) {
  79357. for (var s, i = 1, n = arguments.length; i < n; i++) {
  79358. s = arguments[i];
  79359. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  79360. t[p] = s[p];
  79361. }
  79362. return t;
  79363. };
  79364. var BABYLON;
  79365. (function (BABYLON) {
  79366. /**
  79367. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  79368. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  79369. * It also helps with the default setup of your imageProcessing configuration.
  79370. */
  79371. var EnvironmentHelper = /** @class */ (function () {
  79372. /**
  79373. * constructor
  79374. * @param options
  79375. * @param scene The scene to add the material to
  79376. */
  79377. function EnvironmentHelper(options, scene) {
  79378. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  79379. this._scene = scene;
  79380. this._setupBackground();
  79381. this._setupImageProcessing();
  79382. }
  79383. /**
  79384. * Creates the default options for the helper.
  79385. */
  79386. EnvironmentHelper._getDefaultOptions = function () {
  79387. return {
  79388. createGround: true,
  79389. groundSize: 15,
  79390. groundTexture: this._groundTextureCDNUrl,
  79391. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  79392. groundOpacity: 0.9,
  79393. enableGroundShadow: true,
  79394. groundShadowLevel: 0.5,
  79395. enableGroundMirror: false,
  79396. groundMirrorSizeRatio: 0.3,
  79397. groundMirrorBlurKernel: 64,
  79398. groundMirrorAmount: 1,
  79399. groundMirrorFresnelWeight: 1,
  79400. groundMirrorFallOffDistance: 0,
  79401. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  79402. createSkybox: true,
  79403. skyboxSize: 20,
  79404. skyboxTexture: this._skyboxTextureCDNUrl,
  79405. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  79406. backgroundYRotation: 0,
  79407. sizeAuto: true,
  79408. rootPosition: BABYLON.Vector3.Zero(),
  79409. setupImageProcessing: true,
  79410. environmentTexture: this._environmentTextureCDNUrl,
  79411. cameraExposure: 0.8,
  79412. cameraContrast: 1.2,
  79413. toneMappingEnabled: true,
  79414. };
  79415. };
  79416. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  79417. /**
  79418. * Gets the root mesh created by the helper.
  79419. */
  79420. get: function () {
  79421. return this._rootMesh;
  79422. },
  79423. enumerable: true,
  79424. configurable: true
  79425. });
  79426. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  79427. /**
  79428. * Gets the skybox created by the helper.
  79429. */
  79430. get: function () {
  79431. return this._skybox;
  79432. },
  79433. enumerable: true,
  79434. configurable: true
  79435. });
  79436. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  79437. /**
  79438. * Gets the skybox texture created by the helper.
  79439. */
  79440. get: function () {
  79441. return this._skyboxTexture;
  79442. },
  79443. enumerable: true,
  79444. configurable: true
  79445. });
  79446. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  79447. /**
  79448. * Gets the skybox material created by the helper.
  79449. */
  79450. get: function () {
  79451. return this._skyboxMaterial;
  79452. },
  79453. enumerable: true,
  79454. configurable: true
  79455. });
  79456. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  79457. /**
  79458. * Gets the ground mesh created by the helper.
  79459. */
  79460. get: function () {
  79461. return this._ground;
  79462. },
  79463. enumerable: true,
  79464. configurable: true
  79465. });
  79466. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  79467. /**
  79468. * Gets the ground texture created by the helper.
  79469. */
  79470. get: function () {
  79471. return this._groundTexture;
  79472. },
  79473. enumerable: true,
  79474. configurable: true
  79475. });
  79476. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  79477. /**
  79478. * Gets the ground mirror created by the helper.
  79479. */
  79480. get: function () {
  79481. return this._groundMirror;
  79482. },
  79483. enumerable: true,
  79484. configurable: true
  79485. });
  79486. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  79487. /**
  79488. * Gets the ground mirror render list to helps pushing the meshes
  79489. * you wish in the ground reflection.
  79490. */
  79491. get: function () {
  79492. if (this._groundMirror) {
  79493. return this._groundMirror.renderList;
  79494. }
  79495. return null;
  79496. },
  79497. enumerable: true,
  79498. configurable: true
  79499. });
  79500. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  79501. /**
  79502. * Gets the ground material created by the helper.
  79503. */
  79504. get: function () {
  79505. return this._groundMaterial;
  79506. },
  79507. enumerable: true,
  79508. configurable: true
  79509. });
  79510. /**
  79511. * Updates the background according to the new options
  79512. * @param options
  79513. */
  79514. EnvironmentHelper.prototype.updateOptions = function (options) {
  79515. var newOptions = __assign({}, this._options, options);
  79516. if (this._ground && !newOptions.createGround) {
  79517. this._ground.dispose();
  79518. this._ground = null;
  79519. }
  79520. if (this._groundMaterial && !newOptions.createGround) {
  79521. this._groundMaterial.dispose();
  79522. this._groundMaterial = null;
  79523. }
  79524. if (this._groundTexture) {
  79525. if (this._options.groundTexture != newOptions.groundTexture) {
  79526. this._groundTexture.dispose();
  79527. this._groundTexture = null;
  79528. }
  79529. }
  79530. if (this._skybox && !newOptions.createSkybox) {
  79531. this._skybox.dispose();
  79532. this._skybox = null;
  79533. }
  79534. if (this._skyboxMaterial && !newOptions.createSkybox) {
  79535. this._skyboxMaterial.dispose();
  79536. this._skyboxMaterial = null;
  79537. }
  79538. if (this._skyboxTexture) {
  79539. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  79540. this._skyboxTexture.dispose();
  79541. this._skyboxTexture = null;
  79542. }
  79543. }
  79544. if (this._groundMirror && !newOptions.enableGroundMirror) {
  79545. this._groundMirror.dispose();
  79546. this._groundMirror = null;
  79547. }
  79548. if (this._scene.environmentTexture) {
  79549. if (this._options.environmentTexture != newOptions.environmentTexture) {
  79550. this._scene.environmentTexture.dispose();
  79551. }
  79552. }
  79553. this._options = newOptions;
  79554. this._setupBackground();
  79555. this._setupImageProcessing();
  79556. };
  79557. /**
  79558. * Sets the primary color of all the available elements.
  79559. * @param color
  79560. */
  79561. EnvironmentHelper.prototype.setMainColor = function (color) {
  79562. if (this.groundMaterial) {
  79563. this.groundMaterial.primaryColor = color;
  79564. }
  79565. if (this.skyboxMaterial) {
  79566. this.skyboxMaterial.primaryColor = color;
  79567. }
  79568. if (this.groundMirror) {
  79569. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  79570. }
  79571. };
  79572. /**
  79573. * Setup the image processing according to the specified options.
  79574. */
  79575. EnvironmentHelper.prototype._setupImageProcessing = function () {
  79576. if (this._options.setupImageProcessing) {
  79577. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  79578. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  79579. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  79580. this._setupEnvironmentTexture();
  79581. }
  79582. };
  79583. /**
  79584. * Setup the environment texture according to the specified options.
  79585. */
  79586. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  79587. if (this._scene.environmentTexture) {
  79588. return;
  79589. }
  79590. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  79591. this._scene.environmentTexture = this._options.environmentTexture;
  79592. return;
  79593. }
  79594. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  79595. this._scene.environmentTexture = environmentTexture;
  79596. };
  79597. /**
  79598. * Setup the background according to the specified options.
  79599. */
  79600. EnvironmentHelper.prototype._setupBackground = function () {
  79601. if (!this._rootMesh) {
  79602. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  79603. }
  79604. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  79605. var sceneSize = this._getSceneSize();
  79606. if (this._options.createGround) {
  79607. this._setupGround(sceneSize);
  79608. this._setupGroundMaterial();
  79609. this._setupGroundDiffuseTexture();
  79610. if (this._options.enableGroundMirror) {
  79611. this._setupGroundMirrorTexture(sceneSize);
  79612. }
  79613. this._setupMirrorInGroundMaterial();
  79614. }
  79615. if (this._options.createSkybox) {
  79616. this._setupSkybox(sceneSize);
  79617. this._setupSkyboxMaterial();
  79618. this._setupSkyboxReflectionTexture();
  79619. }
  79620. this._rootMesh.position.x = sceneSize.rootPosition.x;
  79621. this._rootMesh.position.z = sceneSize.rootPosition.z;
  79622. this._rootMesh.position.y = sceneSize.rootPosition.y;
  79623. };
  79624. /**
  79625. * Get the scene sizes according to the setup.
  79626. */
  79627. EnvironmentHelper.prototype._getSceneSize = function () {
  79628. var groundSize = this._options.groundSize;
  79629. var skyboxSize = this._options.skyboxSize;
  79630. var rootPosition = this._options.rootPosition;
  79631. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  79632. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  79633. }
  79634. var sceneExtends = this._scene.getWorldExtends();
  79635. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  79636. var bias = 0.0001;
  79637. if (this._options.sizeAuto) {
  79638. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  79639. this._scene.activeCamera.upperRadiusLimit) {
  79640. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  79641. }
  79642. if (this._scene.activeCamera) {
  79643. bias = (this._scene.activeCamera.maxZ - this._scene.activeCamera.minZ) / 10000;
  79644. }
  79645. var sceneDiagonalLenght = sceneDiagonal.length();
  79646. if (sceneDiagonalLenght > groundSize) {
  79647. groundSize = sceneDiagonalLenght * 2;
  79648. }
  79649. // 10 % bigger.
  79650. groundSize *= 1.1;
  79651. skyboxSize *= 1.5;
  79652. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  79653. rootPosition.y = sceneExtends.min.y - bias;
  79654. }
  79655. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  79656. };
  79657. /**
  79658. * Setup the ground according to the specified options.
  79659. */
  79660. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  79661. var _this = this;
  79662. if (!this._ground) {
  79663. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  79664. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  79665. this._ground.parent = this._rootMesh;
  79666. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  79667. }
  79668. this._ground.receiveShadows = this._options.enableGroundShadow;
  79669. };
  79670. /**
  79671. * Setup the ground material according to the specified options.
  79672. */
  79673. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  79674. if (!this._groundMaterial) {
  79675. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  79676. }
  79677. this._groundMaterial.alpha = this._options.groundOpacity;
  79678. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  79679. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  79680. this._groundMaterial.primaryLevel = 1;
  79681. this._groundMaterial.primaryColor = this._options.groundColor;
  79682. this._groundMaterial.secondaryLevel = 0;
  79683. this._groundMaterial.tertiaryLevel = 0;
  79684. this._groundMaterial.useRGBColor = false;
  79685. this._groundMaterial.enableNoise = true;
  79686. if (this._ground) {
  79687. this._ground.material = this._groundMaterial;
  79688. }
  79689. };
  79690. /**
  79691. * Setup the ground diffuse texture according to the specified options.
  79692. */
  79693. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  79694. if (!this._groundMaterial) {
  79695. return;
  79696. }
  79697. if (this._groundTexture) {
  79698. return;
  79699. }
  79700. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  79701. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  79702. return;
  79703. }
  79704. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  79705. diffuseTexture.gammaSpace = false;
  79706. diffuseTexture.hasAlpha = true;
  79707. this._groundMaterial.diffuseTexture = diffuseTexture;
  79708. };
  79709. /**
  79710. * Setup the ground mirror texture according to the specified options.
  79711. */
  79712. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  79713. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79714. if (!this._groundMirror) {
  79715. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  79716. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  79717. this._groundMirror.anisotropicFilteringLevel = 1;
  79718. this._groundMirror.wrapU = wrapping;
  79719. this._groundMirror.wrapV = wrapping;
  79720. this._groundMirror.gammaSpace = false;
  79721. if (this._groundMirror.renderList) {
  79722. for (var i = 0; i < this._scene.meshes.length; i++) {
  79723. var mesh = this._scene.meshes[i];
  79724. if (mesh !== this._ground &&
  79725. mesh !== this._skybox &&
  79726. mesh !== this._rootMesh) {
  79727. this._groundMirror.renderList.push(mesh);
  79728. }
  79729. }
  79730. }
  79731. }
  79732. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  79733. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  79734. };
  79735. /**
  79736. * Setup the ground to receive the mirror texture.
  79737. */
  79738. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  79739. if (this._groundMaterial) {
  79740. this._groundMaterial.reflectionTexture = this._groundMirror;
  79741. this._groundMaterial.reflectionFresnel = true;
  79742. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  79743. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  79744. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  79745. }
  79746. };
  79747. /**
  79748. * Setup the skybox according to the specified options.
  79749. */
  79750. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  79751. var _this = this;
  79752. if (!this._skybox) {
  79753. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  79754. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  79755. }
  79756. this._skybox.parent = this._rootMesh;
  79757. };
  79758. /**
  79759. * Setup the skybox material according to the specified options.
  79760. */
  79761. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  79762. if (!this._skybox) {
  79763. return;
  79764. }
  79765. if (!this._skyboxMaterial) {
  79766. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  79767. }
  79768. this._skyboxMaterial.useRGBColor = false;
  79769. this._skyboxMaterial.primaryLevel = 1;
  79770. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  79771. this._skyboxMaterial.secondaryLevel = 0;
  79772. this._skyboxMaterial.tertiaryLevel = 0;
  79773. this._skyboxMaterial.enableNoise = true;
  79774. this._skybox.material = this._skyboxMaterial;
  79775. };
  79776. /**
  79777. * Setup the skybox reflection texture according to the specified options.
  79778. */
  79779. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  79780. if (!this._skyboxMaterial) {
  79781. return;
  79782. }
  79783. if (this._skyboxTexture) {
  79784. return;
  79785. }
  79786. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  79787. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  79788. return;
  79789. }
  79790. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  79791. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  79792. this._skyboxTexture.gammaSpace = false;
  79793. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  79794. };
  79795. /**
  79796. * Dispose all the elements created by the Helper.
  79797. */
  79798. EnvironmentHelper.prototype.dispose = function () {
  79799. if (this._groundMaterial) {
  79800. this._groundMaterial.dispose(true, true);
  79801. }
  79802. if (this._skyboxMaterial) {
  79803. this._skyboxMaterial.dispose(true, true);
  79804. }
  79805. this._rootMesh.dispose(false);
  79806. };
  79807. /**
  79808. * Default ground texture URL.
  79809. */
  79810. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  79811. /**
  79812. * Default skybox texture URL.
  79813. */
  79814. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  79815. /**
  79816. * Default environment texture URL.
  79817. */
  79818. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  79819. return EnvironmentHelper;
  79820. }());
  79821. BABYLON.EnvironmentHelper = EnvironmentHelper;
  79822. })(BABYLON || (BABYLON = {}));
  79823. //# sourceMappingURL=babylon.environmentHelper.js.map
  79824. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\ngl_FragColor=color;\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=abs(texture2D(textureSampler,vUV).r);\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,1.0);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb=dither(vPositionW.xy,color.rgb);\n#endif\ngl_FragColor=color;\n}"};
  79825. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor+=mix(-0.5/255.0,0.5/255.0,rand);\ncolor=max(color,0.0);\nreturn color;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*KERNEL_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n#endif","kernelBlurFragment2":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*KERNEL_DEP_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  79826. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  79827. var BABYLON;
  79828. (function (BABYLON) {
  79829. var GridMaterialDefines = /** @class */ (function (_super) {
  79830. __extends(GridMaterialDefines, _super);
  79831. function GridMaterialDefines() {
  79832. var _this = _super.call(this) || this;
  79833. _this.TRANSPARENT = false;
  79834. _this.FOG = false;
  79835. _this.PREMULTIPLYALPHA = false;
  79836. _this.rebuild();
  79837. return _this;
  79838. }
  79839. return GridMaterialDefines;
  79840. }(BABYLON.MaterialDefines));
  79841. /**
  79842. * The grid materials allows you to wrap any shape with a grid.
  79843. * Colors are customizable.
  79844. */
  79845. var GridMaterial = /** @class */ (function (_super) {
  79846. __extends(GridMaterial, _super);
  79847. /**
  79848. * constructor
  79849. * @param name The name given to the material in order to identify it afterwards.
  79850. * @param scene The scene the material is used in.
  79851. */
  79852. function GridMaterial(name, scene) {
  79853. var _this = _super.call(this, name, scene) || this;
  79854. /**
  79855. * Main color of the grid (e.g. between lines)
  79856. */
  79857. _this.mainColor = BABYLON.Color3.Black();
  79858. /**
  79859. * Color of the grid lines.
  79860. */
  79861. _this.lineColor = BABYLON.Color3.Teal();
  79862. /**
  79863. * The scale of the grid compared to unit.
  79864. */
  79865. _this.gridRatio = 1.0;
  79866. /**
  79867. * Allows setting an offset for the grid lines.
  79868. */
  79869. _this.gridOffset = BABYLON.Vector3.Zero();
  79870. /**
  79871. * The frequency of thicker lines.
  79872. */
  79873. _this.majorUnitFrequency = 10;
  79874. /**
  79875. * The visibility of minor units in the grid.
  79876. */
  79877. _this.minorUnitVisibility = 0.33;
  79878. /**
  79879. * The grid opacity outside of the lines.
  79880. */
  79881. _this.opacity = 1.0;
  79882. /**
  79883. * Determine RBG output is premultiplied by alpha value.
  79884. */
  79885. _this.preMultiplyAlpha = false;
  79886. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  79887. return _this;
  79888. }
  79889. /**
  79890. * Returns wehter or not the grid requires alpha blending.
  79891. */
  79892. GridMaterial.prototype.needAlphaBlending = function () {
  79893. return this.opacity < 1.0;
  79894. };
  79895. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  79896. return this.needAlphaBlending();
  79897. };
  79898. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  79899. if (this.isFrozen) {
  79900. if (this._wasPreviouslyReady && subMesh.effect) {
  79901. return true;
  79902. }
  79903. }
  79904. if (!subMesh._materialDefines) {
  79905. subMesh._materialDefines = new GridMaterialDefines();
  79906. }
  79907. var defines = subMesh._materialDefines;
  79908. var scene = this.getScene();
  79909. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  79910. if (this._renderId === scene.getRenderId()) {
  79911. return true;
  79912. }
  79913. }
  79914. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  79915. defines.TRANSPARENT = !defines.TRANSPARENT;
  79916. defines.markAsUnprocessed();
  79917. }
  79918. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  79919. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  79920. defines.markAsUnprocessed();
  79921. }
  79922. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  79923. // Get correct effect
  79924. if (defines.isDirty) {
  79925. defines.markAsProcessed();
  79926. scene.resetCachedMaterial();
  79927. // Attributes
  79928. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  79929. // Defines
  79930. var join = defines.toString();
  79931. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  79932. }
  79933. if (!subMesh.effect || !subMesh.effect.isReady()) {
  79934. return false;
  79935. }
  79936. this._renderId = scene.getRenderId();
  79937. this._wasPreviouslyReady = true;
  79938. return true;
  79939. };
  79940. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  79941. var scene = this.getScene();
  79942. var defines = subMesh._materialDefines;
  79943. if (!defines) {
  79944. return;
  79945. }
  79946. var effect = subMesh.effect;
  79947. if (!effect) {
  79948. return;
  79949. }
  79950. this._activeEffect = effect;
  79951. // Matrices
  79952. this.bindOnlyWorldMatrix(world);
  79953. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  79954. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  79955. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  79956. // Uniforms
  79957. if (this._mustRebind(scene, effect)) {
  79958. this._activeEffect.setColor3("mainColor", this.mainColor);
  79959. this._activeEffect.setColor3("lineColor", this.lineColor);
  79960. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  79961. this._gridControl.x = this.gridRatio;
  79962. this._gridControl.y = Math.round(this.majorUnitFrequency);
  79963. this._gridControl.z = this.minorUnitVisibility;
  79964. this._gridControl.w = this.opacity;
  79965. this._activeEffect.setVector4("gridControl", this._gridControl);
  79966. }
  79967. // Fog
  79968. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  79969. this._afterBind(mesh, this._activeEffect);
  79970. };
  79971. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  79972. _super.prototype.dispose.call(this, forceDisposeEffect);
  79973. };
  79974. GridMaterial.prototype.clone = function (name) {
  79975. var _this = this;
  79976. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  79977. };
  79978. GridMaterial.prototype.serialize = function () {
  79979. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  79980. serializationObject.customType = "BABYLON.GridMaterial";
  79981. return serializationObject;
  79982. };
  79983. GridMaterial.prototype.getClassName = function () {
  79984. return "GridMaterial";
  79985. };
  79986. GridMaterial.Parse = function (source, scene, rootUrl) {
  79987. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  79988. };
  79989. __decorate([
  79990. BABYLON.serializeAsColor3()
  79991. ], GridMaterial.prototype, "mainColor", void 0);
  79992. __decorate([
  79993. BABYLON.serializeAsColor3()
  79994. ], GridMaterial.prototype, "lineColor", void 0);
  79995. __decorate([
  79996. BABYLON.serialize()
  79997. ], GridMaterial.prototype, "gridRatio", void 0);
  79998. __decorate([
  79999. BABYLON.serializeAsColor3()
  80000. ], GridMaterial.prototype, "gridOffset", void 0);
  80001. __decorate([
  80002. BABYLON.serialize()
  80003. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  80004. __decorate([
  80005. BABYLON.serialize()
  80006. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  80007. __decorate([
  80008. BABYLON.serialize()
  80009. ], GridMaterial.prototype, "opacity", void 0);
  80010. __decorate([
  80011. BABYLON.serialize()
  80012. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  80013. return GridMaterial;
  80014. }(BABYLON.PushMaterial));
  80015. BABYLON.GridMaterial = GridMaterial;
  80016. })(BABYLON || (BABYLON = {}));
  80017. //# sourceMappingURL=babylon.gridmaterial.js.map
  80018. BABYLON.Effect.ShadersStore['gridVertexShader'] = "precision highp float;\n\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 projection;\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 worldView;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogVertexDeclaration>\nvoid main(void) {\n#ifdef FOG\nvec4 worldPos=world*vec4(position,1.0);\n#endif\n#include<fogVertex>\nvec4 cameraSpacePosition=worldView*vec4(position,1.0);\ngl_Position=projection*cameraSpacePosition;\n#ifdef TRANSPARENT\nvCameraSpacePosition=cameraSpacePosition;\n#endif\nvPosition=position;\nvNormal=normal;\n}";
  80019. BABYLON.Effect.ShadersStore['gridPixelShader'] = "#extension GL_OES_standard_derivatives : enable\n#define SQRT2 1.41421356\n#define PI 3.14159\nprecision highp float;\nuniform vec3 mainColor;\nuniform vec3 lineColor;\nuniform vec4 gridControl;\nuniform vec3 gridOffset;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogFragmentDeclaration>\nfloat getVisibility(float position) {\n\nfloat majorGridFrequency=gridControl.y;\nif (floor(position+0.5) == floor(position/majorGridFrequency+0.5)*majorGridFrequency)\n{\nreturn 1.0;\n} \nreturn gridControl.z;\n}\nfloat getAnisotropicAttenuation(float differentialLength) {\nconst float maxNumberOfLines=10.0;\nreturn clamp(1.0/(differentialLength+1.0)-1.0/maxNumberOfLines,0.0,1.0);\n}\nfloat isPointOnLine(float position,float differentialLength) {\nfloat fractionPartOfPosition=position-floor(position+0.5); \nfractionPartOfPosition/=differentialLength; \nfractionPartOfPosition=clamp(fractionPartOfPosition,-1.,1.);\nfloat result=0.5+0.5*cos(fractionPartOfPosition*PI); \nreturn result; \n}\nfloat contributionOnAxis(float position) {\nfloat differentialLength=length(vec2(dFdx(position),dFdy(position)));\ndifferentialLength*=SQRT2; \n\nfloat result=isPointOnLine(position,differentialLength);\n\nfloat visibility=getVisibility(position);\nresult*=visibility;\n\nfloat anisotropicAttenuation=getAnisotropicAttenuation(differentialLength);\nresult*=anisotropicAttenuation;\nreturn result;\n}\nfloat normalImpactOnAxis(float x) {\nfloat normalImpact=clamp(1.0-3.0*abs(x*x*x),0.0,1.0);\nreturn normalImpact;\n}\nvoid main(void) {\n\nfloat gridRatio=gridControl.x;\nvec3 gridPos=(vPosition+gridOffset)/gridRatio;\n\nfloat x=contributionOnAxis(gridPos.x);\nfloat y=contributionOnAxis(gridPos.y);\nfloat z=contributionOnAxis(gridPos.z);\n\nvec3 normal=normalize(vNormal);\nx*=normalImpactOnAxis(normal.x);\ny*=normalImpactOnAxis(normal.y);\nz*=normalImpactOnAxis(normal.z);\n\nfloat grid=clamp(x+y+z,0.,1.);\n\nvec3 color=mix(mainColor,lineColor,grid);\n#ifdef FOG\n#include<fogFragment>\n#endif\n#ifdef TRANSPARENT\nfloat distanceToFragment=length(vCameraSpacePosition.xyz);\nfloat cameraPassThrough=clamp(distanceToFragment-0.25,0.0,1.0);\nfloat opacity=clamp(grid,0.08,cameraPassThrough*gridControl.w*grid);\ngl_FragColor=vec4(color.rgb,opacity);\n#ifdef PREMULTIPLYALPHA\ngl_FragColor.rgb*=opacity;\n#endif\n#else\n\ngl_FragColor=vec4(color.rgb,1.0);\n#endif\n}";
  80020. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  80021. var BABYLON;
  80022. (function (BABYLON) {
  80023. var GLTFLoaderCoordinateSystemMode;
  80024. (function (GLTFLoaderCoordinateSystemMode) {
  80025. /**
  80026. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  80027. */
  80028. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  80029. /**
  80030. * Sets the useRightHandedSystem flag on the scene.
  80031. */
  80032. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  80033. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  80034. var GLTFLoaderAnimationStartMode;
  80035. (function (GLTFLoaderAnimationStartMode) {
  80036. /**
  80037. * No animation will start.
  80038. */
  80039. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  80040. /**
  80041. * The first animation will start.
  80042. */
  80043. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  80044. /**
  80045. * All animations will start.
  80046. */
  80047. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  80048. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  80049. var GLTFFileLoader = /** @class */ (function () {
  80050. function GLTFFileLoader() {
  80051. // #endregion
  80052. // #region V2 options
  80053. /**
  80054. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  80055. */
  80056. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  80057. /**
  80058. * The animation start mode (NONE, FIRST, ALL).
  80059. */
  80060. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  80061. /**
  80062. * Set to true to compile materials before raising the success callback.
  80063. */
  80064. this.compileMaterials = false;
  80065. /**
  80066. * Set to true to also compile materials with clip planes.
  80067. */
  80068. this.useClipPlane = false;
  80069. /**
  80070. * Set to true to compile shadow generators before raising the success callback.
  80071. */
  80072. this.compileShadowGenerators = false;
  80073. this.name = "gltf";
  80074. this.extensions = {
  80075. ".gltf": { isBinary: false },
  80076. ".glb": { isBinary: true }
  80077. };
  80078. }
  80079. /**
  80080. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  80081. */
  80082. GLTFFileLoader.prototype.dispose = function () {
  80083. if (this._loader) {
  80084. this._loader.dispose();
  80085. }
  80086. };
  80087. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  80088. try {
  80089. var loaderData = GLTFFileLoader._parse(data);
  80090. if (this.onParsed) {
  80091. this.onParsed(loaderData);
  80092. }
  80093. this._loader = this._getLoader(loaderData);
  80094. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  80095. }
  80096. catch (e) {
  80097. if (onError) {
  80098. onError(e.message, e);
  80099. }
  80100. else {
  80101. BABYLON.Tools.Error(e.message);
  80102. }
  80103. }
  80104. };
  80105. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  80106. try {
  80107. var loaderData = GLTFFileLoader._parse(data);
  80108. if (this.onParsed) {
  80109. this.onParsed(loaderData);
  80110. }
  80111. this._loader = this._getLoader(loaderData);
  80112. this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  80113. }
  80114. catch (e) {
  80115. if (onError) {
  80116. onError(e.message, e);
  80117. }
  80118. else {
  80119. BABYLON.Tools.Error(e.message);
  80120. }
  80121. }
  80122. };
  80123. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  80124. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  80125. };
  80126. GLTFFileLoader.prototype.createPlugin = function () {
  80127. return new GLTFFileLoader();
  80128. };
  80129. GLTFFileLoader._parse = function (data) {
  80130. if (data instanceof ArrayBuffer) {
  80131. return GLTFFileLoader._parseBinary(data);
  80132. }
  80133. return {
  80134. json: JSON.parse(data),
  80135. bin: null
  80136. };
  80137. };
  80138. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  80139. var loaderVersion = { major: 2, minor: 0 };
  80140. var asset = loaderData.json.asset || {};
  80141. var version = GLTFFileLoader._parseVersion(asset.version);
  80142. if (!version) {
  80143. throw new Error("Invalid version: " + asset.version);
  80144. }
  80145. if (asset.minVersion !== undefined) {
  80146. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  80147. if (!minVersion) {
  80148. throw new Error("Invalid minimum version: " + asset.minVersion);
  80149. }
  80150. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  80151. throw new Error("Incompatible minimum version: " + asset.minVersion);
  80152. }
  80153. }
  80154. var createLoaders = {
  80155. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  80156. 2: GLTFFileLoader.CreateGLTFLoaderV2
  80157. };
  80158. var createLoader = createLoaders[version.major];
  80159. if (!createLoader) {
  80160. throw new Error("Unsupported version: " + asset.version);
  80161. }
  80162. return createLoader(this);
  80163. };
  80164. GLTFFileLoader._parseBinary = function (data) {
  80165. var Binary = {
  80166. Magic: 0x46546C67
  80167. };
  80168. var binaryReader = new BinaryReader(data);
  80169. var magic = binaryReader.readUint32();
  80170. if (magic !== Binary.Magic) {
  80171. throw new Error("Unexpected magic: " + magic);
  80172. }
  80173. var version = binaryReader.readUint32();
  80174. switch (version) {
  80175. case 1: return GLTFFileLoader._parseV1(binaryReader);
  80176. case 2: return GLTFFileLoader._parseV2(binaryReader);
  80177. }
  80178. throw new Error("Unsupported version: " + version);
  80179. };
  80180. GLTFFileLoader._parseV1 = function (binaryReader) {
  80181. var ContentFormat = {
  80182. JSON: 0
  80183. };
  80184. var length = binaryReader.readUint32();
  80185. if (length != binaryReader.getLength()) {
  80186. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  80187. }
  80188. var contentLength = binaryReader.readUint32();
  80189. var contentFormat = binaryReader.readUint32();
  80190. var content;
  80191. switch (contentFormat) {
  80192. case ContentFormat.JSON: {
  80193. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  80194. break;
  80195. }
  80196. default: {
  80197. throw new Error("Unexpected content format: " + contentFormat);
  80198. }
  80199. }
  80200. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  80201. var body = binaryReader.readUint8Array(bytesRemaining);
  80202. return {
  80203. json: content,
  80204. bin: body
  80205. };
  80206. };
  80207. GLTFFileLoader._parseV2 = function (binaryReader) {
  80208. var ChunkFormat = {
  80209. JSON: 0x4E4F534A,
  80210. BIN: 0x004E4942
  80211. };
  80212. var length = binaryReader.readUint32();
  80213. if (length !== binaryReader.getLength()) {
  80214. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  80215. }
  80216. // JSON chunk
  80217. var chunkLength = binaryReader.readUint32();
  80218. var chunkFormat = binaryReader.readUint32();
  80219. if (chunkFormat !== ChunkFormat.JSON) {
  80220. throw new Error("First chunk format is not JSON");
  80221. }
  80222. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  80223. // Look for BIN chunk
  80224. var bin = null;
  80225. while (binaryReader.getPosition() < binaryReader.getLength()) {
  80226. var chunkLength_1 = binaryReader.readUint32();
  80227. var chunkFormat_1 = binaryReader.readUint32();
  80228. switch (chunkFormat_1) {
  80229. case ChunkFormat.JSON: {
  80230. throw new Error("Unexpected JSON chunk");
  80231. }
  80232. case ChunkFormat.BIN: {
  80233. bin = binaryReader.readUint8Array(chunkLength_1);
  80234. break;
  80235. }
  80236. default: {
  80237. // ignore unrecognized chunkFormat
  80238. binaryReader.skipBytes(chunkLength_1);
  80239. break;
  80240. }
  80241. }
  80242. }
  80243. return {
  80244. json: json,
  80245. bin: bin
  80246. };
  80247. };
  80248. GLTFFileLoader._parseVersion = function (version) {
  80249. if (version === "1.0" || version === "1.0.1") {
  80250. return {
  80251. major: 1,
  80252. minor: 0
  80253. };
  80254. }
  80255. var match = (version + "").match(/^(\d+)\.(\d+)/);
  80256. if (!match) {
  80257. return null;
  80258. }
  80259. return {
  80260. major: parseInt(match[1]),
  80261. minor: parseInt(match[2])
  80262. };
  80263. };
  80264. GLTFFileLoader._compareVersion = function (a, b) {
  80265. if (a.major > b.major)
  80266. return 1;
  80267. if (a.major < b.major)
  80268. return -1;
  80269. if (a.minor > b.minor)
  80270. return 1;
  80271. if (a.minor < b.minor)
  80272. return -1;
  80273. return 0;
  80274. };
  80275. GLTFFileLoader._decodeBufferToText = function (buffer) {
  80276. var result = "";
  80277. var length = buffer.byteLength;
  80278. for (var i = 0; i < length; i++) {
  80279. result += String.fromCharCode(buffer[i]);
  80280. }
  80281. return result;
  80282. };
  80283. // #endregion
  80284. // #region V1 options
  80285. GLTFFileLoader.IncrementalLoading = true;
  80286. GLTFFileLoader.HomogeneousCoordinates = false;
  80287. return GLTFFileLoader;
  80288. }());
  80289. BABYLON.GLTFFileLoader = GLTFFileLoader;
  80290. var BinaryReader = /** @class */ (function () {
  80291. function BinaryReader(arrayBuffer) {
  80292. this._arrayBuffer = arrayBuffer;
  80293. this._dataView = new DataView(arrayBuffer);
  80294. this._byteOffset = 0;
  80295. }
  80296. BinaryReader.prototype.getPosition = function () {
  80297. return this._byteOffset;
  80298. };
  80299. BinaryReader.prototype.getLength = function () {
  80300. return this._arrayBuffer.byteLength;
  80301. };
  80302. BinaryReader.prototype.readUint32 = function () {
  80303. var value = this._dataView.getUint32(this._byteOffset, true);
  80304. this._byteOffset += 4;
  80305. return value;
  80306. };
  80307. BinaryReader.prototype.readUint8Array = function (length) {
  80308. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  80309. this._byteOffset += length;
  80310. return value;
  80311. };
  80312. BinaryReader.prototype.skipBytes = function (length) {
  80313. this._byteOffset += length;
  80314. };
  80315. return BinaryReader;
  80316. }());
  80317. if (BABYLON.SceneLoader) {
  80318. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  80319. }
  80320. })(BABYLON || (BABYLON = {}));
  80321. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  80322. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  80323. var BABYLON;
  80324. (function (BABYLON) {
  80325. var GLTF1;
  80326. (function (GLTF1) {
  80327. /**
  80328. * Enums
  80329. */
  80330. var EComponentType;
  80331. (function (EComponentType) {
  80332. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  80333. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  80334. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  80335. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  80336. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  80337. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  80338. var EShaderType;
  80339. (function (EShaderType) {
  80340. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  80341. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  80342. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  80343. var EParameterType;
  80344. (function (EParameterType) {
  80345. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  80346. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  80347. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  80348. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  80349. EParameterType[EParameterType["INT"] = 5124] = "INT";
  80350. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  80351. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  80352. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  80353. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  80354. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  80355. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  80356. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  80357. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  80358. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  80359. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  80360. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  80361. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  80362. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  80363. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  80364. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  80365. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  80366. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  80367. var ETextureWrapMode;
  80368. (function (ETextureWrapMode) {
  80369. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  80370. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  80371. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  80372. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  80373. var ETextureFilterType;
  80374. (function (ETextureFilterType) {
  80375. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  80376. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  80377. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  80378. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  80379. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  80380. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  80381. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  80382. var ETextureFormat;
  80383. (function (ETextureFormat) {
  80384. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  80385. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  80386. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  80387. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  80388. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  80389. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  80390. var ECullingType;
  80391. (function (ECullingType) {
  80392. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  80393. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  80394. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  80395. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  80396. var EBlendingFunction;
  80397. (function (EBlendingFunction) {
  80398. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  80399. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  80400. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  80401. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  80402. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  80403. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  80404. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  80405. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  80406. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  80407. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  80408. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  80409. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  80410. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  80411. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  80412. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  80413. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  80414. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  80415. })(BABYLON || (BABYLON = {}));
  80416. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  80417. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  80418. var BABYLON;
  80419. (function (BABYLON) {
  80420. var GLTF1;
  80421. (function (GLTF1) {
  80422. /**
  80423. * Tokenizer. Used for shaders compatibility
  80424. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  80425. */
  80426. var ETokenType;
  80427. (function (ETokenType) {
  80428. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  80429. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  80430. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  80431. })(ETokenType || (ETokenType = {}));
  80432. var Tokenizer = /** @class */ (function () {
  80433. function Tokenizer(toParse) {
  80434. this._pos = 0;
  80435. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  80436. this._toParse = toParse;
  80437. this._maxPos = toParse.length;
  80438. }
  80439. Tokenizer.prototype.getNextToken = function () {
  80440. if (this.isEnd())
  80441. return ETokenType.END_OF_INPUT;
  80442. this.currentString = this.read();
  80443. this.currentToken = ETokenType.UNKNOWN;
  80444. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  80445. this.currentToken = ETokenType.IDENTIFIER;
  80446. this.currentIdentifier = this.currentString;
  80447. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  80448. this.currentIdentifier += this.currentString;
  80449. this.forward();
  80450. }
  80451. }
  80452. return this.currentToken;
  80453. };
  80454. Tokenizer.prototype.peek = function () {
  80455. return this._toParse[this._pos];
  80456. };
  80457. Tokenizer.prototype.read = function () {
  80458. return this._toParse[this._pos++];
  80459. };
  80460. Tokenizer.prototype.forward = function () {
  80461. this._pos++;
  80462. };
  80463. Tokenizer.prototype.isEnd = function () {
  80464. return this._pos >= this._maxPos;
  80465. };
  80466. return Tokenizer;
  80467. }());
  80468. /**
  80469. * Values
  80470. */
  80471. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  80472. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  80473. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  80474. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  80475. /**
  80476. * Parse
  80477. */
  80478. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  80479. for (var buf in parsedBuffers) {
  80480. var parsedBuffer = parsedBuffers[buf];
  80481. gltfRuntime.buffers[buf] = parsedBuffer;
  80482. gltfRuntime.buffersCount++;
  80483. }
  80484. };
  80485. var parseShaders = function (parsedShaders, gltfRuntime) {
  80486. for (var sha in parsedShaders) {
  80487. var parsedShader = parsedShaders[sha];
  80488. gltfRuntime.shaders[sha] = parsedShader;
  80489. gltfRuntime.shaderscount++;
  80490. }
  80491. };
  80492. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  80493. for (var object in parsedObjects) {
  80494. var parsedObject = parsedObjects[object];
  80495. gltfRuntime[runtimeProperty][object] = parsedObject;
  80496. }
  80497. };
  80498. /**
  80499. * Utils
  80500. */
  80501. var normalizeUVs = function (buffer) {
  80502. if (!buffer) {
  80503. return;
  80504. }
  80505. for (var i = 0; i < buffer.length / 2; i++) {
  80506. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  80507. }
  80508. };
  80509. var getAttribute = function (attributeParameter) {
  80510. if (attributeParameter.semantic === "NORMAL") {
  80511. return "normal";
  80512. }
  80513. else if (attributeParameter.semantic === "POSITION") {
  80514. return "position";
  80515. }
  80516. else if (attributeParameter.semantic === "JOINT") {
  80517. return "matricesIndices";
  80518. }
  80519. else if (attributeParameter.semantic === "WEIGHT") {
  80520. return "matricesWeights";
  80521. }
  80522. else if (attributeParameter.semantic === "COLOR") {
  80523. return "color";
  80524. }
  80525. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  80526. var channel = Number(attributeParameter.semantic.split("_")[1]);
  80527. return "uv" + (channel === 0 ? "" : channel + 1);
  80528. }
  80529. return null;
  80530. };
  80531. /**
  80532. * Loads and creates animations
  80533. */
  80534. var loadAnimations = function (gltfRuntime) {
  80535. for (var anim in gltfRuntime.animations) {
  80536. var animation = gltfRuntime.animations[anim];
  80537. if (!animation.channels || !animation.samplers) {
  80538. continue;
  80539. }
  80540. var lastAnimation = null;
  80541. for (var i = 0; i < animation.channels.length; i++) {
  80542. // Get parameters and load buffers
  80543. var channel = animation.channels[i];
  80544. var sampler = animation.samplers[channel.sampler];
  80545. if (!sampler) {
  80546. continue;
  80547. }
  80548. var inputData = null;
  80549. var outputData = null;
  80550. if (animation.parameters) {
  80551. inputData = animation.parameters[sampler.input];
  80552. outputData = animation.parameters[sampler.output];
  80553. }
  80554. else {
  80555. inputData = sampler.input;
  80556. outputData = sampler.output;
  80557. }
  80558. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  80559. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  80560. var targetID = channel.target.id;
  80561. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  80562. if (targetNode === null) {
  80563. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  80564. }
  80565. if (targetNode === null) {
  80566. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  80567. continue;
  80568. }
  80569. var isBone = targetNode instanceof BABYLON.Bone;
  80570. // Get target path (position, rotation or scaling)
  80571. var targetPath = channel.target.path;
  80572. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  80573. if (targetPathIndex !== -1) {
  80574. targetPath = babylonAnimationPaths[targetPathIndex];
  80575. }
  80576. // Determine animation type
  80577. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  80578. if (!isBone) {
  80579. if (targetPath === "rotationQuaternion") {
  80580. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  80581. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  80582. }
  80583. else {
  80584. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  80585. }
  80586. }
  80587. // Create animation and key frames
  80588. var babylonAnimation = null;
  80589. var keys = [];
  80590. var arrayOffset = 0;
  80591. var modifyKey = false;
  80592. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  80593. babylonAnimation = lastAnimation;
  80594. modifyKey = true;
  80595. }
  80596. if (!modifyKey) {
  80597. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  80598. }
  80599. // For each frame
  80600. for (var j = 0; j < bufferInput.length; j++) {
  80601. var value = null;
  80602. if (targetPath === "rotationQuaternion") {
  80603. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  80604. arrayOffset += 4;
  80605. }
  80606. else {
  80607. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  80608. arrayOffset += 3;
  80609. }
  80610. if (isBone) {
  80611. var bone = targetNode;
  80612. var translation = BABYLON.Vector3.Zero();
  80613. var rotationQuaternion = new BABYLON.Quaternion();
  80614. var scaling = BABYLON.Vector3.Zero();
  80615. // Warning on decompose
  80616. var mat = bone.getBaseMatrix();
  80617. if (modifyKey && lastAnimation) {
  80618. mat = lastAnimation.getKeys()[j].value;
  80619. }
  80620. mat.decompose(scaling, rotationQuaternion, translation);
  80621. if (targetPath === "position") {
  80622. translation = value;
  80623. }
  80624. else if (targetPath === "rotationQuaternion") {
  80625. rotationQuaternion = value;
  80626. }
  80627. else {
  80628. scaling = value;
  80629. }
  80630. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  80631. }
  80632. if (!modifyKey) {
  80633. keys.push({
  80634. frame: bufferInput[j],
  80635. value: value
  80636. });
  80637. }
  80638. else if (lastAnimation) {
  80639. lastAnimation.getKeys()[j].value = value;
  80640. }
  80641. }
  80642. // Finish
  80643. if (!modifyKey && babylonAnimation) {
  80644. babylonAnimation.setKeys(keys);
  80645. targetNode.animations.push(babylonAnimation);
  80646. }
  80647. lastAnimation = babylonAnimation;
  80648. gltfRuntime.scene.stopAnimation(targetNode);
  80649. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  80650. }
  80651. }
  80652. };
  80653. /**
  80654. * Returns the bones transformation matrix
  80655. */
  80656. var configureBoneTransformation = function (node) {
  80657. var mat = null;
  80658. if (node.translation || node.rotation || node.scale) {
  80659. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  80660. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  80661. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  80662. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  80663. }
  80664. else {
  80665. mat = BABYLON.Matrix.FromArray(node.matrix);
  80666. }
  80667. return mat;
  80668. };
  80669. /**
  80670. * Returns the parent bone
  80671. */
  80672. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  80673. // Try to find
  80674. for (var i = 0; i < newSkeleton.bones.length; i++) {
  80675. if (newSkeleton.bones[i].name === jointName) {
  80676. return newSkeleton.bones[i];
  80677. }
  80678. }
  80679. // Not found, search in gltf nodes
  80680. var nodes = gltfRuntime.nodes;
  80681. for (var nde in nodes) {
  80682. var node = nodes[nde];
  80683. if (!node.jointName) {
  80684. continue;
  80685. }
  80686. var children = node.children;
  80687. for (var i = 0; i < children.length; i++) {
  80688. var child = gltfRuntime.nodes[children[i]];
  80689. if (!child.jointName) {
  80690. continue;
  80691. }
  80692. if (child.jointName === jointName) {
  80693. var mat = configureBoneTransformation(node);
  80694. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  80695. bone.id = nde;
  80696. return bone;
  80697. }
  80698. }
  80699. }
  80700. return null;
  80701. };
  80702. /**
  80703. * Returns the appropriate root node
  80704. */
  80705. var getNodeToRoot = function (nodesToRoot, id) {
  80706. for (var i = 0; i < nodesToRoot.length; i++) {
  80707. var nodeToRoot = nodesToRoot[i];
  80708. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  80709. var child = nodeToRoot.node.children[j];
  80710. if (child === id) {
  80711. return nodeToRoot.bone;
  80712. }
  80713. }
  80714. }
  80715. return null;
  80716. };
  80717. /**
  80718. * Returns the node with the joint name
  80719. */
  80720. var getJointNode = function (gltfRuntime, jointName) {
  80721. var nodes = gltfRuntime.nodes;
  80722. var node = nodes[jointName];
  80723. if (node) {
  80724. return {
  80725. node: node,
  80726. id: jointName
  80727. };
  80728. }
  80729. for (var nde in nodes) {
  80730. node = nodes[nde];
  80731. if (node.jointName === jointName) {
  80732. return {
  80733. node: node,
  80734. id: nde
  80735. };
  80736. }
  80737. }
  80738. return null;
  80739. };
  80740. /**
  80741. * Checks if a nodes is in joints
  80742. */
  80743. var nodeIsInJoints = function (skins, id) {
  80744. for (var i = 0; i < skins.jointNames.length; i++) {
  80745. if (skins.jointNames[i] === id) {
  80746. return true;
  80747. }
  80748. }
  80749. return false;
  80750. };
  80751. /**
  80752. * Fills the nodes to root for bones and builds hierarchy
  80753. */
  80754. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  80755. // Creates nodes for root
  80756. for (var nde in gltfRuntime.nodes) {
  80757. var node = gltfRuntime.nodes[nde];
  80758. var id = nde;
  80759. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  80760. continue;
  80761. }
  80762. // Create node to root bone
  80763. var mat = configureBoneTransformation(node);
  80764. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  80765. bone.id = id;
  80766. nodesToRoot.push({ bone: bone, node: node, id: id });
  80767. }
  80768. // Parenting
  80769. for (var i = 0; i < nodesToRoot.length; i++) {
  80770. var nodeToRoot = nodesToRoot[i];
  80771. var children = nodeToRoot.node.children;
  80772. for (var j = 0; j < children.length; j++) {
  80773. var child = null;
  80774. for (var k = 0; k < nodesToRoot.length; k++) {
  80775. if (nodesToRoot[k].id === children[j]) {
  80776. child = nodesToRoot[k];
  80777. break;
  80778. }
  80779. }
  80780. if (child) {
  80781. child.bone._parent = nodeToRoot.bone;
  80782. nodeToRoot.bone.children.push(child.bone);
  80783. }
  80784. }
  80785. }
  80786. };
  80787. /**
  80788. * Imports a skeleton
  80789. */
  80790. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  80791. if (!newSkeleton) {
  80792. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  80793. }
  80794. if (!skins.babylonSkeleton) {
  80795. return newSkeleton;
  80796. }
  80797. // Find the root bones
  80798. var nodesToRoot = [];
  80799. var nodesToRootToAdd = [];
  80800. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  80801. newSkeleton.bones = [];
  80802. // Joints
  80803. for (var i = 0; i < skins.jointNames.length; i++) {
  80804. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  80805. if (!jointNode) {
  80806. continue;
  80807. }
  80808. var node = jointNode.node;
  80809. if (!node) {
  80810. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  80811. continue;
  80812. }
  80813. var id = jointNode.id;
  80814. // Optimize, if the bone already exists...
  80815. var existingBone = gltfRuntime.scene.getBoneByID(id);
  80816. if (existingBone) {
  80817. newSkeleton.bones.push(existingBone);
  80818. continue;
  80819. }
  80820. // Search for parent bone
  80821. var foundBone = false;
  80822. var parentBone = null;
  80823. for (var j = 0; j < i; j++) {
  80824. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  80825. if (!jointNode_1) {
  80826. continue;
  80827. }
  80828. var joint = jointNode_1.node;
  80829. if (!joint) {
  80830. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  80831. continue;
  80832. }
  80833. var children = joint.children;
  80834. if (!children) {
  80835. continue;
  80836. }
  80837. foundBone = false;
  80838. for (var k = 0; k < children.length; k++) {
  80839. if (children[k] === id) {
  80840. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  80841. foundBone = true;
  80842. break;
  80843. }
  80844. }
  80845. if (foundBone) {
  80846. break;
  80847. }
  80848. }
  80849. // Create bone
  80850. var mat = configureBoneTransformation(node);
  80851. if (!parentBone && nodesToRoot.length > 0) {
  80852. parentBone = getNodeToRoot(nodesToRoot, id);
  80853. if (parentBone) {
  80854. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  80855. nodesToRootToAdd.push(parentBone);
  80856. }
  80857. }
  80858. }
  80859. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  80860. bone.id = id;
  80861. }
  80862. // Polish
  80863. var bones = newSkeleton.bones;
  80864. newSkeleton.bones = [];
  80865. for (var i = 0; i < skins.jointNames.length; i++) {
  80866. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  80867. if (!jointNode) {
  80868. continue;
  80869. }
  80870. for (var j = 0; j < bones.length; j++) {
  80871. if (bones[j].id === jointNode.id) {
  80872. newSkeleton.bones.push(bones[j]);
  80873. break;
  80874. }
  80875. }
  80876. }
  80877. newSkeleton.prepare();
  80878. // Finish
  80879. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  80880. newSkeleton.bones.push(nodesToRootToAdd[i]);
  80881. }
  80882. return newSkeleton;
  80883. };
  80884. /**
  80885. * Imports a mesh and its geometries
  80886. */
  80887. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  80888. if (!newMesh) {
  80889. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  80890. newMesh.id = id;
  80891. }
  80892. if (!node.babylonNode) {
  80893. return newMesh;
  80894. }
  80895. var subMaterials = [];
  80896. var vertexData = new BABYLON.VertexData();
  80897. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  80898. var verticesStarts = new Array();
  80899. var verticesCounts = new Array();
  80900. var indexStarts = new Array();
  80901. var indexCounts = new Array();
  80902. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  80903. var meshID = meshes[meshIndex];
  80904. var mesh = gltfRuntime.meshes[meshID];
  80905. if (!mesh) {
  80906. continue;
  80907. }
  80908. // Positions, normals and UVs
  80909. for (var i = 0; i < mesh.primitives.length; i++) {
  80910. // Temporary vertex data
  80911. var tempVertexData = new BABYLON.VertexData();
  80912. var primitive = mesh.primitives[i];
  80913. if (primitive.mode !== 4) {
  80914. // continue;
  80915. }
  80916. var attributes = primitive.attributes;
  80917. var accessor = null;
  80918. var buffer = null;
  80919. // Set positions, normal and uvs
  80920. for (var semantic in attributes) {
  80921. // Link accessor and buffer view
  80922. accessor = gltfRuntime.accessors[attributes[semantic]];
  80923. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  80924. if (semantic === "NORMAL") {
  80925. tempVertexData.normals = new Float32Array(buffer.length);
  80926. tempVertexData.normals.set(buffer);
  80927. }
  80928. else if (semantic === "POSITION") {
  80929. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  80930. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  80931. for (var j = 0; j < buffer.length; j += 4) {
  80932. tempVertexData.positions[j] = buffer[j];
  80933. tempVertexData.positions[j + 1] = buffer[j + 1];
  80934. tempVertexData.positions[j + 2] = buffer[j + 2];
  80935. }
  80936. }
  80937. else {
  80938. tempVertexData.positions = new Float32Array(buffer.length);
  80939. tempVertexData.positions.set(buffer);
  80940. }
  80941. verticesCounts.push(tempVertexData.positions.length);
  80942. }
  80943. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  80944. var channel = Number(semantic.split("_")[1]);
  80945. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  80946. var uvs = new Float32Array(buffer.length);
  80947. uvs.set(buffer);
  80948. normalizeUVs(uvs);
  80949. tempVertexData.set(uvs, uvKind);
  80950. }
  80951. else if (semantic === "JOINT") {
  80952. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  80953. tempVertexData.matricesIndices.set(buffer);
  80954. }
  80955. else if (semantic === "WEIGHT") {
  80956. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  80957. tempVertexData.matricesWeights.set(buffer);
  80958. }
  80959. else if (semantic === "COLOR") {
  80960. tempVertexData.colors = new Float32Array(buffer.length);
  80961. tempVertexData.colors.set(buffer);
  80962. }
  80963. }
  80964. // Indices
  80965. accessor = gltfRuntime.accessors[primitive.indices];
  80966. if (accessor) {
  80967. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  80968. tempVertexData.indices = new Int32Array(buffer.length);
  80969. tempVertexData.indices.set(buffer);
  80970. indexCounts.push(tempVertexData.indices.length);
  80971. }
  80972. else {
  80973. // Set indices on the fly
  80974. var indices = [];
  80975. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  80976. indices.push(j);
  80977. }
  80978. tempVertexData.indices = new Int32Array(indices);
  80979. indexCounts.push(tempVertexData.indices.length);
  80980. }
  80981. vertexData.merge(tempVertexData);
  80982. // Sub material
  80983. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  80984. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  80985. // Update vertices start and index start
  80986. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  80987. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  80988. }
  80989. }
  80990. var material;
  80991. if (subMaterials.length > 1) {
  80992. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  80993. material.subMaterials = subMaterials;
  80994. }
  80995. else {
  80996. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  80997. }
  80998. if (subMaterials.length === 1) {
  80999. material = subMaterials[0];
  81000. }
  81001. if (!newMesh.material) {
  81002. newMesh.material = material;
  81003. }
  81004. // Apply geometry
  81005. geometry.setAllVerticesData(vertexData, false);
  81006. newMesh.computeWorldMatrix(true);
  81007. // Apply submeshes
  81008. newMesh.subMeshes = [];
  81009. var index = 0;
  81010. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  81011. var meshID = meshes[meshIndex];
  81012. var mesh = gltfRuntime.meshes[meshID];
  81013. if (!mesh) {
  81014. continue;
  81015. }
  81016. for (var i = 0; i < mesh.primitives.length; i++) {
  81017. if (mesh.primitives[i].mode !== 4) {
  81018. //continue;
  81019. }
  81020. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  81021. index++;
  81022. }
  81023. }
  81024. // Finish
  81025. return newMesh;
  81026. };
  81027. /**
  81028. * Configure node transformation from position, rotation and scaling
  81029. */
  81030. var configureNode = function (newNode, position, rotation, scaling) {
  81031. if (newNode.position) {
  81032. newNode.position = position;
  81033. }
  81034. if (newNode.rotationQuaternion || newNode.rotation) {
  81035. newNode.rotationQuaternion = rotation;
  81036. }
  81037. if (newNode.scaling) {
  81038. newNode.scaling = scaling;
  81039. }
  81040. };
  81041. /**
  81042. * Configures node from transformation matrix
  81043. */
  81044. var configureNodeFromMatrix = function (newNode, node, parent) {
  81045. if (node.matrix) {
  81046. var position = new BABYLON.Vector3(0, 0, 0);
  81047. var rotation = new BABYLON.Quaternion();
  81048. var scaling = new BABYLON.Vector3(0, 0, 0);
  81049. var mat = BABYLON.Matrix.FromArray(node.matrix);
  81050. mat.decompose(scaling, rotation, position);
  81051. configureNode(newNode, position, rotation, scaling);
  81052. }
  81053. else if (node.translation && node.rotation && node.scale) {
  81054. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  81055. }
  81056. newNode.computeWorldMatrix(true);
  81057. };
  81058. /**
  81059. * Imports a node
  81060. */
  81061. var importNode = function (gltfRuntime, node, id, parent) {
  81062. var lastNode = null;
  81063. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  81064. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  81065. return null;
  81066. }
  81067. }
  81068. // Meshes
  81069. if (node.skin) {
  81070. if (node.meshes) {
  81071. var skin = gltfRuntime.skins[node.skin];
  81072. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  81073. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  81074. if (newMesh.skeleton === null) {
  81075. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  81076. if (!skin.babylonSkeleton) {
  81077. skin.babylonSkeleton = newMesh.skeleton;
  81078. }
  81079. }
  81080. lastNode = newMesh;
  81081. }
  81082. }
  81083. else if (node.meshes) {
  81084. /**
  81085. * Improve meshes property
  81086. */
  81087. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  81088. lastNode = newMesh;
  81089. }
  81090. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  81091. var light = gltfRuntime.lights[node.light];
  81092. if (light) {
  81093. if (light.type === "ambient") {
  81094. var ambienLight = light[light.type];
  81095. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  81096. hemiLight.name = node.name || "";
  81097. if (ambienLight.color) {
  81098. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  81099. }
  81100. lastNode = hemiLight;
  81101. }
  81102. else if (light.type === "directional") {
  81103. var directionalLight = light[light.type];
  81104. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  81105. dirLight.name = node.name || "";
  81106. if (directionalLight.color) {
  81107. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  81108. }
  81109. lastNode = dirLight;
  81110. }
  81111. else if (light.type === "point") {
  81112. var pointLight = light[light.type];
  81113. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  81114. ptLight.name = node.name || "";
  81115. if (pointLight.color) {
  81116. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  81117. }
  81118. lastNode = ptLight;
  81119. }
  81120. else if (light.type === "spot") {
  81121. var spotLight = light[light.type];
  81122. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  81123. spLight.name = node.name || "";
  81124. if (spotLight.color) {
  81125. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  81126. }
  81127. if (spotLight.fallOfAngle) {
  81128. spLight.angle = spotLight.fallOfAngle;
  81129. }
  81130. if (spotLight.fallOffExponent) {
  81131. spLight.exponent = spotLight.fallOffExponent;
  81132. }
  81133. lastNode = spLight;
  81134. }
  81135. }
  81136. }
  81137. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  81138. var camera = gltfRuntime.cameras[node.camera];
  81139. if (camera) {
  81140. if (camera.type === "orthographic") {
  81141. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  81142. orthoCamera.name = node.name || "";
  81143. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  81144. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  81145. lastNode = orthoCamera;
  81146. }
  81147. else if (camera.type === "perspective") {
  81148. var perspectiveCamera = camera[camera.type];
  81149. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  81150. persCamera.name = node.name || "";
  81151. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  81152. if (!perspectiveCamera.aspectRatio) {
  81153. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  81154. }
  81155. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  81156. persCamera.maxZ = perspectiveCamera.zfar;
  81157. persCamera.minZ = perspectiveCamera.znear;
  81158. }
  81159. lastNode = persCamera;
  81160. }
  81161. }
  81162. }
  81163. // Empty node
  81164. if (!node.jointName) {
  81165. if (node.babylonNode) {
  81166. return node.babylonNode;
  81167. }
  81168. else if (lastNode === null) {
  81169. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  81170. node.babylonNode = dummy;
  81171. lastNode = dummy;
  81172. }
  81173. }
  81174. if (lastNode !== null) {
  81175. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  81176. configureNodeFromMatrix(lastNode, node, parent);
  81177. }
  81178. else {
  81179. var translation = node.translation || [0, 0, 0];
  81180. var rotation = node.rotation || [0, 0, 0, 1];
  81181. var scale = node.scale || [1, 1, 1];
  81182. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  81183. }
  81184. lastNode.updateCache(true);
  81185. node.babylonNode = lastNode;
  81186. }
  81187. return lastNode;
  81188. };
  81189. /**
  81190. * Traverses nodes and creates them
  81191. */
  81192. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  81193. if (meshIncluded === void 0) { meshIncluded = false; }
  81194. var node = gltfRuntime.nodes[id];
  81195. var newNode = null;
  81196. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  81197. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  81198. meshIncluded = true;
  81199. }
  81200. else {
  81201. meshIncluded = false;
  81202. }
  81203. }
  81204. else {
  81205. meshIncluded = true;
  81206. }
  81207. if (!node.jointName && meshIncluded) {
  81208. newNode = importNode(gltfRuntime, node, id, parent);
  81209. if (newNode !== null) {
  81210. newNode.id = id;
  81211. newNode.parent = parent;
  81212. }
  81213. }
  81214. if (node.children) {
  81215. for (var i = 0; i < node.children.length; i++) {
  81216. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  81217. }
  81218. }
  81219. };
  81220. /**
  81221. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  81222. */
  81223. var postLoad = function (gltfRuntime) {
  81224. // Nodes
  81225. var currentScene = gltfRuntime.currentScene;
  81226. if (currentScene) {
  81227. for (var i = 0; i < currentScene.nodes.length; i++) {
  81228. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  81229. }
  81230. }
  81231. else {
  81232. for (var thing in gltfRuntime.scenes) {
  81233. currentScene = gltfRuntime.scenes[thing];
  81234. for (var i = 0; i < currentScene.nodes.length; i++) {
  81235. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  81236. }
  81237. }
  81238. }
  81239. // Set animations
  81240. loadAnimations(gltfRuntime);
  81241. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  81242. var skeleton = gltfRuntime.scene.skeletons[i];
  81243. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  81244. }
  81245. };
  81246. /**
  81247. * onBind shaderrs callback to set uniforms and matrices
  81248. */
  81249. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  81250. var materialValues = material.values || technique.parameters;
  81251. for (var unif in unTreatedUniforms) {
  81252. var uniform = unTreatedUniforms[unif];
  81253. var type = uniform.type;
  81254. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  81255. if (uniform.semantic && !uniform.source && !uniform.node) {
  81256. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  81257. }
  81258. else if (uniform.semantic && (uniform.source || uniform.node)) {
  81259. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  81260. if (source === null) {
  81261. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  81262. }
  81263. if (source === null) {
  81264. continue;
  81265. }
  81266. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  81267. }
  81268. }
  81269. else {
  81270. var value = materialValues[technique.uniforms[unif]];
  81271. if (!value) {
  81272. continue;
  81273. }
  81274. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  81275. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  81276. if (texture === null || texture === undefined) {
  81277. continue;
  81278. }
  81279. shaderMaterial.getEffect().setTexture(unif, texture);
  81280. }
  81281. else {
  81282. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  81283. }
  81284. }
  81285. }
  81286. onSuccess(shaderMaterial);
  81287. };
  81288. /**
  81289. * Prepare uniforms to send the only one time
  81290. * Loads the appropriate textures
  81291. */
  81292. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  81293. var materialValues = material.values || technique.parameters;
  81294. var techniqueUniforms = technique.uniforms;
  81295. /**
  81296. * Prepare values here (not matrices)
  81297. */
  81298. for (var unif in unTreatedUniforms) {
  81299. var uniform = unTreatedUniforms[unif];
  81300. var type = uniform.type;
  81301. var value = materialValues[techniqueUniforms[unif]];
  81302. if (value === undefined) {
  81303. // In case the value is the same for all materials
  81304. value = uniform.value;
  81305. }
  81306. if (!value) {
  81307. continue;
  81308. }
  81309. var onLoadTexture = function (uniformName) {
  81310. return function (texture) {
  81311. if (uniform.value && uniformName) {
  81312. // Static uniform
  81313. shaderMaterial.setTexture(uniformName, texture);
  81314. delete unTreatedUniforms[uniformName];
  81315. }
  81316. };
  81317. };
  81318. // Texture (sampler2D)
  81319. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  81320. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  81321. }
  81322. else {
  81323. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  81324. // Static uniform
  81325. delete unTreatedUniforms[unif];
  81326. }
  81327. }
  81328. }
  81329. };
  81330. /**
  81331. * Shader compilation failed
  81332. */
  81333. var onShaderCompileError = function (program, shaderMaterial, onError) {
  81334. return function (effect, error) {
  81335. shaderMaterial.dispose(true);
  81336. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  81337. };
  81338. };
  81339. /**
  81340. * Shader compilation success
  81341. */
  81342. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  81343. return function (_) {
  81344. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  81345. shaderMaterial.onBind = function (mesh) {
  81346. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  81347. };
  81348. };
  81349. };
  81350. /**
  81351. * Returns the appropriate uniform if already handled by babylon
  81352. */
  81353. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  81354. for (var unif in technique.uniforms) {
  81355. var uniform = technique.uniforms[unif];
  81356. var uniformParameter = technique.parameters[uniform];
  81357. if (tokenizer.currentIdentifier === unif) {
  81358. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  81359. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  81360. if (transformIndex !== -1) {
  81361. delete unTreatedUniforms[unif];
  81362. return babylonTransforms[transformIndex];
  81363. }
  81364. }
  81365. }
  81366. }
  81367. return tokenizer.currentIdentifier;
  81368. };
  81369. /**
  81370. * All shaders loaded. Create materials one by one
  81371. */
  81372. var importMaterials = function (gltfRuntime) {
  81373. // Create materials
  81374. for (var mat in gltfRuntime.materials) {
  81375. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  81376. }
  81377. };
  81378. /**
  81379. * Implementation of the base glTF spec
  81380. */
  81381. var GLTFLoaderBase = /** @class */ (function () {
  81382. function GLTFLoaderBase() {
  81383. }
  81384. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  81385. var gltfRuntime = {
  81386. extensions: {},
  81387. accessors: {},
  81388. buffers: {},
  81389. bufferViews: {},
  81390. meshes: {},
  81391. lights: {},
  81392. cameras: {},
  81393. nodes: {},
  81394. images: {},
  81395. textures: {},
  81396. shaders: {},
  81397. programs: {},
  81398. samplers: {},
  81399. techniques: {},
  81400. materials: {},
  81401. animations: {},
  81402. skins: {},
  81403. extensionsUsed: [],
  81404. scenes: {},
  81405. buffersCount: 0,
  81406. shaderscount: 0,
  81407. scene: scene,
  81408. rootUrl: rootUrl,
  81409. loadedBufferCount: 0,
  81410. loadedBufferViews: {},
  81411. loadedShaderCount: 0,
  81412. importOnlyMeshes: false,
  81413. dummyNodes: []
  81414. };
  81415. // Parse
  81416. if (parsedData.extensions) {
  81417. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  81418. }
  81419. if (parsedData.extensionsUsed) {
  81420. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  81421. }
  81422. if (parsedData.buffers) {
  81423. parseBuffers(parsedData.buffers, gltfRuntime);
  81424. }
  81425. if (parsedData.bufferViews) {
  81426. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  81427. }
  81428. if (parsedData.accessors) {
  81429. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  81430. }
  81431. if (parsedData.meshes) {
  81432. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  81433. }
  81434. if (parsedData.lights) {
  81435. parseObject(parsedData.lights, "lights", gltfRuntime);
  81436. }
  81437. if (parsedData.cameras) {
  81438. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  81439. }
  81440. if (parsedData.nodes) {
  81441. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  81442. }
  81443. if (parsedData.images) {
  81444. parseObject(parsedData.images, "images", gltfRuntime);
  81445. }
  81446. if (parsedData.textures) {
  81447. parseObject(parsedData.textures, "textures", gltfRuntime);
  81448. }
  81449. if (parsedData.shaders) {
  81450. parseShaders(parsedData.shaders, gltfRuntime);
  81451. }
  81452. if (parsedData.programs) {
  81453. parseObject(parsedData.programs, "programs", gltfRuntime);
  81454. }
  81455. if (parsedData.samplers) {
  81456. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  81457. }
  81458. if (parsedData.techniques) {
  81459. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  81460. }
  81461. if (parsedData.materials) {
  81462. parseObject(parsedData.materials, "materials", gltfRuntime);
  81463. }
  81464. if (parsedData.animations) {
  81465. parseObject(parsedData.animations, "animations", gltfRuntime);
  81466. }
  81467. if (parsedData.skins) {
  81468. parseObject(parsedData.skins, "skins", gltfRuntime);
  81469. }
  81470. if (parsedData.scenes) {
  81471. gltfRuntime.scenes = parsedData.scenes;
  81472. }
  81473. if (parsedData.scene && parsedData.scenes) {
  81474. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  81475. }
  81476. return gltfRuntime;
  81477. };
  81478. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  81479. var buffer = gltfRuntime.buffers[id];
  81480. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  81481. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  81482. }
  81483. else {
  81484. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  81485. if (request) {
  81486. onError(request.status + " " + request.statusText);
  81487. }
  81488. });
  81489. }
  81490. };
  81491. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  81492. var texture = gltfRuntime.textures[id];
  81493. if (!texture || !texture.source) {
  81494. onError("");
  81495. return;
  81496. }
  81497. if (texture.babylonTexture) {
  81498. onSuccess(null);
  81499. return;
  81500. }
  81501. var source = gltfRuntime.images[texture.source];
  81502. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  81503. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  81504. }
  81505. else {
  81506. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  81507. if (request) {
  81508. onError(request.status + " " + request.statusText);
  81509. }
  81510. });
  81511. }
  81512. };
  81513. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  81514. var texture = gltfRuntime.textures[id];
  81515. if (texture.babylonTexture) {
  81516. onSuccess(texture.babylonTexture);
  81517. return;
  81518. }
  81519. var sampler = gltfRuntime.samplers[texture.sampler];
  81520. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  81521. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  81522. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  81523. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  81524. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  81525. var blob = new Blob([buffer]);
  81526. var blobURL = URL.createObjectURL(blob);
  81527. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  81528. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  81529. if (sampler.wrapS !== undefined) {
  81530. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  81531. }
  81532. if (sampler.wrapT !== undefined) {
  81533. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  81534. }
  81535. newTexture.name = id;
  81536. texture.babylonTexture = newTexture;
  81537. onSuccess(newTexture);
  81538. };
  81539. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  81540. var shader = gltfRuntime.shaders[id];
  81541. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  81542. var shaderString = atob(shader.uri.split(",")[1]);
  81543. onSuccess(shaderString);
  81544. }
  81545. else {
  81546. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  81547. if (request) {
  81548. onError(request.status + " " + request.statusText);
  81549. }
  81550. });
  81551. }
  81552. };
  81553. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  81554. var material = gltfRuntime.materials[id];
  81555. if (!material.technique) {
  81556. if (onError) {
  81557. onError("No technique found.");
  81558. }
  81559. return;
  81560. }
  81561. var technique = gltfRuntime.techniques[material.technique];
  81562. if (!technique) {
  81563. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  81564. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  81565. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  81566. onSuccess(defaultMaterial);
  81567. return;
  81568. }
  81569. var program = gltfRuntime.programs[technique.program];
  81570. var states = technique.states;
  81571. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  81572. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  81573. var newVertexShader = "";
  81574. var newPixelShader = "";
  81575. var vertexTokenizer = new Tokenizer(vertexShader);
  81576. var pixelTokenizer = new Tokenizer(pixelShader);
  81577. var unTreatedUniforms = {};
  81578. var uniforms = [];
  81579. var attributes = [];
  81580. var samplers = [];
  81581. // Fill uniform, sampler2D and attributes
  81582. for (var unif in technique.uniforms) {
  81583. var uniform = technique.uniforms[unif];
  81584. var uniformParameter = technique.parameters[uniform];
  81585. unTreatedUniforms[unif] = uniformParameter;
  81586. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  81587. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  81588. if (transformIndex !== -1) {
  81589. uniforms.push(babylonTransforms[transformIndex]);
  81590. delete unTreatedUniforms[unif];
  81591. }
  81592. else {
  81593. uniforms.push(unif);
  81594. }
  81595. }
  81596. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  81597. samplers.push(unif);
  81598. }
  81599. else {
  81600. uniforms.push(unif);
  81601. }
  81602. }
  81603. for (var attr in technique.attributes) {
  81604. var attribute = technique.attributes[attr];
  81605. var attributeParameter = technique.parameters[attribute];
  81606. if (attributeParameter.semantic) {
  81607. attributes.push(getAttribute(attributeParameter));
  81608. }
  81609. }
  81610. // Configure vertex shader
  81611. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  81612. var tokenType = vertexTokenizer.currentToken;
  81613. if (tokenType !== ETokenType.IDENTIFIER) {
  81614. newVertexShader += vertexTokenizer.currentString;
  81615. continue;
  81616. }
  81617. var foundAttribute = false;
  81618. for (var attr in technique.attributes) {
  81619. var attribute = technique.attributes[attr];
  81620. var attributeParameter = technique.parameters[attribute];
  81621. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  81622. newVertexShader += getAttribute(attributeParameter);
  81623. foundAttribute = true;
  81624. break;
  81625. }
  81626. }
  81627. if (foundAttribute) {
  81628. continue;
  81629. }
  81630. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  81631. }
  81632. // Configure pixel shader
  81633. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  81634. var tokenType = pixelTokenizer.currentToken;
  81635. if (tokenType !== ETokenType.IDENTIFIER) {
  81636. newPixelShader += pixelTokenizer.currentString;
  81637. continue;
  81638. }
  81639. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  81640. }
  81641. // Create shader material
  81642. var shaderPath = {
  81643. vertex: program.vertexShader + id,
  81644. fragment: program.fragmentShader + id
  81645. };
  81646. var options = {
  81647. attributes: attributes,
  81648. uniforms: uniforms,
  81649. samplers: samplers,
  81650. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  81651. };
  81652. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  81653. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  81654. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  81655. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  81656. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  81657. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  81658. if (states && states.functions) {
  81659. var functions = states.functions;
  81660. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  81661. shaderMaterial.backFaceCulling = false;
  81662. }
  81663. var blendFunc = functions.blendFuncSeparate;
  81664. if (blendFunc) {
  81665. if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  81666. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  81667. }
  81668. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  81669. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  81670. }
  81671. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  81672. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  81673. }
  81674. else if (blendFunc[0] === GLTF1.EBlendingFunction.ZERO && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  81675. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  81676. }
  81677. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  81678. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  81679. }
  81680. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  81681. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  81682. }
  81683. }
  81684. }
  81685. };
  81686. return GLTFLoaderBase;
  81687. }());
  81688. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  81689. /**
  81690. * glTF V1 Loader
  81691. */
  81692. var GLTFLoader = /** @class */ (function () {
  81693. function GLTFLoader() {
  81694. }
  81695. GLTFLoader.RegisterExtension = function (extension) {
  81696. if (GLTFLoader.Extensions[extension.name]) {
  81697. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  81698. return;
  81699. }
  81700. GLTFLoader.Extensions[extension.name] = extension;
  81701. };
  81702. GLTFLoader.prototype.dispose = function () {
  81703. // do nothing
  81704. };
  81705. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  81706. var _this = this;
  81707. scene.useRightHandedSystem = true;
  81708. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  81709. gltfRuntime.importOnlyMeshes = true;
  81710. if (meshesNames === "") {
  81711. gltfRuntime.importMeshesNames = [];
  81712. }
  81713. else if (typeof meshesNames === "string") {
  81714. gltfRuntime.importMeshesNames = [meshesNames];
  81715. }
  81716. else if (meshesNames && !(meshesNames instanceof Array)) {
  81717. gltfRuntime.importMeshesNames = [meshesNames];
  81718. }
  81719. else {
  81720. gltfRuntime.importMeshesNames = [];
  81721. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  81722. }
  81723. // Create nodes
  81724. _this._createNodes(gltfRuntime);
  81725. var meshes = new Array();
  81726. var skeletons = new Array();
  81727. // Fill arrays of meshes and skeletons
  81728. for (var nde in gltfRuntime.nodes) {
  81729. var node = gltfRuntime.nodes[nde];
  81730. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  81731. meshes.push(node.babylonNode);
  81732. }
  81733. }
  81734. for (var skl in gltfRuntime.skins) {
  81735. var skin = gltfRuntime.skins[skl];
  81736. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  81737. skeletons.push(skin.babylonSkeleton);
  81738. }
  81739. }
  81740. // Load buffers, shaders, materials, etc.
  81741. _this._loadBuffersAsync(gltfRuntime, function () {
  81742. _this._loadShadersAsync(gltfRuntime, function () {
  81743. importMaterials(gltfRuntime);
  81744. postLoad(gltfRuntime);
  81745. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  81746. onSuccess(meshes, [], skeletons);
  81747. }
  81748. });
  81749. }, onProgress);
  81750. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  81751. onSuccess(meshes, [], skeletons);
  81752. }
  81753. }, onError);
  81754. return true;
  81755. };
  81756. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  81757. var _this = this;
  81758. scene.useRightHandedSystem = true;
  81759. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  81760. // Load runtime extensios
  81761. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  81762. // Create nodes
  81763. _this._createNodes(gltfRuntime);
  81764. // Load buffers, shaders, materials, etc.
  81765. _this._loadBuffersAsync(gltfRuntime, function () {
  81766. _this._loadShadersAsync(gltfRuntime, function () {
  81767. importMaterials(gltfRuntime);
  81768. postLoad(gltfRuntime);
  81769. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  81770. onSuccess();
  81771. }
  81772. });
  81773. });
  81774. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  81775. onSuccess();
  81776. }
  81777. }, onError);
  81778. }, onError);
  81779. };
  81780. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  81781. var hasShaders = false;
  81782. var processShader = function (sha, shader) {
  81783. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  81784. gltfRuntime.loadedShaderCount++;
  81785. if (shaderString) {
  81786. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  81787. }
  81788. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  81789. onload();
  81790. }
  81791. }, function () {
  81792. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  81793. });
  81794. };
  81795. for (var sha in gltfRuntime.shaders) {
  81796. hasShaders = true;
  81797. var shader = gltfRuntime.shaders[sha];
  81798. if (shader) {
  81799. processShader.bind(this, sha, shader)();
  81800. }
  81801. else {
  81802. BABYLON.Tools.Error("No shader named: " + sha);
  81803. }
  81804. }
  81805. if (!hasShaders) {
  81806. onload();
  81807. }
  81808. };
  81809. ;
  81810. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  81811. var hasBuffers = false;
  81812. var processBuffer = function (buf, buffer) {
  81813. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  81814. gltfRuntime.loadedBufferCount++;
  81815. if (bufferView) {
  81816. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  81817. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  81818. }
  81819. gltfRuntime.loadedBufferViews[buf] = bufferView;
  81820. }
  81821. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  81822. onLoad();
  81823. }
  81824. }, function () {
  81825. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  81826. });
  81827. };
  81828. for (var buf in gltfRuntime.buffers) {
  81829. hasBuffers = true;
  81830. var buffer = gltfRuntime.buffers[buf];
  81831. if (buffer) {
  81832. processBuffer.bind(this, buf, buffer)();
  81833. }
  81834. else {
  81835. BABYLON.Tools.Error("No buffer named: " + buf);
  81836. }
  81837. }
  81838. if (!hasBuffers) {
  81839. onLoad();
  81840. }
  81841. };
  81842. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  81843. var currentScene = gltfRuntime.currentScene;
  81844. if (currentScene) {
  81845. // Only one scene even if multiple scenes are defined
  81846. for (var i = 0; i < currentScene.nodes.length; i++) {
  81847. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  81848. }
  81849. }
  81850. else {
  81851. // Load all scenes
  81852. for (var thing in gltfRuntime.scenes) {
  81853. currentScene = gltfRuntime.scenes[thing];
  81854. for (var i = 0; i < currentScene.nodes.length; i++) {
  81855. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  81856. }
  81857. }
  81858. }
  81859. };
  81860. GLTFLoader.Extensions = {};
  81861. return GLTFLoader;
  81862. }());
  81863. GLTF1.GLTFLoader = GLTFLoader;
  81864. ;
  81865. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  81866. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  81867. })(BABYLON || (BABYLON = {}));
  81868. //# sourceMappingURL=babylon.glTFLoader.js.map
  81869. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  81870. var BABYLON;
  81871. (function (BABYLON) {
  81872. var GLTF1;
  81873. (function (GLTF1) {
  81874. /**
  81875. * Utils functions for GLTF
  81876. */
  81877. var GLTFUtils = /** @class */ (function () {
  81878. function GLTFUtils() {
  81879. }
  81880. /**
  81881. * Sets the given "parameter" matrix
  81882. * @param scene: the {BABYLON.Scene} object
  81883. * @param source: the source node where to pick the matrix
  81884. * @param parameter: the GLTF technique parameter
  81885. * @param uniformName: the name of the shader's uniform
  81886. * @param shaderMaterial: the shader material
  81887. */
  81888. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  81889. var mat = null;
  81890. if (parameter.semantic === "MODEL") {
  81891. mat = source.getWorldMatrix();
  81892. }
  81893. else if (parameter.semantic === "PROJECTION") {
  81894. mat = scene.getProjectionMatrix();
  81895. }
  81896. else if (parameter.semantic === "VIEW") {
  81897. mat = scene.getViewMatrix();
  81898. }
  81899. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  81900. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  81901. }
  81902. else if (parameter.semantic === "MODELVIEW") {
  81903. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  81904. }
  81905. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  81906. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  81907. }
  81908. else if (parameter.semantic === "MODELINVERSE") {
  81909. mat = source.getWorldMatrix().invert();
  81910. }
  81911. else if (parameter.semantic === "VIEWINVERSE") {
  81912. mat = scene.getViewMatrix().invert();
  81913. }
  81914. else if (parameter.semantic === "PROJECTIONINVERSE") {
  81915. mat = scene.getProjectionMatrix().invert();
  81916. }
  81917. else if (parameter.semantic === "MODELVIEWINVERSE") {
  81918. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  81919. }
  81920. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  81921. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  81922. }
  81923. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  81924. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  81925. }
  81926. else {
  81927. debugger;
  81928. }
  81929. if (mat) {
  81930. switch (parameter.type) {
  81931. case GLTF1.EParameterType.FLOAT_MAT2:
  81932. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  81933. break;
  81934. case GLTF1.EParameterType.FLOAT_MAT3:
  81935. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  81936. break;
  81937. case GLTF1.EParameterType.FLOAT_MAT4:
  81938. shaderMaterial.setMatrix(uniformName, mat);
  81939. break;
  81940. default: break;
  81941. }
  81942. }
  81943. };
  81944. /**
  81945. * Sets the given "parameter" matrix
  81946. * @param shaderMaterial: the shader material
  81947. * @param uniform: the name of the shader's uniform
  81948. * @param value: the value of the uniform
  81949. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  81950. */
  81951. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  81952. switch (type) {
  81953. case GLTF1.EParameterType.FLOAT:
  81954. shaderMaterial.setFloat(uniform, value);
  81955. return true;
  81956. case GLTF1.EParameterType.FLOAT_VEC2:
  81957. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  81958. return true;
  81959. case GLTF1.EParameterType.FLOAT_VEC3:
  81960. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  81961. return true;
  81962. case GLTF1.EParameterType.FLOAT_VEC4:
  81963. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  81964. return true;
  81965. default: return false;
  81966. }
  81967. };
  81968. /**
  81969. * If the uri is a base64 string
  81970. * @param uri: the uri to test
  81971. */
  81972. GLTFUtils.IsBase64 = function (uri) {
  81973. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  81974. };
  81975. /**
  81976. * Decode the base64 uri
  81977. * @param uri: the uri to decode
  81978. */
  81979. GLTFUtils.DecodeBase64 = function (uri) {
  81980. var decodedString = atob(uri.split(",")[1]);
  81981. var bufferLength = decodedString.length;
  81982. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  81983. for (var i = 0; i < bufferLength; i++) {
  81984. bufferView[i] = decodedString.charCodeAt(i);
  81985. }
  81986. return bufferView.buffer;
  81987. };
  81988. /**
  81989. * Returns the wrap mode of the texture
  81990. * @param mode: the mode value
  81991. */
  81992. GLTFUtils.GetWrapMode = function (mode) {
  81993. switch (mode) {
  81994. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  81995. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  81996. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  81997. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  81998. }
  81999. };
  82000. /**
  82001. * Returns the byte stride giving an accessor
  82002. * @param accessor: the GLTF accessor objet
  82003. */
  82004. GLTFUtils.GetByteStrideFromType = function (accessor) {
  82005. // Needs this function since "byteStride" isn't requiered in glTF format
  82006. var type = accessor.type;
  82007. switch (type) {
  82008. case "VEC2": return 2;
  82009. case "VEC3": return 3;
  82010. case "VEC4": return 4;
  82011. case "MAT2": return 4;
  82012. case "MAT3": return 9;
  82013. case "MAT4": return 16;
  82014. default: return 1;
  82015. }
  82016. };
  82017. /**
  82018. * Returns the texture filter mode giving a mode value
  82019. * @param mode: the filter mode value
  82020. */
  82021. GLTFUtils.GetTextureFilterMode = function (mode) {
  82022. switch (mode) {
  82023. case GLTF1.ETextureFilterType.LINEAR:
  82024. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  82025. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  82026. case GLTF1.ETextureFilterType.NEAREST:
  82027. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  82028. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  82029. }
  82030. };
  82031. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  82032. var byteOffset = bufferView.byteOffset + byteOffset;
  82033. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  82034. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  82035. throw new Error("Buffer access is out of range");
  82036. }
  82037. var buffer = loadedBufferView.buffer;
  82038. byteOffset += loadedBufferView.byteOffset;
  82039. switch (componentType) {
  82040. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  82041. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  82042. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  82043. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  82044. default: return new Float32Array(buffer, byteOffset, byteLength);
  82045. }
  82046. };
  82047. /**
  82048. * Returns a buffer from its accessor
  82049. * @param gltfRuntime: the GLTF runtime
  82050. * @param accessor: the GLTF accessor
  82051. */
  82052. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  82053. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  82054. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  82055. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  82056. };
  82057. /**
  82058. * Decodes a buffer view into a string
  82059. * @param view: the buffer view
  82060. */
  82061. GLTFUtils.DecodeBufferToText = function (view) {
  82062. var result = "";
  82063. var length = view.byteLength;
  82064. for (var i = 0; i < length; ++i) {
  82065. result += String.fromCharCode(view[i]);
  82066. }
  82067. return result;
  82068. };
  82069. /**
  82070. * Returns the default material of gltf. Related to
  82071. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  82072. * @param scene: the Babylon.js scene
  82073. */
  82074. GLTFUtils.GetDefaultMaterial = function (scene) {
  82075. if (!GLTFUtils._DefaultMaterial) {
  82076. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  82077. "precision highp float;",
  82078. "",
  82079. "uniform mat4 worldView;",
  82080. "uniform mat4 projection;",
  82081. "",
  82082. "attribute vec3 position;",
  82083. "",
  82084. "void main(void)",
  82085. "{",
  82086. " gl_Position = projection * worldView * vec4(position, 1.0);",
  82087. "}"
  82088. ].join("\n");
  82089. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  82090. "precision highp float;",
  82091. "",
  82092. "uniform vec4 u_emission;",
  82093. "",
  82094. "void main(void)",
  82095. "{",
  82096. " gl_FragColor = u_emission;",
  82097. "}"
  82098. ].join("\n");
  82099. var shaderPath = {
  82100. vertex: "GLTFDefaultMaterial",
  82101. fragment: "GLTFDefaultMaterial"
  82102. };
  82103. var options = {
  82104. attributes: ["position"],
  82105. uniforms: ["worldView", "projection", "u_emission"],
  82106. samplers: new Array(),
  82107. needAlphaBlending: false
  82108. };
  82109. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  82110. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  82111. }
  82112. return GLTFUtils._DefaultMaterial;
  82113. };
  82114. // The GLTF default material
  82115. GLTFUtils._DefaultMaterial = null;
  82116. return GLTFUtils;
  82117. }());
  82118. GLTF1.GLTFUtils = GLTFUtils;
  82119. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  82120. })(BABYLON || (BABYLON = {}));
  82121. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  82122. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  82123. var BABYLON;
  82124. (function (BABYLON) {
  82125. var GLTF1;
  82126. (function (GLTF1) {
  82127. var GLTFLoaderExtension = /** @class */ (function () {
  82128. function GLTFLoaderExtension(name) {
  82129. this._name = name;
  82130. }
  82131. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  82132. get: function () {
  82133. return this._name;
  82134. },
  82135. enumerable: true,
  82136. configurable: true
  82137. });
  82138. /**
  82139. * Defines an override for loading the runtime
  82140. * Return true to stop further extensions from loading the runtime
  82141. */
  82142. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  82143. return false;
  82144. };
  82145. /**
  82146. * Defines an onverride for creating gltf runtime
  82147. * Return true to stop further extensions from creating the runtime
  82148. */
  82149. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  82150. return false;
  82151. };
  82152. /**
  82153. * Defines an override for loading buffers
  82154. * Return true to stop further extensions from loading this buffer
  82155. */
  82156. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  82157. return false;
  82158. };
  82159. /**
  82160. * Defines an override for loading texture buffers
  82161. * Return true to stop further extensions from loading this texture data
  82162. */
  82163. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  82164. return false;
  82165. };
  82166. /**
  82167. * Defines an override for creating textures
  82168. * Return true to stop further extensions from loading this texture
  82169. */
  82170. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  82171. return false;
  82172. };
  82173. /**
  82174. * Defines an override for loading shader strings
  82175. * Return true to stop further extensions from loading this shader data
  82176. */
  82177. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  82178. return false;
  82179. };
  82180. /**
  82181. * Defines an override for loading materials
  82182. * Return true to stop further extensions from loading this material
  82183. */
  82184. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  82185. return false;
  82186. };
  82187. // ---------
  82188. // Utilities
  82189. // ---------
  82190. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  82191. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  82192. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  82193. }, function () {
  82194. setTimeout(function () {
  82195. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  82196. });
  82197. });
  82198. };
  82199. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  82200. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  82201. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  82202. }, function () {
  82203. setTimeout(function () {
  82204. onSuccess();
  82205. });
  82206. });
  82207. };
  82208. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  82209. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  82210. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  82211. }, function () {
  82212. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  82213. });
  82214. };
  82215. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  82216. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  82217. };
  82218. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  82219. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  82220. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  82221. }, function () {
  82222. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  82223. });
  82224. };
  82225. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  82226. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  82227. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  82228. }, function () {
  82229. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  82230. });
  82231. };
  82232. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  82233. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  82234. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  82235. }, function () {
  82236. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  82237. });
  82238. };
  82239. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  82240. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  82241. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  82242. }, function () {
  82243. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  82244. });
  82245. };
  82246. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  82247. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  82248. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  82249. if (func(loaderExtension)) {
  82250. return;
  82251. }
  82252. }
  82253. defaultFunc();
  82254. };
  82255. return GLTFLoaderExtension;
  82256. }());
  82257. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  82258. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  82259. })(BABYLON || (BABYLON = {}));
  82260. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  82261. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  82262. var BABYLON;
  82263. (function (BABYLON) {
  82264. var GLTF1;
  82265. (function (GLTF1) {
  82266. var BinaryExtensionBufferName = "binary_glTF";
  82267. ;
  82268. ;
  82269. var GLTFBinaryExtension = /** @class */ (function (_super) {
  82270. __extends(GLTFBinaryExtension, _super);
  82271. function GLTFBinaryExtension() {
  82272. return _super.call(this, "KHR_binary_glTF") || this;
  82273. }
  82274. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  82275. var extensionsUsed = data.json.extensionsUsed;
  82276. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  82277. return false;
  82278. }
  82279. this._bin = data.bin;
  82280. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  82281. return true;
  82282. };
  82283. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  82284. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  82285. return false;
  82286. }
  82287. if (id !== BinaryExtensionBufferName) {
  82288. return false;
  82289. }
  82290. onSuccess(this._bin);
  82291. return true;
  82292. };
  82293. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  82294. var texture = gltfRuntime.textures[id];
  82295. var source = gltfRuntime.images[texture.source];
  82296. if (!source.extensions || !(this.name in source.extensions)) {
  82297. return false;
  82298. }
  82299. var sourceExt = source.extensions[this.name];
  82300. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  82301. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  82302. onSuccess(buffer);
  82303. return true;
  82304. };
  82305. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  82306. var shader = gltfRuntime.shaders[id];
  82307. if (!shader.extensions || !(this.name in shader.extensions)) {
  82308. return false;
  82309. }
  82310. var binaryExtensionShader = shader.extensions[this.name];
  82311. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  82312. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  82313. setTimeout(function () {
  82314. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  82315. onSuccess(shaderString);
  82316. });
  82317. return true;
  82318. };
  82319. return GLTFBinaryExtension;
  82320. }(GLTF1.GLTFLoaderExtension));
  82321. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  82322. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  82323. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  82324. })(BABYLON || (BABYLON = {}));
  82325. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  82326. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  82327. var BABYLON;
  82328. (function (BABYLON) {
  82329. var GLTF1;
  82330. (function (GLTF1) {
  82331. ;
  82332. ;
  82333. ;
  82334. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  82335. __extends(GLTFMaterialsCommonExtension, _super);
  82336. function GLTFMaterialsCommonExtension() {
  82337. return _super.call(this, "KHR_materials_common") || this;
  82338. }
  82339. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  82340. if (!gltfRuntime.extensions)
  82341. return false;
  82342. var extension = gltfRuntime.extensions[this.name];
  82343. if (!extension)
  82344. return false;
  82345. // Create lights
  82346. var lights = extension.lights;
  82347. if (lights) {
  82348. for (var thing in lights) {
  82349. var light = lights[thing];
  82350. switch (light.type) {
  82351. case "ambient":
  82352. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  82353. var ambient = light.ambient;
  82354. if (ambient) {
  82355. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  82356. }
  82357. break;
  82358. case "point":
  82359. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  82360. var point = light.point;
  82361. if (point) {
  82362. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  82363. }
  82364. break;
  82365. case "directional":
  82366. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  82367. var directional = light.directional;
  82368. if (directional) {
  82369. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  82370. }
  82371. break;
  82372. case "spot":
  82373. var spot = light.spot;
  82374. if (spot) {
  82375. var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);
  82376. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  82377. }
  82378. break;
  82379. default:
  82380. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  82381. break;
  82382. }
  82383. }
  82384. }
  82385. return false;
  82386. };
  82387. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  82388. var material = gltfRuntime.materials[id];
  82389. if (!material || !material.extensions)
  82390. return false;
  82391. var extension = material.extensions[this.name];
  82392. if (!extension)
  82393. return false;
  82394. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  82395. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  82396. if (extension.technique === "CONSTANT") {
  82397. standardMaterial.disableLighting = true;
  82398. }
  82399. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  82400. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  82401. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  82402. // Ambient
  82403. if (typeof extension.values.ambient === "string") {
  82404. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  82405. }
  82406. else {
  82407. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  82408. }
  82409. // Diffuse
  82410. if (typeof extension.values.diffuse === "string") {
  82411. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  82412. }
  82413. else {
  82414. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  82415. }
  82416. // Emission
  82417. if (typeof extension.values.emission === "string") {
  82418. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  82419. }
  82420. else {
  82421. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  82422. }
  82423. // Specular
  82424. if (typeof extension.values.specular === "string") {
  82425. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  82426. }
  82427. else {
  82428. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  82429. }
  82430. return true;
  82431. };
  82432. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  82433. // Create buffer from texture url
  82434. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  82435. // Create texture from buffer
  82436. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  82437. }, onError);
  82438. };
  82439. return GLTFMaterialsCommonExtension;
  82440. }(GLTF1.GLTFLoaderExtension));
  82441. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  82442. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  82443. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  82444. })(BABYLON || (BABYLON = {}));
  82445. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  82446. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  82447. var BABYLON;
  82448. (function (BABYLON) {
  82449. var GLTF2;
  82450. (function (GLTF2) {
  82451. /**
  82452. * Enums
  82453. */
  82454. var EComponentType;
  82455. (function (EComponentType) {
  82456. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  82457. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  82458. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  82459. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  82460. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  82461. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  82462. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  82463. var EMeshPrimitiveMode;
  82464. (function (EMeshPrimitiveMode) {
  82465. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  82466. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  82467. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  82468. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  82469. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  82470. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  82471. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  82472. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  82473. var ETextureMagFilter;
  82474. (function (ETextureMagFilter) {
  82475. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  82476. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  82477. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  82478. var ETextureMinFilter;
  82479. (function (ETextureMinFilter) {
  82480. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  82481. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  82482. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  82483. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  82484. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  82485. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  82486. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  82487. var ETextureWrapMode;
  82488. (function (ETextureWrapMode) {
  82489. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  82490. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  82491. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  82492. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  82493. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  82494. })(BABYLON || (BABYLON = {}));
  82495. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  82496. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  82497. var BABYLON;
  82498. (function (BABYLON) {
  82499. var GLTF2;
  82500. (function (GLTF2) {
  82501. var GLTFLoaderTracker = /** @class */ (function () {
  82502. function GLTFLoaderTracker(onComplete) {
  82503. this._pendingCount = 0;
  82504. this._callback = onComplete;
  82505. }
  82506. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  82507. this._pendingCount++;
  82508. };
  82509. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  82510. if (--this._pendingCount === 0) {
  82511. this._callback();
  82512. }
  82513. };
  82514. return GLTFLoaderTracker;
  82515. }());
  82516. var GLTFLoader = /** @class */ (function () {
  82517. function GLTFLoader(parent) {
  82518. this._disposed = false;
  82519. this._defaultSampler = {};
  82520. this._renderReady = false;
  82521. this._requests = new Array();
  82522. this._renderReadyObservable = new BABYLON.Observable();
  82523. // Count of pending work that needs to complete before the asset is rendered.
  82524. this._renderPendingCount = 0;
  82525. // Count of pending work that needs to complete before the loader is disposed.
  82526. this._loaderPendingCount = 0;
  82527. this._loaderTrackers = new Array();
  82528. this._parent = parent;
  82529. }
  82530. GLTFLoader.RegisterExtension = function (extension) {
  82531. if (GLTFLoader.Extensions[extension.name]) {
  82532. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  82533. return;
  82534. }
  82535. GLTFLoader.Extensions[extension.name] = extension;
  82536. // Keep the order of registration so that extensions registered first are called first.
  82537. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  82538. };
  82539. GLTFLoader.prototype.dispose = function () {
  82540. if (this._disposed) {
  82541. return;
  82542. }
  82543. this._disposed = true;
  82544. // Abort requests that are not complete
  82545. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  82546. var request = _a[_i];
  82547. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  82548. request.abort();
  82549. }
  82550. }
  82551. // Revoke object urls created during load
  82552. if (this._gltf.textures) {
  82553. for (var _b = 0, _c = this._gltf.textures; _b < _c.length; _b++) {
  82554. var texture = _c[_b];
  82555. if (texture.url) {
  82556. URL.revokeObjectURL(texture.url);
  82557. }
  82558. }
  82559. }
  82560. };
  82561. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  82562. var _this = this;
  82563. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  82564. if (onSuccess) {
  82565. onSuccess(_this._getMeshes(), [], _this._getSkeletons());
  82566. }
  82567. }, onProgress, onError);
  82568. };
  82569. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  82570. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  82571. };
  82572. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  82573. var _this = this;
  82574. this._babylonScene = scene;
  82575. this._rootUrl = rootUrl;
  82576. this._successCallback = onSuccess;
  82577. this._progressCallback = onProgress;
  82578. this._errorCallback = onError;
  82579. this._tryCatchOnError(function () {
  82580. _this._loadData(data);
  82581. _this._addPendingData(_this);
  82582. _this._loadDefaultScene(nodeNames);
  82583. _this._loadAnimations();
  82584. _this._removePendingData(_this);
  82585. });
  82586. };
  82587. GLTFLoader.prototype._onProgress = function () {
  82588. if (!this._progressCallback) {
  82589. return;
  82590. }
  82591. var lengthComputable = true;
  82592. var loaded = 0;
  82593. var total = 0;
  82594. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  82595. var request = _a[_i];
  82596. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  82597. return;
  82598. }
  82599. lengthComputable = lengthComputable && request._lengthComputable;
  82600. loaded += request._loaded;
  82601. total += request._total;
  82602. }
  82603. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  82604. };
  82605. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  82606. if (this._renderReady) {
  82607. func();
  82608. }
  82609. else {
  82610. this._renderReadyObservable.add(func);
  82611. }
  82612. };
  82613. GLTFLoader.prototype._onRenderReady = function () {
  82614. this._rootNode.babylonMesh.setEnabled(true);
  82615. this._startAnimations();
  82616. if (this._successCallback) {
  82617. this._successCallback();
  82618. }
  82619. this._renderReadyObservable.notifyObservers(this);
  82620. };
  82621. GLTFLoader.prototype._onComplete = function () {
  82622. if (this._parent.onComplete) {
  82623. this._parent.onComplete();
  82624. }
  82625. this.dispose();
  82626. };
  82627. GLTFLoader.prototype._loadData = function (data) {
  82628. this._gltf = data.json;
  82629. // Assign the index of each object for convinience.
  82630. GLTFLoader._AssignIndices(this._gltf.accessors);
  82631. GLTFLoader._AssignIndices(this._gltf.animations);
  82632. GLTFLoader._AssignIndices(this._gltf.buffers);
  82633. GLTFLoader._AssignIndices(this._gltf.bufferViews);
  82634. GLTFLoader._AssignIndices(this._gltf.images);
  82635. GLTFLoader._AssignIndices(this._gltf.materials);
  82636. GLTFLoader._AssignIndices(this._gltf.meshes);
  82637. GLTFLoader._AssignIndices(this._gltf.nodes);
  82638. GLTFLoader._AssignIndices(this._gltf.samplers);
  82639. GLTFLoader._AssignIndices(this._gltf.scenes);
  82640. GLTFLoader._AssignIndices(this._gltf.skins);
  82641. GLTFLoader._AssignIndices(this._gltf.textures);
  82642. if (data.bin) {
  82643. var buffers = this._gltf.buffers;
  82644. if (buffers && buffers[0] && !buffers[0].uri) {
  82645. var binaryBuffer = buffers[0];
  82646. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  82647. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  82648. }
  82649. binaryBuffer.loadedData = data.bin;
  82650. }
  82651. else {
  82652. BABYLON.Tools.Warn("Unexpected BIN chunk");
  82653. }
  82654. }
  82655. };
  82656. GLTFLoader.prototype._getMeshes = function () {
  82657. var meshes = new Array();
  82658. // Root mesh is always first.
  82659. meshes.push(this._rootNode.babylonMesh);
  82660. var nodes = this._gltf.nodes;
  82661. if (nodes) {
  82662. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  82663. var node = nodes_1[_i];
  82664. if (node.babylonMesh) {
  82665. meshes.push(node.babylonMesh);
  82666. }
  82667. }
  82668. }
  82669. return meshes;
  82670. };
  82671. GLTFLoader.prototype._getSkeletons = function () {
  82672. var skeletons = new Array();
  82673. var skins = this._gltf.skins;
  82674. if (skins) {
  82675. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  82676. var skin = skins_1[_i];
  82677. if (skin.babylonSkeleton) {
  82678. skeletons.push(skin.babylonSkeleton);
  82679. }
  82680. }
  82681. }
  82682. return skeletons;
  82683. };
  82684. GLTFLoader.prototype._startAnimations = function () {
  82685. var animations = this._gltf.animations;
  82686. if (!animations) {
  82687. return;
  82688. }
  82689. switch (this._parent.animationStartMode) {
  82690. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  82691. // do nothing
  82692. break;
  82693. }
  82694. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  82695. var animation = animations[0];
  82696. for (var _i = 0, _a = animation.targets; _i < _a.length; _i++) {
  82697. var target = _a[_i];
  82698. this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true);
  82699. }
  82700. break;
  82701. }
  82702. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  82703. for (var _b = 0, animations_1 = animations; _b < animations_1.length; _b++) {
  82704. var animation = animations_1[_b];
  82705. for (var _c = 0, _d = animation.targets; _c < _d.length; _c++) {
  82706. var target = _d[_c];
  82707. this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true);
  82708. }
  82709. }
  82710. break;
  82711. }
  82712. default: {
  82713. BABYLON.Tools.Error("Invalid animation start mode " + this._parent.animationStartMode);
  82714. return;
  82715. }
  82716. }
  82717. };
  82718. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  82719. var scene = GLTFLoader._GetProperty(this._gltf.scenes, this._gltf.scene || 0);
  82720. if (!scene) {
  82721. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  82722. }
  82723. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  82724. };
  82725. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  82726. var _this = this;
  82727. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  82728. switch (this._parent.coordinateSystemMode) {
  82729. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  82730. if (!this._babylonScene.useRightHandedSystem) {
  82731. this._rootNode.rotation = [0, 1, 0, 0];
  82732. this._rootNode.scale = [1, 1, -1];
  82733. this._loadTransform(this._rootNode);
  82734. }
  82735. break;
  82736. }
  82737. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  82738. this._babylonScene.useRightHandedSystem = true;
  82739. break;
  82740. }
  82741. default: {
  82742. BABYLON.Tools.Error("Invalid coordinate system mode " + this._parent.coordinateSystemMode);
  82743. return;
  82744. }
  82745. }
  82746. if (this._parent.onMeshLoaded) {
  82747. this._parent.onMeshLoaded(this._rootNode.babylonMesh);
  82748. }
  82749. var nodeIndices = scene.nodes;
  82750. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  82751. node.parent = parentNode;
  82752. return true;
  82753. }, this._rootNode);
  82754. if (nodeNames) {
  82755. if (!(nodeNames instanceof Array)) {
  82756. nodeNames = [nodeNames];
  82757. }
  82758. var filteredNodeIndices_1 = new Array();
  82759. this._traverseNodes(context, nodeIndices, function (node) {
  82760. if (nodeNames.indexOf(node.name) !== -1) {
  82761. filteredNodeIndices_1.push(node.index);
  82762. node.parent = _this._rootNode;
  82763. return false;
  82764. }
  82765. return true;
  82766. }, this._rootNode);
  82767. nodeIndices = filteredNodeIndices_1;
  82768. }
  82769. for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) {
  82770. var index = nodeIndices_1[_i];
  82771. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  82772. if (!node) {
  82773. throw new Error(context + ": Failed to find node " + index);
  82774. }
  82775. this._loadNode("#/nodes/" + index, node);
  82776. }
  82777. // Disable the root mesh until the asset is ready to render.
  82778. this._rootNode.babylonMesh.setEnabled(false);
  82779. };
  82780. GLTFLoader.prototype._loadNode = function (context, node) {
  82781. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  82782. return;
  82783. }
  82784. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  82785. node.babylonMesh.hasVertexAlpha = true;
  82786. this._loadTransform(node);
  82787. if (node.mesh != null) {
  82788. var mesh = GLTFLoader._GetProperty(this._gltf.meshes, node.mesh);
  82789. if (!mesh) {
  82790. throw new Error(context + ": Failed to find mesh " + node.mesh);
  82791. }
  82792. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  82793. }
  82794. node.babylonMesh.parent = node.parent.babylonMesh;
  82795. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  82796. node.babylonAnimationTargets.push(node.babylonMesh);
  82797. if (node.skin != null) {
  82798. var skin_1 = GLTFLoader._GetProperty(this._gltf.skins, node.skin);
  82799. if (!skin_1) {
  82800. throw new Error(context + ": Failed to find skin " + node.skin);
  82801. }
  82802. this._loadSkinAsync("#/skins/" + node.skin, skin_1, function () {
  82803. node.babylonMesh.skeleton = skin_1.babylonSkeleton;
  82804. node.babylonMesh._refreshBoundingInfo(true);
  82805. });
  82806. node.babylonMesh.parent = this._rootNode.babylonMesh;
  82807. node.babylonMesh.position = BABYLON.Vector3.Zero();
  82808. node.babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  82809. node.babylonMesh.scaling = BABYLON.Vector3.One();
  82810. }
  82811. if (node.camera != null) {
  82812. // TODO: handle cameras
  82813. }
  82814. if (node.children) {
  82815. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  82816. var index = _a[_i];
  82817. var childNode = GLTFLoader._GetProperty(this._gltf.nodes, index);
  82818. if (!childNode) {
  82819. throw new Error(context + ": Failed to find child node " + index);
  82820. }
  82821. this._loadNode("#/nodes/" + index, childNode);
  82822. }
  82823. }
  82824. if (this._parent.onMeshLoaded) {
  82825. this._parent.onMeshLoaded(node.babylonMesh);
  82826. }
  82827. };
  82828. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  82829. var _this = this;
  82830. var primitives = mesh.primitives;
  82831. if (!primitives || primitives.length === 0) {
  82832. throw new Error(context + ": Primitives are missing");
  82833. }
  82834. this._createMorphTargets(context, node, mesh);
  82835. this._loadAllVertexDataAsync(context, mesh, function () {
  82836. _this._loadMorphTargets(context, node, mesh);
  82837. var vertexData = new BABYLON.VertexData();
  82838. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  82839. var primitive = primitives_1[_i];
  82840. vertexData.merge(primitive.vertexData);
  82841. }
  82842. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  82843. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  82844. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  82845. node.babylonMesh.subMeshes = [];
  82846. var verticesStart = 0;
  82847. var indicesStart = 0;
  82848. for (var index = 0; index < primitives.length; index++) {
  82849. var vertexData_1 = primitives[index].vertexData;
  82850. var verticesCount = vertexData_1.positions.length;
  82851. var indicesCount = vertexData_1.indices.length;
  82852. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  82853. verticesStart += verticesCount;
  82854. indicesStart += indicesCount;
  82855. }
  82856. ;
  82857. });
  82858. if (primitives.length === 1) {
  82859. var primitive = primitives[0];
  82860. if (primitive.material == null) {
  82861. node.babylonMesh.material = this._getDefaultMaterial();
  82862. }
  82863. else {
  82864. var material = GLTFLoader._GetProperty(this._gltf.materials, primitive.material);
  82865. if (!material) {
  82866. throw new Error(context + ": Failed to find material " + primitive.material);
  82867. }
  82868. this._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  82869. if (isNew && _this._parent.onMaterialLoaded) {
  82870. _this._parent.onMaterialLoaded(babylonMaterial);
  82871. }
  82872. node.babylonMesh.material = babylonMaterial;
  82873. });
  82874. }
  82875. }
  82876. else {
  82877. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  82878. node.babylonMesh.material = multiMaterial;
  82879. var subMaterials_1 = multiMaterial.subMaterials;
  82880. var _loop_1 = function (index) {
  82881. var primitive = primitives[index];
  82882. if (primitive.material == null) {
  82883. subMaterials_1[index] = this_1._getDefaultMaterial();
  82884. }
  82885. else {
  82886. var material = GLTFLoader._GetProperty(this_1._gltf.materials, primitive.material);
  82887. if (!material) {
  82888. throw new Error(context + ": Failed to find material " + primitive.material);
  82889. }
  82890. this_1._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  82891. if (isNew && _this._parent.onMaterialLoaded) {
  82892. _this._parent.onMaterialLoaded(babylonMaterial);
  82893. }
  82894. subMaterials_1[index] = babylonMaterial;
  82895. });
  82896. }
  82897. };
  82898. var this_1 = this;
  82899. for (var index = 0; index < primitives.length; index++) {
  82900. _loop_1(index);
  82901. }
  82902. ;
  82903. }
  82904. };
  82905. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  82906. var primitives = mesh.primitives;
  82907. var numRemainingPrimitives = primitives.length;
  82908. var _loop_2 = function (index) {
  82909. var primitive = primitives[index];
  82910. this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  82911. primitive.vertexData = vertexData;
  82912. if (--numRemainingPrimitives === 0) {
  82913. onSuccess();
  82914. }
  82915. });
  82916. };
  82917. var this_2 = this;
  82918. for (var index = 0; index < primitives.length; index++) {
  82919. _loop_2(index);
  82920. }
  82921. };
  82922. /**
  82923. * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
  82924. * @param {ArrayBufferView} data
  82925. * @param {IGLTFAccessor} accessor
  82926. */
  82927. GLTFLoader.prototype._convertToFloat4TextureCoordArray = function (context, data, accessor) {
  82928. if (accessor.componentType == GLTF2.EComponentType.FLOAT) {
  82929. return data;
  82930. }
  82931. var buffer = data;
  82932. var factor = 1;
  82933. switch (accessor.componentType) {
  82934. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  82935. factor = 1 / 255;
  82936. break;
  82937. }
  82938. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  82939. factor = 1 / 65535;
  82940. break;
  82941. }
  82942. default: {
  82943. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  82944. }
  82945. }
  82946. var result = new Float32Array(accessor.count * 2);
  82947. for (var i = 0; i < result.length; ++i) {
  82948. result[i] = buffer[i] * factor;
  82949. }
  82950. return result;
  82951. };
  82952. /**
  82953. * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
  82954. * @param {ArrayBufferView} data
  82955. * @param {IGLTFAccessor} accessor
  82956. */
  82957. GLTFLoader.prototype._convertToFloat4ColorArray = function (context, data, accessor) {
  82958. var colorComponentCount = GLTFLoader._GetNumComponents(context, accessor.type);
  82959. if (colorComponentCount === 4 && accessor.componentType === GLTF2.EComponentType.FLOAT) {
  82960. return data;
  82961. }
  82962. var buffer = data;
  82963. var factor = 1;
  82964. switch (accessor.componentType) {
  82965. case GLTF2.EComponentType.FLOAT: {
  82966. factor = 1;
  82967. break;
  82968. }
  82969. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  82970. factor = 1 / 255;
  82971. break;
  82972. }
  82973. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  82974. factor = 1 / 65535;
  82975. break;
  82976. }
  82977. default: {
  82978. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  82979. }
  82980. }
  82981. var result = new Float32Array(accessor.count * 4);
  82982. if (colorComponentCount === 4) {
  82983. for (var i = 0; i < result.length; ++i) {
  82984. result[i] = buffer[i] * factor;
  82985. }
  82986. }
  82987. else {
  82988. var offset = 0;
  82989. for (var i = 0; i < result.length; ++i) {
  82990. if ((i + 1) % 4 === 0) {
  82991. result[i] = 1;
  82992. }
  82993. else {
  82994. result[i] = buffer[offset++] * factor;
  82995. }
  82996. }
  82997. }
  82998. return result;
  82999. };
  83000. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  83001. var _this = this;
  83002. var attributes = primitive.attributes;
  83003. if (!attributes) {
  83004. throw new Error(context + ": Attributes are missing");
  83005. }
  83006. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  83007. // TODO: handle other primitive modes
  83008. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  83009. }
  83010. var vertexData = new BABYLON.VertexData();
  83011. var numRemainingAttributes = Object.keys(attributes).length;
  83012. var _loop_3 = function (attribute) {
  83013. var accessor = GLTFLoader._GetProperty(this_3._gltf.accessors, attributes[attribute]);
  83014. if (!accessor) {
  83015. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  83016. }
  83017. this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  83018. switch (attribute) {
  83019. case "POSITION": {
  83020. vertexData.positions = data;
  83021. break;
  83022. }
  83023. case "NORMAL": {
  83024. vertexData.normals = data;
  83025. break;
  83026. }
  83027. case "TANGENT": {
  83028. vertexData.tangents = data;
  83029. break;
  83030. }
  83031. case "TEXCOORD_0": {
  83032. vertexData.uvs = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  83033. break;
  83034. }
  83035. case "TEXCOORD_1": {
  83036. vertexData.uvs2 = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  83037. break;
  83038. }
  83039. case "JOINTS_0": {
  83040. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  83041. break;
  83042. }
  83043. case "WEIGHTS_0": {
  83044. //TODO: need to add support for normalized weights.
  83045. vertexData.matricesWeights = data;
  83046. break;
  83047. }
  83048. case "COLOR_0": {
  83049. vertexData.colors = _this._convertToFloat4ColorArray(context, data, accessor);
  83050. break;
  83051. }
  83052. default: {
  83053. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  83054. break;
  83055. }
  83056. }
  83057. if (--numRemainingAttributes === 0) {
  83058. if (primitive.indices == null) {
  83059. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  83060. for (var i = 0; i < vertexData.indices.length; i++) {
  83061. vertexData.indices[i] = i;
  83062. }
  83063. onSuccess(vertexData);
  83064. }
  83065. else {
  83066. var indicesAccessor = GLTFLoader._GetProperty(_this._gltf.accessors, primitive.indices);
  83067. if (!indicesAccessor) {
  83068. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  83069. }
  83070. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  83071. vertexData.indices = data;
  83072. onSuccess(vertexData);
  83073. });
  83074. }
  83075. }
  83076. });
  83077. };
  83078. var this_3 = this;
  83079. for (var attribute in attributes) {
  83080. _loop_3(attribute);
  83081. }
  83082. };
  83083. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  83084. var primitives = mesh.primitives;
  83085. var targets = primitives[0].targets;
  83086. if (!targets) {
  83087. return;
  83088. }
  83089. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  83090. var primitive = primitives_2[_i];
  83091. if (!primitive.targets || primitive.targets.length != targets.length) {
  83092. throw new Error(context + ": All primitives are required to list the same number of targets");
  83093. }
  83094. }
  83095. var morphTargetManager = new BABYLON.MorphTargetManager();
  83096. node.babylonMesh.morphTargetManager = morphTargetManager;
  83097. for (var index = 0; index < targets.length; index++) {
  83098. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  83099. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  83100. }
  83101. };
  83102. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  83103. var morphTargetManager = node.babylonMesh.morphTargetManager;
  83104. if (!morphTargetManager) {
  83105. return;
  83106. }
  83107. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  83108. var numTargets = morphTargetManager.numTargets;
  83109. for (var index = 0; index < numTargets; index++) {
  83110. var vertexData = new BABYLON.VertexData();
  83111. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  83112. var primitive = _a[_i];
  83113. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  83114. }
  83115. if (!vertexData.positions) {
  83116. throw new Error(context + ": Positions are missing");
  83117. }
  83118. var target = morphTargetManager.getTarget(index);
  83119. target.setPositions(vertexData.positions);
  83120. target.setNormals(vertexData.normals);
  83121. target.setTangents(vertexData.tangents);
  83122. }
  83123. });
  83124. };
  83125. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  83126. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  83127. var _loop_4 = function (primitive) {
  83128. var targets = primitive.targets;
  83129. primitive.targetsVertexData = new Array(targets.length);
  83130. var _loop_5 = function (index) {
  83131. this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  83132. primitive.targetsVertexData[index] = vertexData;
  83133. if (--numRemainingTargets === 0) {
  83134. onSuccess();
  83135. }
  83136. });
  83137. };
  83138. for (var index = 0; index < targets.length; index++) {
  83139. _loop_5(index);
  83140. }
  83141. };
  83142. var this_4 = this;
  83143. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  83144. var primitive = _a[_i];
  83145. _loop_4(primitive);
  83146. }
  83147. };
  83148. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  83149. var targetVertexData = new BABYLON.VertexData();
  83150. var numRemainingAttributes = Object.keys(attributes).length;
  83151. var _loop_6 = function (attribute) {
  83152. var accessor = GLTFLoader._GetProperty(this_5._gltf.accessors, attributes[attribute]);
  83153. if (!accessor) {
  83154. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  83155. }
  83156. this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  83157. // glTF stores morph target information as deltas while babylon.js expects the final data.
  83158. // As a result we have to add the original data to the delta to calculate the final data.
  83159. var values = data;
  83160. switch (attribute) {
  83161. case "POSITION": {
  83162. for (var i = 0; i < values.length; i++) {
  83163. values[i] += vertexData.positions[i];
  83164. }
  83165. targetVertexData.positions = values;
  83166. break;
  83167. }
  83168. case "NORMAL": {
  83169. for (var i = 0; i < values.length; i++) {
  83170. values[i] += vertexData.normals[i];
  83171. }
  83172. targetVertexData.normals = values;
  83173. break;
  83174. }
  83175. case "TANGENT": {
  83176. // Tangent data for morph targets is stored as xyz delta.
  83177. // The vertexData.tangent is stored as xyzw.
  83178. // So we need to skip every fourth vertexData.tangent.
  83179. for (var i = 0, j = 0; i < values.length; i++, j++) {
  83180. values[i] += vertexData.tangents[j];
  83181. if ((i + 1) % 3 == 0) {
  83182. j++;
  83183. }
  83184. }
  83185. targetVertexData.tangents = values;
  83186. break;
  83187. }
  83188. default: {
  83189. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  83190. break;
  83191. }
  83192. }
  83193. if (--numRemainingAttributes === 0) {
  83194. onSuccess(targetVertexData);
  83195. }
  83196. });
  83197. };
  83198. var this_5 = this;
  83199. for (var attribute in attributes) {
  83200. _loop_6(attribute);
  83201. }
  83202. };
  83203. GLTFLoader.prototype._loadTransform = function (node) {
  83204. var position = BABYLON.Vector3.Zero();
  83205. var rotation = BABYLON.Quaternion.Identity();
  83206. var scaling = BABYLON.Vector3.One();
  83207. if (node.matrix) {
  83208. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  83209. matrix.decompose(scaling, rotation, position);
  83210. }
  83211. else {
  83212. if (node.translation)
  83213. position = BABYLON.Vector3.FromArray(node.translation);
  83214. if (node.rotation)
  83215. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  83216. if (node.scale)
  83217. scaling = BABYLON.Vector3.FromArray(node.scale);
  83218. }
  83219. node.babylonMesh.position = position;
  83220. node.babylonMesh.rotationQuaternion = rotation;
  83221. node.babylonMesh.scaling = scaling;
  83222. };
  83223. GLTFLoader.prototype._loadSkinAsync = function (context, skin, onSuccess) {
  83224. var _this = this;
  83225. if (skin.babylonSkeleton) {
  83226. onSuccess();
  83227. return;
  83228. }
  83229. var skeletonId = "skeleton" + skin.index;
  83230. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  83231. if (skin.inverseBindMatrices == null) {
  83232. this._loadBones(context, skin, null);
  83233. onSuccess();
  83234. }
  83235. else {
  83236. var accessor = GLTFLoader._GetProperty(this._gltf.accessors, skin.inverseBindMatrices);
  83237. if (!accessor) {
  83238. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  83239. }
  83240. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  83241. _this._loadBones(context, skin, data);
  83242. onSuccess();
  83243. });
  83244. }
  83245. };
  83246. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  83247. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  83248. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  83249. node.babylonAnimationTargets.push(babylonBone);
  83250. return babylonBone;
  83251. };
  83252. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  83253. var babylonBones = {};
  83254. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  83255. var index = _a[_i];
  83256. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  83257. if (!node) {
  83258. throw new Error(context + ": Failed to find joint " + index);
  83259. }
  83260. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  83261. }
  83262. };
  83263. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  83264. var babylonBone = babylonBones[node.index];
  83265. if (babylonBone) {
  83266. return babylonBone;
  83267. }
  83268. var boneIndex = skin.joints.indexOf(node.index);
  83269. var baseMatrix = BABYLON.Matrix.Identity();
  83270. if (inverseBindMatrixData && boneIndex !== -1) {
  83271. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  83272. baseMatrix.invertToRef(baseMatrix);
  83273. }
  83274. var babylonParentBone = null;
  83275. if (node.parent !== this._rootNode) {
  83276. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  83277. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  83278. }
  83279. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  83280. babylonBones[node.index] = babylonBone;
  83281. return babylonBone;
  83282. };
  83283. GLTFLoader.prototype._getNodeMatrix = function (node) {
  83284. return node.matrix ?
  83285. BABYLON.Matrix.FromArray(node.matrix) :
  83286. BABYLON.Matrix.Compose(node.scale ? BABYLON.Vector3.FromArray(node.scale) : BABYLON.Vector3.One(), node.rotation ? BABYLON.Quaternion.FromArray(node.rotation) : BABYLON.Quaternion.Identity(), node.translation ? BABYLON.Vector3.FromArray(node.translation) : BABYLON.Vector3.Zero());
  83287. };
  83288. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  83289. for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) {
  83290. var index = indices_1[_i];
  83291. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  83292. if (!node) {
  83293. throw new Error(context + ": Failed to find node " + index);
  83294. }
  83295. this._traverseNode(context, node, action, parentNode);
  83296. }
  83297. };
  83298. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  83299. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  83300. return;
  83301. }
  83302. if (!action(node, parentNode)) {
  83303. return;
  83304. }
  83305. if (node.children) {
  83306. this._traverseNodes(context, node.children, action, node);
  83307. }
  83308. };
  83309. GLTFLoader.prototype._loadAnimations = function () {
  83310. var animations = this._gltf.animations;
  83311. if (!animations) {
  83312. return;
  83313. }
  83314. for (var index = 0; index < animations.length; index++) {
  83315. var animation = animations[index];
  83316. this._loadAnimation("#/animations/" + index, animation);
  83317. }
  83318. };
  83319. GLTFLoader.prototype._loadAnimation = function (context, animation) {
  83320. animation.targets = [];
  83321. for (var index = 0; index < animation.channels.length; index++) {
  83322. var channel = GLTFLoader._GetProperty(animation.channels, index);
  83323. if (!channel) {
  83324. throw new Error(context + ": Failed to find channel " + index);
  83325. }
  83326. var sampler = GLTFLoader._GetProperty(animation.samplers, channel.sampler);
  83327. if (!sampler) {
  83328. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  83329. }
  83330. this._loadAnimationChannel(animation, context + "/channels/" + index, channel, context + "/samplers/" + channel.sampler, sampler);
  83331. }
  83332. };
  83333. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  83334. var targetNode = GLTFLoader._GetProperty(this._gltf.nodes, channel.target.node);
  83335. if (!targetNode) {
  83336. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  83337. }
  83338. var targetPath;
  83339. var animationType;
  83340. switch (channel.target.path) {
  83341. case "translation": {
  83342. targetPath = "position";
  83343. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  83344. break;
  83345. }
  83346. case "rotation": {
  83347. targetPath = "rotationQuaternion";
  83348. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  83349. break;
  83350. }
  83351. case "scale": {
  83352. targetPath = "scaling";
  83353. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  83354. break;
  83355. }
  83356. case "weights": {
  83357. targetPath = "influence";
  83358. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  83359. break;
  83360. }
  83361. default: {
  83362. throw new Error(channelContext + ": Invalid target path " + channel.target.path);
  83363. }
  83364. }
  83365. var inputData;
  83366. var outputData;
  83367. var checkSuccess = function () {
  83368. if (!inputData || !outputData) {
  83369. return;
  83370. }
  83371. var outputBufferOffset = 0;
  83372. var getNextOutputValue;
  83373. switch (targetPath) {
  83374. case "position": {
  83375. getNextOutputValue = function () {
  83376. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  83377. outputBufferOffset += 3;
  83378. return value;
  83379. };
  83380. break;
  83381. }
  83382. case "rotationQuaternion": {
  83383. getNextOutputValue = function () {
  83384. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  83385. outputBufferOffset += 4;
  83386. return value;
  83387. };
  83388. break;
  83389. }
  83390. case "scaling": {
  83391. getNextOutputValue = function () {
  83392. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  83393. outputBufferOffset += 3;
  83394. return value;
  83395. };
  83396. break;
  83397. }
  83398. case "influence": {
  83399. getNextOutputValue = function () {
  83400. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  83401. var value = new Array(numTargets);
  83402. for (var i = 0; i < numTargets; i++) {
  83403. value[i] = outputData[outputBufferOffset++];
  83404. }
  83405. return value;
  83406. };
  83407. break;
  83408. }
  83409. }
  83410. var getNextKey;
  83411. switch (sampler.interpolation) {
  83412. case "LINEAR": {
  83413. getNextKey = function (frameIndex) { return ({
  83414. frame: inputData[frameIndex],
  83415. value: getNextOutputValue()
  83416. }); };
  83417. break;
  83418. }
  83419. case "CUBICSPLINE": {
  83420. getNextKey = function (frameIndex) { return ({
  83421. frame: inputData[frameIndex],
  83422. inTangent: getNextOutputValue(),
  83423. value: getNextOutputValue(),
  83424. outTangent: getNextOutputValue()
  83425. }); };
  83426. break;
  83427. }
  83428. default: {
  83429. throw new Error(samplerContext + ": Invalid interpolation " + sampler.interpolation);
  83430. }
  83431. }
  83432. ;
  83433. var keys;
  83434. if (inputData.length === 1) {
  83435. var key = getNextKey(0);
  83436. keys = [
  83437. { frame: key.frame, value: key.value },
  83438. { frame: key.frame + 1, value: key.value }
  83439. ];
  83440. }
  83441. else {
  83442. keys = new Array(inputData.length);
  83443. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  83444. keys[frameIndex] = getNextKey(frameIndex);
  83445. }
  83446. }
  83447. if (targetPath === "influence") {
  83448. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  83449. var _loop_7 = function (targetIndex) {
  83450. var morphTarget = morphTargetManager.getTarget(targetIndex);
  83451. var animationName = (animation.name || "anim" + animation.index) + "_" + targetIndex;
  83452. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  83453. babylonAnimation.setKeys(keys.map(function (key) { return ({
  83454. frame: key.frame,
  83455. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  83456. value: key.value[targetIndex],
  83457. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  83458. }); }));
  83459. morphTarget.animations.push(babylonAnimation);
  83460. animation.targets.push(morphTarget);
  83461. };
  83462. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  83463. _loop_7(targetIndex);
  83464. }
  83465. }
  83466. else {
  83467. var animationName = animation.name || "anim" + animation.index;
  83468. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  83469. babylonAnimation.setKeys(keys);
  83470. if (targetNode.babylonAnimationTargets) {
  83471. for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) {
  83472. var target = _a[_i];
  83473. target.animations.push(babylonAnimation.clone());
  83474. animation.targets.push(target);
  83475. }
  83476. }
  83477. }
  83478. };
  83479. var inputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.input);
  83480. if (!inputAccessor) {
  83481. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  83482. }
  83483. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  83484. inputData = data;
  83485. checkSuccess();
  83486. });
  83487. var outputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.output);
  83488. if (!outputAccessor) {
  83489. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  83490. }
  83491. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  83492. outputData = data;
  83493. checkSuccess();
  83494. });
  83495. };
  83496. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  83497. var _this = this;
  83498. this._addPendingData(buffer);
  83499. if (buffer.loadedData) {
  83500. onSuccess(buffer.loadedData);
  83501. this._removePendingData(buffer);
  83502. }
  83503. else if (buffer.loadedObservable) {
  83504. buffer.loadedObservable.add(function (buffer) {
  83505. onSuccess(buffer.loadedData);
  83506. _this._removePendingData(buffer);
  83507. });
  83508. }
  83509. else {
  83510. if (!buffer.uri) {
  83511. throw new Error(context + ": Uri is missing");
  83512. }
  83513. buffer.loadedObservable = new BABYLON.Observable();
  83514. buffer.loadedObservable.add(function (buffer) {
  83515. onSuccess(buffer.loadedData);
  83516. _this._removePendingData(buffer);
  83517. });
  83518. this._loadUriAsync(context, buffer.uri, function (data) {
  83519. buffer.loadedData = data;
  83520. buffer.loadedObservable.notifyObservers(buffer);
  83521. buffer.loadedObservable = undefined;
  83522. });
  83523. }
  83524. };
  83525. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  83526. var buffer = GLTFLoader._GetProperty(this._gltf.buffers, bufferView.buffer);
  83527. if (!buffer) {
  83528. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  83529. }
  83530. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  83531. var data;
  83532. try {
  83533. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  83534. }
  83535. catch (e) {
  83536. throw new Error(context + ": " + e.message);
  83537. }
  83538. onSuccess(data);
  83539. });
  83540. };
  83541. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  83542. var _this = this;
  83543. if (accessor.sparse) {
  83544. throw new Error(context + ": Sparse accessors are not currently supported");
  83545. }
  83546. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, accessor.bufferView);
  83547. if (!bufferView) {
  83548. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  83549. }
  83550. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  83551. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  83552. var data;
  83553. var byteOffset = accessor.byteOffset || 0;
  83554. var byteStride = bufferView.byteStride;
  83555. if (byteStride === 0) {
  83556. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  83557. }
  83558. try {
  83559. switch (accessor.componentType) {
  83560. case GLTF2.EComponentType.BYTE: {
  83561. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  83562. break;
  83563. }
  83564. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  83565. data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  83566. break;
  83567. }
  83568. case GLTF2.EComponentType.SHORT: {
  83569. data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  83570. break;
  83571. }
  83572. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  83573. data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  83574. break;
  83575. }
  83576. case GLTF2.EComponentType.UNSIGNED_INT: {
  83577. data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  83578. break;
  83579. }
  83580. case GLTF2.EComponentType.FLOAT: {
  83581. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  83582. break;
  83583. }
  83584. default: {
  83585. throw new Error(context + ": Invalid component type " + accessor.componentType);
  83586. }
  83587. }
  83588. }
  83589. catch (e) {
  83590. throw new Error(context + ": " + e);
  83591. }
  83592. onSuccess(data);
  83593. });
  83594. };
  83595. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  83596. byteOffset += data.byteOffset;
  83597. var targetLength = count * numComponents;
  83598. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  83599. return new typedArray(data.buffer, byteOffset, targetLength);
  83600. }
  83601. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  83602. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  83603. var targetBuffer = new typedArray(targetLength);
  83604. var sourceIndex = 0;
  83605. var targetIndex = 0;
  83606. while (targetIndex < targetLength) {
  83607. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  83608. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  83609. targetIndex++;
  83610. }
  83611. sourceIndex += elementStride;
  83612. }
  83613. return targetBuffer;
  83614. };
  83615. GLTFLoader.prototype._addPendingData = function (data) {
  83616. if (!this._renderReady) {
  83617. this._renderPendingCount++;
  83618. }
  83619. this._addLoaderPendingData(data);
  83620. };
  83621. GLTFLoader.prototype._removePendingData = function (data) {
  83622. var _this = this;
  83623. if (!this._renderReady) {
  83624. if (--this._renderPendingCount === 0) {
  83625. this._addLoaderPendingData(this);
  83626. this._compileMaterialsAsync(function () {
  83627. _this._compileShadowGeneratorsAsync(function () {
  83628. _this._removeLoaderPendingData(_this);
  83629. _this._renderReady = true;
  83630. _this._onRenderReady();
  83631. });
  83632. });
  83633. }
  83634. }
  83635. this._removeLoaderPendingData(data);
  83636. };
  83637. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  83638. this._loaderPendingCount++;
  83639. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  83640. var tracker = _a[_i];
  83641. tracker._addPendingData(data);
  83642. }
  83643. };
  83644. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  83645. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  83646. var tracker = _a[_i];
  83647. tracker._removePendingData(data);
  83648. }
  83649. if (--this._loaderPendingCount === 0) {
  83650. this._onComplete();
  83651. }
  83652. };
  83653. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  83654. var _this = this;
  83655. var tracker = new GLTFLoaderTracker(function () {
  83656. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1);
  83657. onComplete();
  83658. });
  83659. this._loaderTrackers.push(tracker);
  83660. this._addLoaderPendingData(tracker);
  83661. action();
  83662. this._removeLoaderPendingData(tracker);
  83663. };
  83664. GLTFLoader.prototype._getDefaultMaterial = function () {
  83665. if (!this._defaultMaterial) {
  83666. var id = "__gltf_default";
  83667. var material = this._babylonScene.getMaterialByName(id);
  83668. if (!material) {
  83669. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  83670. material.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  83671. material.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  83672. material.metallic = 1;
  83673. material.roughness = 1;
  83674. }
  83675. this._defaultMaterial = material;
  83676. }
  83677. return this._defaultMaterial;
  83678. };
  83679. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  83680. var babylonMaterial = material.babylonMaterial;
  83681. // Ensure metallic workflow
  83682. babylonMaterial.metallic = 1;
  83683. babylonMaterial.roughness = 1;
  83684. var properties = material.pbrMetallicRoughness;
  83685. if (!properties) {
  83686. return;
  83687. }
  83688. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  83689. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  83690. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  83691. if (properties.baseColorTexture) {
  83692. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.baseColorTexture.index);
  83693. if (!texture) {
  83694. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  83695. }
  83696. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  83697. }
  83698. if (properties.metallicRoughnessTexture) {
  83699. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.metallicRoughnessTexture.index);
  83700. if (!texture) {
  83701. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  83702. }
  83703. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  83704. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  83705. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  83706. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  83707. }
  83708. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  83709. };
  83710. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  83711. if (material.babylonMaterial) {
  83712. assign(material.babylonMaterial, false);
  83713. return;
  83714. }
  83715. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  83716. return;
  83717. }
  83718. this._createPbrMaterial(material);
  83719. this._loadMaterialBaseProperties(context, material);
  83720. this._loadMaterialMetallicRoughnessProperties(context, material);
  83721. assign(material.babylonMaterial, true);
  83722. };
  83723. GLTFLoader.prototype._createPbrMaterial = function (material) {
  83724. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  83725. babylonMaterial.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  83726. material.babylonMaterial = babylonMaterial;
  83727. };
  83728. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  83729. var babylonMaterial = material.babylonMaterial;
  83730. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  83731. if (material.doubleSided) {
  83732. babylonMaterial.backFaceCulling = false;
  83733. babylonMaterial.twoSidedLighting = true;
  83734. }
  83735. if (material.normalTexture) {
  83736. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.normalTexture.index);
  83737. if (!texture) {
  83738. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  83739. }
  83740. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  83741. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  83742. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  83743. if (material.normalTexture.scale != null) {
  83744. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  83745. }
  83746. }
  83747. if (material.occlusionTexture) {
  83748. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.occlusionTexture.index);
  83749. if (!texture) {
  83750. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  83751. }
  83752. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  83753. babylonMaterial.useAmbientInGrayScale = true;
  83754. if (material.occlusionTexture.strength != null) {
  83755. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  83756. }
  83757. }
  83758. if (material.emissiveTexture) {
  83759. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.emissiveTexture.index);
  83760. if (!texture) {
  83761. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  83762. }
  83763. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  83764. }
  83765. };
  83766. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  83767. var babylonMaterial = material.babylonMaterial;
  83768. var alphaMode = material.alphaMode || "OPAQUE";
  83769. switch (alphaMode) {
  83770. case "OPAQUE": {
  83771. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  83772. break;
  83773. }
  83774. case "MASK": {
  83775. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  83776. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  83777. if (colorFactor) {
  83778. if (colorFactor[3] == 0) {
  83779. babylonMaterial.alphaCutOff = 1;
  83780. }
  83781. else {
  83782. babylonMaterial.alphaCutOff /= colorFactor[3];
  83783. }
  83784. }
  83785. if (babylonMaterial.albedoTexture) {
  83786. babylonMaterial.albedoTexture.hasAlpha = true;
  83787. }
  83788. break;
  83789. }
  83790. case "BLEND": {
  83791. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  83792. if (colorFactor) {
  83793. babylonMaterial.alpha = colorFactor[3];
  83794. }
  83795. if (babylonMaterial.albedoTexture) {
  83796. babylonMaterial.albedoTexture.hasAlpha = true;
  83797. babylonMaterial.useAlphaFromAlbedoTexture = true;
  83798. }
  83799. break;
  83800. }
  83801. default: {
  83802. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  83803. }
  83804. }
  83805. };
  83806. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  83807. var _this = this;
  83808. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(this._gltf.samplers, texture.sampler));
  83809. if (!sampler) {
  83810. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  83811. }
  83812. this._loadSampler("#/samplers/" + sampler.index, sampler);
  83813. this._addPendingData(texture);
  83814. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, sampler.noMipMaps, false, sampler.samplingMode, function () {
  83815. _this._tryCatchOnError(function () {
  83816. _this._removePendingData(texture);
  83817. });
  83818. }, function (message) {
  83819. _this._tryCatchOnError(function () {
  83820. throw new Error(context + ": " + message);
  83821. });
  83822. });
  83823. if (texture.url) {
  83824. babylonTexture.updateURL(texture.url);
  83825. }
  83826. else if (texture.dataReadyObservable) {
  83827. texture.dataReadyObservable.add(function (texture) {
  83828. babylonTexture.updateURL(texture.url);
  83829. });
  83830. }
  83831. else {
  83832. texture.dataReadyObservable = new BABYLON.Observable();
  83833. texture.dataReadyObservable.add(function (texture) {
  83834. babylonTexture.updateURL(texture.url);
  83835. });
  83836. var image_1 = GLTFLoader._GetProperty(this._gltf.images, texture.source);
  83837. if (!image_1) {
  83838. throw new Error(context + ": Failed to find source " + texture.source);
  83839. }
  83840. this._loadImageAsync("#/images/" + image_1.index, image_1, function (data) {
  83841. texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType }));
  83842. texture.dataReadyObservable.notifyObservers(texture);
  83843. texture.dataReadyObservable = undefined;
  83844. });
  83845. }
  83846. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  83847. babylonTexture.wrapU = sampler.wrapU;
  83848. babylonTexture.wrapV = sampler.wrapV;
  83849. babylonTexture.name = texture.name || "texture" + texture.index;
  83850. if (this._parent.onTextureLoaded) {
  83851. this._parent.onTextureLoaded(babylonTexture);
  83852. }
  83853. return babylonTexture;
  83854. };
  83855. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  83856. if (sampler.noMipMaps != undefined) {
  83857. return;
  83858. }
  83859. sampler.noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  83860. sampler.samplingMode = GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter);
  83861. sampler.wrapU = GLTFLoader._GetTextureWrapMode(context, sampler.wrapS);
  83862. sampler.wrapV = GLTFLoader._GetTextureWrapMode(context, sampler.wrapT);
  83863. };
  83864. GLTFLoader.prototype._loadImageAsync = function (context, image, onSuccess) {
  83865. if (image.uri) {
  83866. this._loadUriAsync(context, image.uri, onSuccess);
  83867. }
  83868. else {
  83869. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, image.bufferView);
  83870. if (!bufferView) {
  83871. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  83872. }
  83873. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  83874. }
  83875. };
  83876. GLTFLoader.prototype._loadUriAsync = function (context, uri, onSuccess) {
  83877. var _this = this;
  83878. if (GLTF2.GLTFUtils.IsBase64(uri)) {
  83879. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(uri)));
  83880. return;
  83881. }
  83882. if (!GLTF2.GLTFUtils.ValidateUri(uri)) {
  83883. throw new Error(context + ": Uri '" + uri + "' is invalid");
  83884. }
  83885. var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) {
  83886. _this._tryCatchOnError(function () {
  83887. onSuccess(new Uint8Array(data));
  83888. });
  83889. }, function (event) {
  83890. _this._tryCatchOnError(function () {
  83891. if (request && !_this._renderReady) {
  83892. request._lengthComputable = event.lengthComputable;
  83893. request._loaded = event.loaded;
  83894. request._total = event.total;
  83895. _this._onProgress();
  83896. }
  83897. });
  83898. }, this._babylonScene.database, true, function (request, exception) {
  83899. _this._tryCatchOnError(function () {
  83900. throw new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request);
  83901. });
  83902. }, function (oldRequest, newRequest) {
  83903. _this._requests.splice(_this._requests.indexOf(oldRequest), 1, newRequest);
  83904. });
  83905. if (request) {
  83906. this._requests.push(request);
  83907. }
  83908. };
  83909. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  83910. if (this._disposed) {
  83911. return;
  83912. }
  83913. try {
  83914. handler();
  83915. }
  83916. catch (e) {
  83917. BABYLON.Tools.Error("glTF Loader: " + e.message);
  83918. if (this._errorCallback) {
  83919. this._errorCallback(e.message, e);
  83920. }
  83921. this.dispose();
  83922. }
  83923. };
  83924. GLTFLoader._AssignIndices = function (array) {
  83925. if (array) {
  83926. for (var index = 0; index < array.length; index++) {
  83927. array[index].index = index;
  83928. }
  83929. }
  83930. };
  83931. GLTFLoader._GetProperty = function (array, index) {
  83932. if (!array || index == undefined || !array[index]) {
  83933. return null;
  83934. }
  83935. return array[index];
  83936. };
  83937. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  83938. // Set defaults if undefined
  83939. mode = mode == undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  83940. switch (mode) {
  83941. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  83942. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  83943. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  83944. default:
  83945. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  83946. return BABYLON.Texture.WRAP_ADDRESSMODE;
  83947. }
  83948. };
  83949. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  83950. // Set defaults if undefined
  83951. magFilter = magFilter == undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  83952. minFilter = minFilter == undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  83953. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  83954. switch (minFilter) {
  83955. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  83956. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  83957. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  83958. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  83959. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  83960. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  83961. default:
  83962. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  83963. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  83964. }
  83965. }
  83966. else {
  83967. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  83968. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  83969. }
  83970. switch (minFilter) {
  83971. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  83972. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  83973. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  83974. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  83975. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  83976. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  83977. default:
  83978. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  83979. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  83980. }
  83981. }
  83982. };
  83983. GLTFLoader._GetNumComponents = function (context, type) {
  83984. switch (type) {
  83985. case "SCALAR": return 1;
  83986. case "VEC2": return 2;
  83987. case "VEC3": return 3;
  83988. case "VEC4": return 4;
  83989. case "MAT2": return 4;
  83990. case "MAT3": return 9;
  83991. case "MAT4": return 16;
  83992. }
  83993. throw new Error(context + ": Invalid type " + type);
  83994. };
  83995. GLTFLoader.prototype._compileMaterialAsync = function (babylonMaterial, babylonMesh, onSuccess) {
  83996. var _this = this;
  83997. if (this._parent.useClipPlane) {
  83998. babylonMaterial.forceCompilation(babylonMesh, function () {
  83999. babylonMaterial.forceCompilation(babylonMesh, function () {
  84000. _this._tryCatchOnError(onSuccess);
  84001. }, { clipPlane: true });
  84002. });
  84003. }
  84004. else {
  84005. babylonMaterial.forceCompilation(babylonMesh, function () {
  84006. _this._tryCatchOnError(onSuccess);
  84007. });
  84008. }
  84009. };
  84010. GLTFLoader.prototype._compileMaterialsAsync = function (onSuccess) {
  84011. if (!this._parent.compileMaterials || !this._gltf.materials) {
  84012. onSuccess();
  84013. return;
  84014. }
  84015. var meshes = this._getMeshes();
  84016. var remaining = 0;
  84017. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  84018. var mesh = meshes_1[_i];
  84019. if (mesh.material instanceof BABYLON.MultiMaterial) {
  84020. for (var _a = 0, _b = mesh.material.subMaterials; _a < _b.length; _a++) {
  84021. var subMaterial = _b[_a];
  84022. if (subMaterial) {
  84023. remaining++;
  84024. }
  84025. }
  84026. }
  84027. else if (mesh.material) {
  84028. remaining++;
  84029. }
  84030. }
  84031. if (remaining === 0) {
  84032. onSuccess();
  84033. return;
  84034. }
  84035. for (var _c = 0, meshes_2 = meshes; _c < meshes_2.length; _c++) {
  84036. var mesh = meshes_2[_c];
  84037. if (mesh.material instanceof BABYLON.MultiMaterial) {
  84038. for (var _d = 0, _e = mesh.material.subMaterials; _d < _e.length; _d++) {
  84039. var subMaterial = _e[_d];
  84040. if (subMaterial) {
  84041. this._compileMaterialAsync(subMaterial, mesh, function () {
  84042. if (--remaining === 0) {
  84043. onSuccess();
  84044. }
  84045. });
  84046. }
  84047. }
  84048. }
  84049. else if (mesh.material) {
  84050. this._compileMaterialAsync(mesh.material, mesh, function () {
  84051. if (--remaining === 0) {
  84052. onSuccess();
  84053. }
  84054. });
  84055. }
  84056. }
  84057. };
  84058. GLTFLoader.prototype._compileShadowGeneratorsAsync = function (onSuccess) {
  84059. var _this = this;
  84060. if (!this._parent.compileShadowGenerators) {
  84061. onSuccess();
  84062. return;
  84063. }
  84064. var lights = this._babylonScene.lights;
  84065. var remaining = 0;
  84066. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  84067. var light = lights_1[_i];
  84068. var generator = light.getShadowGenerator();
  84069. if (generator) {
  84070. remaining++;
  84071. }
  84072. }
  84073. if (remaining === 0) {
  84074. onSuccess();
  84075. return;
  84076. }
  84077. for (var _a = 0, lights_2 = lights; _a < lights_2.length; _a++) {
  84078. var light = lights_2[_a];
  84079. var generator = light.getShadowGenerator();
  84080. if (generator) {
  84081. generator.forceCompilation(function () {
  84082. if (--remaining === 0) {
  84083. _this._tryCatchOnError(onSuccess);
  84084. }
  84085. });
  84086. }
  84087. }
  84088. };
  84089. GLTFLoader.Extensions = {};
  84090. return GLTFLoader;
  84091. }());
  84092. GLTF2.GLTFLoader = GLTFLoader;
  84093. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  84094. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  84095. })(BABYLON || (BABYLON = {}));
  84096. //# sourceMappingURL=babylon.glTFLoader.js.map
  84097. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84098. var BABYLON;
  84099. (function (BABYLON) {
  84100. var GLTF2;
  84101. (function (GLTF2) {
  84102. /**
  84103. * Utils functions for GLTF
  84104. */
  84105. var GLTFUtils = /** @class */ (function () {
  84106. function GLTFUtils() {
  84107. }
  84108. /**
  84109. * If the uri is a base64 string
  84110. * @param uri: the uri to test
  84111. */
  84112. GLTFUtils.IsBase64 = function (uri) {
  84113. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  84114. };
  84115. /**
  84116. * Decode the base64 uri
  84117. * @param uri: the uri to decode
  84118. */
  84119. GLTFUtils.DecodeBase64 = function (uri) {
  84120. var decodedString = atob(uri.split(",")[1]);
  84121. var bufferLength = decodedString.length;
  84122. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  84123. for (var i = 0; i < bufferLength; i++) {
  84124. bufferView[i] = decodedString.charCodeAt(i);
  84125. }
  84126. return bufferView.buffer;
  84127. };
  84128. GLTFUtils.ValidateUri = function (uri) {
  84129. return (uri.indexOf("..") === -1);
  84130. };
  84131. return GLTFUtils;
  84132. }());
  84133. GLTF2.GLTFUtils = GLTFUtils;
  84134. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  84135. })(BABYLON || (BABYLON = {}));
  84136. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  84137. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84138. var BABYLON;
  84139. (function (BABYLON) {
  84140. var GLTF2;
  84141. (function (GLTF2) {
  84142. var GLTFLoaderExtension = /** @class */ (function () {
  84143. function GLTFLoaderExtension() {
  84144. this.enabled = true;
  84145. }
  84146. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  84147. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  84148. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  84149. GLTFLoaderExtension.prototype._loadExtension = function (context, property, action) {
  84150. var _this = this;
  84151. if (!property.extensions) {
  84152. return false;
  84153. }
  84154. var extension = property.extensions[this.name];
  84155. if (!extension) {
  84156. return false;
  84157. }
  84158. // Clear out the extension before executing the action to avoid recursing into the same property.
  84159. property.extensions[this.name] = undefined;
  84160. action(context + "extensions/" + this.name, extension, function () {
  84161. // Restore the extension after completing the action.
  84162. property.extensions[_this.name] = extension;
  84163. });
  84164. return true;
  84165. };
  84166. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  84167. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  84168. };
  84169. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  84170. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  84171. };
  84172. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  84173. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  84174. };
  84175. GLTFLoaderExtension._ApplyExtensions = function (action) {
  84176. var extensions = GLTFLoaderExtension._Extensions;
  84177. if (!extensions) {
  84178. return false;
  84179. }
  84180. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  84181. var extension = extensions_1[_i];
  84182. if (extension.enabled && action(extension)) {
  84183. return true;
  84184. }
  84185. }
  84186. return false;
  84187. };
  84188. //
  84189. // Utilities
  84190. //
  84191. GLTFLoaderExtension._Extensions = [];
  84192. return GLTFLoaderExtension;
  84193. }());
  84194. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  84195. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  84196. })(BABYLON || (BABYLON = {}));
  84197. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  84198. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  84199. var BABYLON;
  84200. (function (BABYLON) {
  84201. var GLTF2;
  84202. (function (GLTF2) {
  84203. var Extensions;
  84204. (function (Extensions) {
  84205. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  84206. var MSFTLOD = /** @class */ (function (_super) {
  84207. __extends(MSFTLOD, _super);
  84208. function MSFTLOD() {
  84209. var _this = _super !== null && _super.apply(this, arguments) || this;
  84210. /**
  84211. * Specify the minimal delay between LODs in ms (default = 250)
  84212. */
  84213. _this.Delay = 250;
  84214. return _this;
  84215. }
  84216. Object.defineProperty(MSFTLOD.prototype, "name", {
  84217. get: function () {
  84218. return "MSFT_lod";
  84219. },
  84220. enumerable: true,
  84221. configurable: true
  84222. });
  84223. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  84224. return this._loadExtension(context, node, function (context, extension, onComplete) {
  84225. for (var i = extension.ids.length - 1; i >= 0; i--) {
  84226. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, extension.ids[i]);
  84227. if (!lodNode) {
  84228. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  84229. }
  84230. loader._traverseNode(context, lodNode, action, parentNode);
  84231. }
  84232. loader._traverseNode(context, node, action, parentNode);
  84233. onComplete();
  84234. });
  84235. };
  84236. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  84237. var _this = this;
  84238. return this._loadExtension(context, node, function (context, extension, onComplete) {
  84239. var nodes = [node];
  84240. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  84241. var index = _a[_i];
  84242. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  84243. if (!lodNode) {
  84244. throw new Error(context + ": Failed to find node " + index);
  84245. }
  84246. nodes.push(lodNode);
  84247. }
  84248. loader._addLoaderPendingData(node);
  84249. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  84250. loader._removeLoaderPendingData(node);
  84251. onComplete();
  84252. });
  84253. });
  84254. };
  84255. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  84256. var _this = this;
  84257. loader._whenAction(function () {
  84258. loader._loadNode(context, nodes[index]);
  84259. }, function () {
  84260. if (index !== nodes.length - 1) {
  84261. var previousNode = nodes[index + 1];
  84262. previousNode.babylonMesh.setEnabled(false);
  84263. }
  84264. if (index === 0) {
  84265. onComplete();
  84266. return;
  84267. }
  84268. setTimeout(function () {
  84269. loader._tryCatchOnError(function () {
  84270. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  84271. });
  84272. }, _this.Delay);
  84273. });
  84274. };
  84275. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  84276. var _this = this;
  84277. return this._loadExtension(context, material, function (context, extension, onComplete) {
  84278. var materials = [material];
  84279. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  84280. var index = _a[_i];
  84281. var lodMaterial = GLTF2.GLTFLoader._GetProperty(loader._gltf.materials, index);
  84282. if (!lodMaterial) {
  84283. throw new Error(context + ": Failed to find material " + index);
  84284. }
  84285. materials.push(lodMaterial);
  84286. }
  84287. loader._addLoaderPendingData(material);
  84288. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  84289. loader._removeLoaderPendingData(material);
  84290. onComplete();
  84291. });
  84292. });
  84293. };
  84294. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  84295. var _this = this;
  84296. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  84297. if (index === materials.length - 1) {
  84298. assign(babylonMaterial, isNew);
  84299. // Load the next LOD when the loader is ready to render.
  84300. loader._executeWhenRenderReady(function () {
  84301. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  84302. });
  84303. }
  84304. else {
  84305. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  84306. assign(babylonMaterial, isNew);
  84307. if (index === 0) {
  84308. onComplete();
  84309. }
  84310. else {
  84311. setTimeout(function () {
  84312. loader._tryCatchOnError(function () {
  84313. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  84314. });
  84315. }, _this.Delay);
  84316. }
  84317. });
  84318. }
  84319. });
  84320. };
  84321. return MSFTLOD;
  84322. }(GLTF2.GLTFLoaderExtension));
  84323. Extensions.MSFTLOD = MSFTLOD;
  84324. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  84325. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  84326. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  84327. })(BABYLON || (BABYLON = {}));
  84328. //# sourceMappingURL=MSFT_lod.js.map
  84329. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  84330. var BABYLON;
  84331. (function (BABYLON) {
  84332. var GLTF2;
  84333. (function (GLTF2) {
  84334. var Extensions;
  84335. (function (Extensions) {
  84336. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  84337. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  84338. function KHRMaterialsPbrSpecularGlossiness() {
  84339. return _super !== null && _super.apply(this, arguments) || this;
  84340. }
  84341. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  84342. get: function () {
  84343. return "KHR_materials_pbrSpecularGlossiness";
  84344. },
  84345. enumerable: true,
  84346. configurable: true
  84347. });
  84348. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  84349. var _this = this;
  84350. return this._loadExtension(context, material, function (context, extension, onComplete) {
  84351. loader._createPbrMaterial(material);
  84352. loader._loadMaterialBaseProperties(context, material);
  84353. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  84354. assign(material.babylonMaterial, true);
  84355. onComplete();
  84356. });
  84357. };
  84358. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  84359. var babylonMaterial = material.babylonMaterial;
  84360. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  84361. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  84362. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  84363. if (properties.diffuseTexture) {
  84364. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.diffuseTexture.index);
  84365. if (!texture) {
  84366. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  84367. }
  84368. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  84369. }
  84370. if (properties.specularGlossinessTexture) {
  84371. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.specularGlossinessTexture.index);
  84372. if (!texture) {
  84373. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  84374. }
  84375. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  84376. babylonMaterial.reflectivityTexture.hasAlpha = true;
  84377. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  84378. }
  84379. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  84380. };
  84381. return KHRMaterialsPbrSpecularGlossiness;
  84382. }(GLTF2.GLTFLoaderExtension));
  84383. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  84384. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  84385. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  84386. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  84387. })(BABYLON || (BABYLON = {}));
  84388. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  84389. (function universalModuleDefinition(root, factory) {
  84390. var f = factory();
  84391. if (root && root["BABYLON"]) {
  84392. return;
  84393. }
  84394. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  84395. globalObject["BABYLON"] = f;
  84396. if(typeof exports === 'object' && typeof module === 'object')
  84397. module.exports = f;
  84398. else if(typeof define === 'function' && define.amd)
  84399. define(["BABYLON"], factory);
  84400. else if(typeof exports === 'object')
  84401. exports["BABYLON"] = f;
  84402. else {
  84403. root["BABYLON"] = f;
  84404. }
  84405. })(this, function() {
  84406. return BABYLON;
  84407. });